diff --git a/docs/sync-ux-acceptance.md b/docs/sync-ux-acceptance.md new file mode 100644 index 0000000..8176390 --- /dev/null +++ b/docs/sync-ux-acceptance.md @@ -0,0 +1,28 @@ +# Sync UI acceptance in isolated Obsidian + +`test/workspaceView.test.ts` and `test/settingsTab.test.ts` exercise the real renderers and handlers in jsdom. Run `npm test` and `npm run lint`. + +For visual checks, `scripts/test-sync-layout.cjs` drives an **isolated, disposable** Obsidian instance over Playwright CDP. Never attach it to a personal vault. It stops background sync and injects presentation state; it does not enroll or call a live Connect service. + +## Prepare + +1. Build the plugin and copy `main.js`, `manifest.json`, and `styles.css` into a disposable vault's `.obsidian/plugins/mdbase-obsidian/`. Enable the plugin in that vault. +2. Use a separate Obsidian app copy and profile. The profile's `obsidian.json` should list only the disposable vault, with `open: true`. Launch with `--no-sandbox --ozone-platform=wayland --user-data-dir= --password-store=basic --remote-debugging-port=`. +3. Create the opt-in marker `.obsidian/mdbase-ux-disposable` in the disposable vault. The script refuses unmarked vaults and checks the attached vault's exact path before injecting state. +4. Make that isolated window visible so Wayland can paint screenshots. Do not drive another agent's window. + +## Run + +```sh +MDBASE_UX_CDP_URL=http://127.0.0.1:42001 \ +MDBASE_UX_VAULT=/absolute/path/to/disposable-vault \ +MDBASE_UX_SHOTS=/absolute/path/to/screenshots \ +MDBASE_UX_PLAYWRIGHT=/absolute/path/to/node_modules/@playwright/test \ +node scripts/test-sync-layout.cjs after-layout +``` + +`MDBASE_UX_PLAYWRIGHT` can be omitted if Playwright is already resolvable. It is not a plugin runtime dependency. + +The audit captures 14 states at 1100px and 390px, in dark and light themes: healthy, offline, sign-in, copied device, paused, unexpected failure, progress, first-sync review, deletion-burst review, rebuild, unresolved conflict, pinned conflict history, enrollment, and local upload. Desktop sidebars are collapsed for realistic narrow panes. Assertions reject horizontal overflow and primary/dismiss targets below 44px in narrow panes. Long, unbroken paths are intentional. `*-checks.json` records the measured bounds; the command exits nonzero on a regression. + +Review the PNGs as well as the assertions. Diff panels may scroll horizontally within their own surface; the workspace itself must not. Stop the isolated instance after testing and discard its app/profile/vault. Injected profile state is ephemeral and must never be saved as real credentials. diff --git a/main.js b/main.js index 32d9abb..ffe00cc 100644 --- a/main.js +++ b/main.js @@ -3,100 +3,100 @@ THIS IS A GENERATED/BUNDLED FILE BY ESBUILD if you want to view the source, please visit the github repository of this plugin */ -var Zx=Object.create;var Pa=Object.defineProperty;var eE=Object.getOwnPropertyDescriptor;var tE=Object.getOwnPropertyNames;var rE=Object.getPrototypeOf,nE=Object.prototype.hasOwnProperty;var oy=(r,e)=>()=>(r&&(e=r(r=0)),e);var A=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ay=(r,e)=>{for(var t in e)Pa(r,t,{get:e[t],enumerable:!0})},cy=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of tE(e))!nE.call(r,i)&&i!==t&&Pa(r,i,{get:()=>e[i],enumerable:!(n=eE(e,i))||n.enumerable});return r};var Kn=(r,e,t)=>(t=r!=null?Zx(rE(r)):{},cy(e||!r||!r.__esModule?Pa(t,"default",{value:r,enumerable:!0}):t,r)),iE=r=>cy(Pa({},"__esModule",{value:!0}),r);var qs=A(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.regexpCode=se.getEsmExportName=se.getProperty=se.safeStringify=se.stringify=se.strConcat=se.addCodeArg=se.str=se._=se.nil=se._Code=se.Name=se.IDENTIFIER=se._CodeOrName=void 0;var Fs=class{};se._CodeOrName=Fs;se.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Gn=class extends Fs{constructor(e){if(super(),!se.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};se.Name=Gn;var Ot=class extends Fs{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((t,n)=>`${t}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((t,n)=>(n instanceof Gn&&(t[n.str]=(t[n.str]||0)+1),t),{})}};se._Code=Ot;se.nil=new Ot("");function uy(r,...e){let t=[r[0]],n=0;for(;n{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.ValueScope=dt.ValueScopeName=dt.Scope=dt.varKinds=dt.UsedValueState=void 0;var lt=qs(),jd=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Ra;(function(r){r[r.Started=0]="Started",r[r.Completed=1]="Completed"})(Ra||(dt.UsedValueState=Ra={}));dt.varKinds={const:new lt.Name("const"),let:new lt.Name("let"),var:new lt.Name("var")};var Ia=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof lt.Name?e:this.name(e)}name(e){return new lt.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){var t,n;if(!((n=(t=this._parent)===null||t===void 0?void 0:t._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};dt.Scope=Ia;var Oa=class extends lt.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:n}){this.value=e,this.scopePath=(0,lt._)`.${new lt.Name(t)}[${n}]`}};dt.ValueScopeName=Oa;var vE=(0,lt._)`\n`,qd=class extends Ia{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?vE:lt.nil}}get(){return this._scope}name(e){return new Oa(e,this._newName(e))}value(e,t){var n;if(t.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:s}=i,o=(n=t.key)!==null&&n!==void 0?n:t.ref,a=this._values[s];if(a){let u=a.get(o);if(u)return u}else a=this._values[s]=new Map;a.set(o,i);let c=this._scope[s]||(this._scope[s]=[]),l=c.length;return c[l]=t.ref,i.setValue(t,{property:s,itemIndex:l}),i}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,lt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},t,n)}_reduceValues(e,t,n={},i){let s=lt.nil;for(let o in e){let a=e[o];if(!a)continue;let c=n[o]=n[o]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,Ra.Started);let u=t(l);if(u){let d=this.opts.es5?dt.varKinds.var:dt.varKinds.const;s=(0,lt._)`${s}${d} ${l} = ${u};${this.opts._n}`}else if(u=i?.(l))s=(0,lt._)`${s}${u}${this.opts._n}`;else throw new jd(l);c.set(l,Ra.Completed)})}return s}};dt.ValueScope=qd});var U=A(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.or=Y.and=Y.not=Y.CodeGen=Y.operators=Y.varKinds=Y.ValueScopeName=Y.ValueScope=Y.Scope=Y.Name=Y.regexpCode=Y.stringify=Y.getProperty=Y.nil=Y.strConcat=Y.str=Y._=void 0;var re=qs(),Gt=Bd(),an=qs();Object.defineProperty(Y,"_",{enumerable:!0,get:function(){return an._}});Object.defineProperty(Y,"str",{enumerable:!0,get:function(){return an.str}});Object.defineProperty(Y,"strConcat",{enumerable:!0,get:function(){return an.strConcat}});Object.defineProperty(Y,"nil",{enumerable:!0,get:function(){return an.nil}});Object.defineProperty(Y,"getProperty",{enumerable:!0,get:function(){return an.getProperty}});Object.defineProperty(Y,"stringify",{enumerable:!0,get:function(){return an.stringify}});Object.defineProperty(Y,"regexpCode",{enumerable:!0,get:function(){return an.regexpCode}});Object.defineProperty(Y,"Name",{enumerable:!0,get:function(){return an.Name}});var Fa=Bd();Object.defineProperty(Y,"Scope",{enumerable:!0,get:function(){return Fa.Scope}});Object.defineProperty(Y,"ValueScope",{enumerable:!0,get:function(){return Fa.ValueScope}});Object.defineProperty(Y,"ValueScopeName",{enumerable:!0,get:function(){return Fa.ValueScopeName}});Object.defineProperty(Y,"varKinds",{enumerable:!0,get:function(){return Fa.varKinds}});Y.operators={GT:new re._Code(">"),GTE:new re._Code(">="),LT:new re._Code("<"),LTE:new re._Code("<="),EQ:new re._Code("==="),NEQ:new re._Code("!=="),NOT:new re._Code("!"),OR:new re._Code("||"),AND:new re._Code("&&"),ADD:new re._Code("+")};var Lr=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},Ud=class extends Lr{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let n=e?Gt.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=Mi(this.rhs,e,t)),this}get names(){return this.rhs instanceof re._CodeOrName?this.rhs.names:{}}},Da=class extends Lr{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(!(this.lhs instanceof re.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Mi(this.rhs,e,t),this}get names(){let e=this.lhs instanceof re.Name?{}:{...this.lhs.names};return La(e,this.rhs)}},Vd=class extends Da{constructor(e,t,n,i){super(e,n,i),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Hd=class extends Lr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},zd=class extends Lr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Kd=class extends Lr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Wd=class extends Lr{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=Mi(this.code,e,t),this}get names(){return this.code instanceof re._CodeOrName?this.code.names:{}}},Bs=class extends Lr{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,i=n.length;for(;i--;){let s=n[i];s.optimizeNames(e,t)||(wE(e,s.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>Xn(e,t.names),{})}},Fr=class extends Bs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Gd=class extends Bs{},Ci=class extends Fr{};Ci.kind="else";var Jn=class r extends Fr{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let t=this.else;if(t){let n=t.optimizeNodes();t=this.else=Array.isArray(n)?new Ci(n):n}if(t)return e===!1?t instanceof r?t:t.nodes:this.nodes.length?this:new r(py(e),t instanceof r?[t]:t.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,t){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,t),!!(super.optimizeNames(e,t)||this.else))return this.condition=Mi(this.condition,e,t),this}get names(){let e=super.names;return La(e,this.condition),this.else&&Xn(e,this.else.names),e}};Jn.kind="if";var Yn=class extends Fr{};Yn.kind="for";var Jd=class extends Yn{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=Mi(this.iteration,e,t),this}get names(){return Xn(super.names,this.iteration.names)}},Yd=class extends Yn{constructor(e,t,n,i){super(),this.varKind=e,this.name=t,this.from=n,this.to=i}render(e){let t=e.es5?Gt.varKinds.var:this.varKind,{name:n,from:i,to:s}=this;return`for(${t} ${n}=${i}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=La(super.names,this.from);return La(e,this.to)}},Na=class extends Yn{constructor(e,t,n,i){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=i}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=Mi(this.iterable,e,t),this}get names(){return Xn(super.names,this.iterable.names)}},Us=class extends Fr{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Us.kind="func";var Vs=class extends Bs{render(e){return"return "+super.render(e)}};Vs.kind="return";var Xd=class extends Fr{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(t=this.finally)===null||t===void 0||t.optimizeNodes(),this}optimizeNames(e,t){var n,i;return super.optimizeNames(e,t),(n=this.catch)===null||n===void 0||n.optimizeNames(e,t),(i=this.finally)===null||i===void 0||i.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&Xn(e,this.catch.names),this.finally&&Xn(e,this.finally.names),e}},Hs=class extends Fr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Hs.kind="catch";var zs=class extends Fr{render(e){return"finally"+super.render(e)}};zs.kind="finally";var Qd=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?` -`:""},this._extScope=e,this._scope=new Gt.Scope({parent:e}),this._nodes=[new Gd]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,i){let s=this._scope.toName(t);return n!==void 0&&i&&(this._constants[s.str]=n),this._leafNode(new Ud(e,s,n)),s}const(e,t,n){return this._def(Gt.varKinds.const,e,t,n)}let(e,t,n){return this._def(Gt.varKinds.let,e,t,n)}var(e,t,n){return this._def(Gt.varKinds.var,e,t,n)}assign(e,t,n){return this._leafNode(new Da(e,t,n))}add(e,t){return this._leafNode(new Vd(e,Y.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==re.nil&&this._leafNode(new Wd(e)),this}object(...e){let t=["{"];for(let[n,i]of e)t.length>1&&t.push(","),t.push(n),(n!==i||this.opts.es5)&&(t.push(":"),(0,re.addCodeArg)(t,i));return t.push("}"),new re._Code(t)}if(e,t,n){if(this._blockNode(new Jn(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Jn(e))}else(){return this._elseNode(new Ci)}endIf(){return this._endBlockNode(Jn,Ci)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new Jd(e),t)}forRange(e,t,n,i,s=this.opts.es5?Gt.varKinds.var:Gt.varKinds.let){let o=this._scope.toName(e);return this._for(new Yd(s,o,t,n),()=>i(o))}forOf(e,t,n,i=Gt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let o=t instanceof re.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0,re._)`${o}.length`,a=>{this.var(s,(0,re._)`${o}[${a}]`),n(s)})}return this._for(new Na("of",i,s,t),()=>n(s))}forIn(e,t,n,i=this.opts.es5?Gt.varKinds.var:Gt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,re._)`Object.keys(${t})`,n);let s=this._scope.toName(e);return this._for(new Na("in",i,s,t),()=>n(s))}endFor(){return this._endBlockNode(Yn)}label(e){return this._leafNode(new Hd(e))}break(e){return this._leafNode(new zd(e))}return(e){let t=new Vs;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Vs)}try(e,t,n){if(!t&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new Xd;if(this._blockNode(i),this.code(e),t){let s=this.name("e");this._currNode=i.catch=new Hs(s),t(s)}return n&&(this._currNode=i.finally=new zs,this.code(n)),this._endBlockNode(Hs,zs)}throw(e){return this._leafNode(new Kd(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=re.nil,n,i){return this._blockNode(new Us(e,t,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(Us)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof Jn))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};Y.CodeGen=Qd;function Xn(r,e){for(let t in e)r[t]=(r[t]||0)+(e[t]||0);return r}function La(r,e){return e instanceof re._CodeOrName?Xn(r,e.names):r}function Mi(r,e,t){if(r instanceof re.Name)return n(r);if(!i(r))return r;return new re._Code(r._items.reduce((s,o)=>(o instanceof re.Name&&(o=n(o)),o instanceof re._Code?s.push(...o._items):s.push(o),s),[]));function n(s){let o=t[s.str];return o===void 0||e[s.str]!==1?s:(delete e[s.str],o)}function i(s){return s instanceof re._Code&&s._items.some(o=>o instanceof re.Name&&e[o.str]===1&&t[o.str]!==void 0)}}function wE(r,e){for(let t in e)r[t]=(r[t]||0)-(e[t]||0)}function py(r){return typeof r=="boolean"||typeof r=="number"||r===null?!r:(0,re._)`!${Zd(r)}`}Y.not=py;var _E=hy(Y.operators.AND);function SE(...r){return r.reduce(_E)}Y.and=SE;var $E=hy(Y.operators.OR);function xE(...r){return r.reduce($E)}Y.or=xE;function hy(r){return(e,t)=>e===re.nil?t:t===re.nil?e:(0,re._)`${Zd(e)} ${r} ${Zd(t)}`}function Zd(r){return r instanceof re.Name?r:(0,re._)`(${r})`}});var Q=A(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.checkStrictMode=X.getErrorPath=X.Type=X.useFunc=X.setEvaluated=X.evaluatedPropsToName=X.mergeEvaluated=X.eachItem=X.unescapeJsonPointer=X.escapeJsonPointer=X.escapeFragment=X.unescapeFragment=X.schemaRefOrVal=X.schemaHasRulesButRef=X.schemaHasRules=X.checkUnknownRules=X.alwaysValidSchema=X.toHash=void 0;var de=U(),EE=qs();function AE(r){let e={};for(let t of r)e[t]=!0;return e}X.toHash=AE;function kE(r,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(gy(r,e),!by(e,r.self.RULES.all))}X.alwaysValidSchema=kE;function gy(r,e=r.schema){let{opts:t,self:n}=r;if(!t.strictSchema||typeof e=="boolean")return;let i=n.RULES.keywords;for(let s in e)i[s]||_y(r,`unknown keyword: "${s}"`)}X.checkUnknownRules=gy;function by(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(e[t])return!0;return!1}X.schemaHasRules=by;function PE(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(t!=="$ref"&&e.all[t])return!0;return!1}X.schemaHasRulesButRef=PE;function CE({topSchemaRef:r,schemaPath:e},t,n,i){if(!i){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return(0,de._)`${t}`}return(0,de._)`${r}${e}${(0,de.getProperty)(n)}`}X.schemaRefOrVal=CE;function ME(r){return vy(decodeURIComponent(r))}X.unescapeFragment=ME;function TE(r){return encodeURIComponent(tu(r))}X.escapeFragment=TE;function tu(r){return typeof r=="number"?`${r}`:r.replace(/~/g,"~0").replace(/\//g,"~1")}X.escapeJsonPointer=tu;function vy(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}X.unescapeJsonPointer=vy;function RE(r,e){if(Array.isArray(r))for(let t of r)e(t);else e(r)}X.eachItem=RE;function my({mergeNames:r,mergeToName:e,mergeValues:t,resultToName:n}){return(i,s,o,a)=>{let c=o===void 0?s:o instanceof de.Name?(s instanceof de.Name?r(i,s,o):e(i,s,o),o):s instanceof de.Name?(e(i,o,s),s):t(s,o);return a===de.Name&&!(c instanceof de.Name)?n(i,c):c}}X.mergeEvaluated={props:my({mergeNames:(r,e,t)=>r.if((0,de._)`${t} !== true && ${e} !== undefined`,()=>{r.if((0,de._)`${e} === true`,()=>r.assign(t,!0),()=>r.assign(t,(0,de._)`${t} || {}`).code((0,de._)`Object.assign(${t}, ${e})`))}),mergeToName:(r,e,t)=>r.if((0,de._)`${t} !== true`,()=>{e===!0?r.assign(t,!0):(r.assign(t,(0,de._)`${t} || {}`),ru(r,t,e))}),mergeValues:(r,e)=>r===!0?!0:{...r,...e},resultToName:wy}),items:my({mergeNames:(r,e,t)=>r.if((0,de._)`${t} !== true && ${e} !== undefined`,()=>r.assign(t,(0,de._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(r,e,t)=>r.if((0,de._)`${t} !== true`,()=>r.assign(t,e===!0?!0:(0,de._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(r,e)=>r===!0?!0:Math.max(r,e),resultToName:(r,e)=>r.var("items",e)})};function wy(r,e){if(e===!0)return r.var("props",!0);let t=r.var("props",(0,de._)`{}`);return e!==void 0&&ru(r,t,e),t}X.evaluatedPropsToName=wy;function ru(r,e,t){Object.keys(t).forEach(n=>r.assign((0,de._)`${e}${(0,de.getProperty)(n)}`,!0))}X.setEvaluated=ru;var yy={};function IE(r,e){return r.scopeValue("func",{ref:e,code:yy[e.code]||(yy[e.code]=new EE._Code(e.code))})}X.useFunc=IE;var eu;(function(r){r[r.Num=0]="Num",r[r.Str=1]="Str"})(eu||(X.Type=eu={}));function OE(r,e,t){if(r instanceof de.Name){let n=e===eu.Num;return t?n?(0,de._)`"[" + ${r} + "]"`:(0,de._)`"['" + ${r} + "']"`:n?(0,de._)`"/" + ${r}`:(0,de._)`"/" + ${r}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0,de.getProperty)(r).toString():"/"+tu(r)}X.getErrorPath=OE;function _y(r,e,t=r.opts.strictSchema){if(t){if(e=`strict mode: ${e}`,t===!0)throw new Error(e);r.self.logger.warn(e)}}X.checkStrictMode=_y});var Dt=A(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});var Ue=U(),DE={data:new Ue.Name("data"),valCxt:new Ue.Name("valCxt"),instancePath:new Ue.Name("instancePath"),parentData:new Ue.Name("parentData"),parentDataProperty:new Ue.Name("parentDataProperty"),rootData:new Ue.Name("rootData"),dynamicAnchors:new Ue.Name("dynamicAnchors"),vErrors:new Ue.Name("vErrors"),errors:new Ue.Name("errors"),this:new Ue.Name("this"),self:new Ue.Name("self"),scope:new Ue.Name("scope"),json:new Ue.Name("json"),jsonPos:new Ue.Name("jsonPos"),jsonLen:new Ue.Name("jsonLen"),jsonPart:new Ue.Name("jsonPart")};nu.default=DE});var Ks=A(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.extendErrors=Ve.resetErrorsCount=Ve.reportExtraError=Ve.reportError=Ve.keyword$DataError=Ve.keywordError=void 0;var ie=U(),ja=Q(),Ze=Dt();Ve.keywordError={message:({keyword:r})=>(0,ie.str)`must pass "${r}" keyword validation`};Ve.keyword$DataError={message:({keyword:r,schemaType:e})=>e?(0,ie.str)`"${r}" keyword must be ${e} ($data)`:(0,ie.str)`"${r}" keyword is invalid ($data)`};function NE(r,e=Ve.keywordError,t,n){let{it:i}=r,{gen:s,compositeRule:o,allErrors:a}=i,c=xy(r,e,t);n??(o||a)?Sy(s,c):$y(i,(0,ie._)`[${c}]`)}Ve.reportError=NE;function LE(r,e=Ve.keywordError,t){let{it:n}=r,{gen:i,compositeRule:s,allErrors:o}=n,a=xy(r,e,t);Sy(i,a),s||o||$y(n,Ze.default.vErrors)}Ve.reportExtraError=LE;function FE(r,e){r.assign(Ze.default.errors,e),r.if((0,ie._)`${Ze.default.vErrors} !== null`,()=>r.if(e,()=>r.assign((0,ie._)`${Ze.default.vErrors}.length`,e),()=>r.assign(Ze.default.vErrors,null)))}Ve.resetErrorsCount=FE;function jE({gen:r,keyword:e,schemaValue:t,data:n,errsCount:i,it:s}){if(i===void 0)throw new Error("ajv implementation error");let o=r.name("err");r.forRange("i",i,Ze.default.errors,a=>{r.const(o,(0,ie._)`${Ze.default.vErrors}[${a}]`),r.if((0,ie._)`${o}.instancePath === undefined`,()=>r.assign((0,ie._)`${o}.instancePath`,(0,ie.strConcat)(Ze.default.instancePath,s.errorPath))),r.assign((0,ie._)`${o}.schemaPath`,(0,ie.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(r.assign((0,ie._)`${o}.schema`,t),r.assign((0,ie._)`${o}.data`,n))})}Ve.extendErrors=jE;function Sy(r,e){let t=r.const("err",e);r.if((0,ie._)`${Ze.default.vErrors} === null`,()=>r.assign(Ze.default.vErrors,(0,ie._)`[${t}]`),(0,ie._)`${Ze.default.vErrors}.push(${t})`),r.code((0,ie._)`${Ze.default.errors}++`)}function $y(r,e){let{gen:t,validateName:n,schemaEnv:i}=r;i.$async?t.throw((0,ie._)`new ${r.ValidationError}(${e})`):(t.assign((0,ie._)`${n}.errors`,e),t.return(!1))}var Qn={keyword:new ie.Name("keyword"),schemaPath:new ie.Name("schemaPath"),params:new ie.Name("params"),propertyName:new ie.Name("propertyName"),message:new ie.Name("message"),schema:new ie.Name("schema"),parentSchema:new ie.Name("parentSchema")};function xy(r,e,t){let{createErrors:n}=r.it;return n===!1?(0,ie._)`{}`:qE(r,e,t)}function qE(r,e,t={}){let{gen:n,it:i}=r,s=[BE(i,t),UE(r,t)];return VE(r,e,s),n.object(...s)}function BE({errorPath:r},{instancePath:e}){let t=e?(0,ie.str)`${r}${(0,ja.getErrorPath)(e,ja.Type.Str)}`:r;return[Ze.default.instancePath,(0,ie.strConcat)(Ze.default.instancePath,t)]}function UE({keyword:r,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:n}){let i=n?e:(0,ie.str)`${e}/${r}`;return t&&(i=(0,ie.str)`${i}${(0,ja.getErrorPath)(t,ja.Type.Str)}`),[Qn.schemaPath,i]}function VE(r,{params:e,message:t},n){let{keyword:i,data:s,schemaValue:o,it:a}=r,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;n.push([Qn.keyword,i],[Qn.params,typeof e=="function"?e(r):e||(0,ie._)`{}`]),c.messages&&n.push([Qn.message,typeof t=="function"?t(r):t]),c.verbose&&n.push([Qn.schema,o],[Qn.parentSchema,(0,ie._)`${u}${d}`],[Ze.default.data,s]),l&&n.push([Qn.propertyName,l])}});var Ay=A(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.boolOrEmptySchema=Ti.topBoolOrEmptySchema=void 0;var HE=Ks(),zE=U(),KE=Dt(),WE={message:"boolean schema is false"};function GE(r){let{gen:e,schema:t,validateName:n}=r;t===!1?Ey(r,!1):typeof t=="object"&&t.$async===!0?e.return(KE.default.data):(e.assign((0,zE._)`${n}.errors`,null),e.return(!0))}Ti.topBoolOrEmptySchema=GE;function JE(r,e){let{gen:t,schema:n}=r;n===!1?(t.var(e,!1),Ey(r)):t.var(e,!0)}Ti.boolOrEmptySchema=JE;function Ey(r,e){let{gen:t,data:n}=r,i={gen:t,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:r};(0,HE.reportError)(i,WE,void 0,e)}});var iu=A(Ri=>{"use strict";Object.defineProperty(Ri,"__esModule",{value:!0});Ri.getRules=Ri.isJSONType=void 0;var YE=["string","number","integer","boolean","null","object","array"],XE=new Set(YE);function QE(r){return typeof r=="string"&&XE.has(r)}Ri.isJSONType=QE;function ZE(){let r={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...r,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},r.number,r.string,r.array,r.object],post:{rules:[]},all:{},keywords:{}}}Ri.getRules=ZE});var su=A(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.shouldUseRule=cn.shouldUseGroup=cn.schemaHasRulesForType=void 0;function eA({schema:r,self:e},t){let n=e.RULES.types[t];return n&&n!==!0&&ky(r,n)}cn.schemaHasRulesForType=eA;function ky(r,e){return e.rules.some(t=>Py(r,t))}cn.shouldUseGroup=ky;function Py(r,e){var t;return r[e.keyword]!==void 0||((t=e.definition.implements)===null||t===void 0?void 0:t.some(n=>r[n]!==void 0))}cn.shouldUseRule=Py});var Ws=A(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.reportTypeError=He.checkDataTypes=He.checkDataType=He.coerceAndCheckDataType=He.getJSONTypes=He.getSchemaTypes=He.DataType=void 0;var tA=iu(),rA=su(),nA=Ks(),K=U(),Cy=Q(),Ii;(function(r){r[r.Correct=0]="Correct",r[r.Wrong=1]="Wrong"})(Ii||(He.DataType=Ii={}));function iA(r){let e=My(r.type);if(e.includes("null")){if(r.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&r.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');r.nullable===!0&&e.push("null")}return e}He.getSchemaTypes=iA;function My(r){let e=Array.isArray(r)?r:r?[r]:[];if(e.every(tA.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}He.getJSONTypes=My;function sA(r,e){let{gen:t,data:n,opts:i}=r,s=oA(e,i.coerceTypes),o=e.length>0&&!(s.length===0&&e.length===1&&(0,rA.schemaHasRulesForType)(r,e[0]));if(o){let a=au(e,n,i.strictNumbers,Ii.Wrong);t.if(a,()=>{s.length?aA(r,e,s):cu(r)})}return o}He.coerceAndCheckDataType=sA;var Ty=new Set(["string","number","integer","boolean","null"]);function oA(r,e){return e?r.filter(t=>Ty.has(t)||e==="array"&&t==="array"):[]}function aA(r,e,t){let{gen:n,data:i,opts:s}=r,o=n.let("dataType",(0,K._)`typeof ${i}`),a=n.let("coerced",(0,K._)`undefined`);s.coerceTypes==="array"&&n.if((0,K._)`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,K._)`${i}[0]`).assign(o,(0,K._)`typeof ${i}`).if(au(e,i,s.strictNumbers),()=>n.assign(a,i))),n.if((0,K._)`${a} !== undefined`);for(let l of t)(Ty.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),cu(r),n.endIf(),n.if((0,K._)`${a} !== undefined`,()=>{n.assign(i,a),cA(r,a)});function c(l){switch(l){case"string":n.elseIf((0,K._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,K._)`"" + ${i}`).elseIf((0,K._)`${i} === null`).assign(a,(0,K._)`""`);return;case"number":n.elseIf((0,K._)`${o} == "boolean" || ${i} === null - || (${o} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,K._)`+${i}`);return;case"integer":n.elseIf((0,K._)`${o} === "boolean" || ${i} === null - || (${o} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(a,(0,K._)`+${i}`);return;case"boolean":n.elseIf((0,K._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(a,!1).elseIf((0,K._)`${i} === "true" || ${i} === 1`).assign(a,!0);return;case"null":n.elseIf((0,K._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(a,null);return;case"array":n.elseIf((0,K._)`${o} === "string" || ${o} === "number" - || ${o} === "boolean" || ${i} === null`).assign(a,(0,K._)`[${i}]`)}}}function cA({gen:r,parentData:e,parentDataProperty:t},n){r.if((0,K._)`${e} !== undefined`,()=>r.assign((0,K._)`${e}[${t}]`,n))}function ou(r,e,t,n=Ii.Correct){let i=n===Ii.Correct?K.operators.EQ:K.operators.NEQ,s;switch(r){case"null":return(0,K._)`${e} ${i} null`;case"array":s=(0,K._)`Array.isArray(${e})`;break;case"object":s=(0,K._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=o((0,K._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=o();break;default:return(0,K._)`typeof ${e} ${i} ${r}`}return n===Ii.Correct?s:(0,K.not)(s);function o(a=K.nil){return(0,K.and)((0,K._)`typeof ${e} == "number"`,a,t?(0,K._)`isFinite(${e})`:K.nil)}}He.checkDataType=ou;function au(r,e,t,n){if(r.length===1)return ou(r[0],e,t,n);let i,s=(0,Cy.toHash)(r);if(s.array&&s.object){let o=(0,K._)`typeof ${e} != "object"`;i=s.null?o:(0,K._)`!${e} || ${o}`,delete s.null,delete s.array,delete s.object}else i=K.nil;s.number&&delete s.integer;for(let o in s)i=(0,K.and)(i,ou(o,e,t,n));return i}He.checkDataTypes=au;var lA={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,K._)`{type: ${r}}`:(0,K._)`{type: ${e}}`};function cu(r){let e=dA(r);(0,nA.reportError)(e,lA)}He.reportTypeError=cu;function dA(r){let{gen:e,data:t,schema:n}=r,i=(0,Cy.schemaRefOrVal)(r,n,"type");return{gen:e,keyword:"type",data:t,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:r}}});var Iy=A(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.assignDefaults=void 0;var Oi=U(),uA=Q();function fA(r,e){let{properties:t,items:n}=r.schema;if(e==="object"&&t)for(let i in t)Ry(r,i,t[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,s)=>Ry(r,s,i.default))}qa.assignDefaults=fA;function Ry(r,e,t){let{gen:n,compositeRule:i,data:s,opts:o}=r;if(t===void 0)return;let a=(0,Oi._)`${s}${(0,Oi.getProperty)(e)}`;if(i){(0,uA.checkStrictMode)(r,`default is ignored for: ${a}`);return}let c=(0,Oi._)`${a} === undefined`;o.useDefaults==="empty"&&(c=(0,Oi._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Oi._)`${a} = ${(0,Oi.stringify)(t)}`)}});var Nt=A(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.validateUnion=le.validateArray=le.usePattern=le.callValidateCode=le.schemaProperties=le.allSchemaProperties=le.noPropertyInData=le.propertyInData=le.isOwnProperty=le.hasPropFunc=le.reportMissingProp=le.checkMissingProp=le.checkReportMissingProp=void 0;var me=U(),lu=Q(),ln=Dt(),pA=Q();function hA(r,e){let{gen:t,data:n,it:i}=r;t.if(uu(t,n,e,i.opts.ownProperties),()=>{r.setParams({missingProperty:(0,me._)`${e}`},!0),r.error()})}le.checkReportMissingProp=hA;function mA({gen:r,data:e,it:{opts:t}},n,i){return(0,me.or)(...n.map(s=>(0,me.and)(uu(r,e,s,t.ownProperties),(0,me._)`${i} = ${s}`)))}le.checkMissingProp=mA;function yA(r,e){r.setParams({missingProperty:e},!0),r.error()}le.reportMissingProp=yA;function Oy(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,me._)`Object.prototype.hasOwnProperty`})}le.hasPropFunc=Oy;function du(r,e,t){return(0,me._)`${Oy(r)}.call(${e}, ${t})`}le.isOwnProperty=du;function gA(r,e,t,n){let i=(0,me._)`${e}${(0,me.getProperty)(t)} !== undefined`;return n?(0,me._)`${i} && ${du(r,e,t)}`:i}le.propertyInData=gA;function uu(r,e,t,n){let i=(0,me._)`${e}${(0,me.getProperty)(t)} === undefined`;return n?(0,me.or)(i,(0,me.not)(du(r,e,t))):i}le.noPropertyInData=uu;function Dy(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}le.allSchemaProperties=Dy;function bA(r,e){return Dy(e).filter(t=>!(0,lu.alwaysValidSchema)(r,e[t]))}le.schemaProperties=bA;function vA({schemaCode:r,data:e,it:{gen:t,topSchemaRef:n,schemaPath:i,errorPath:s},it:o},a,c,l){let u=l?(0,me._)`${r}, ${e}, ${n}${i}`:e,d=[[ln.default.instancePath,(0,me.strConcat)(ln.default.instancePath,s)],[ln.default.parentData,o.parentData],[ln.default.parentDataProperty,o.parentDataProperty],[ln.default.rootData,ln.default.rootData]];o.opts.dynamicRef&&d.push([ln.default.dynamicAnchors,ln.default.dynamicAnchors]);let f=(0,me._)`${u}, ${t.object(...d)}`;return c!==me.nil?(0,me._)`${a}.call(${c}, ${f})`:(0,me._)`${a}(${f})`}le.callValidateCode=vA;var wA=(0,me._)`new RegExp`;function _A({gen:r,it:{opts:e}},t){let n=e.unicodeRegExp?"u":"",{regExp:i}=e.code,s=i(t,n);return r.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,me._)`${i.code==="new RegExp"?wA:(0,pA.useFunc)(r,i)}(${t}, ${n})`})}le.usePattern=_A;function SA(r){let{gen:e,data:t,keyword:n,it:i}=r,s=e.name("valid");if(i.allErrors){let a=e.let("valid",!0);return o(()=>e.assign(a,!1)),a}return e.var(s,!0),o(()=>e.break()),s;function o(a){let c=e.const("len",(0,me._)`${t}.length`);e.forRange("i",0,c,l=>{r.subschema({keyword:n,dataProp:l,dataPropType:lu.Type.Num},s),e.if((0,me.not)(s),a)})}}le.validateArray=SA;function $A(r){let{gen:e,schema:t,keyword:n,it:i}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(t.some(c=>(0,lu.alwaysValidSchema)(i,c))&&!i.opts.unevaluated)return;let o=e.let("valid",!1),a=e.name("_valid");e.block(()=>t.forEach((c,l)=>{let u=r.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);e.assign(o,(0,me._)`${o} || ${a}`),r.mergeValidEvaluated(u,a)||e.if((0,me.not)(o))})),r.result(o,()=>r.reset(),()=>r.error(!0))}le.validateUnion=$A});var Fy=A(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.validateKeywordUsage=yr.validSchemaType=yr.funcKeywordCode=yr.macroKeywordCode=void 0;var et=U(),Zn=Dt(),xA=Nt(),EA=Ks();function AA(r,e){let{gen:t,keyword:n,schema:i,parentSchema:s,it:o}=r,a=e.macro.call(o.self,i,s,o),c=Ly(t,n,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);let l=t.name("valid");r.subschema({schema:a,schemaPath:et.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),r.pass(l,()=>r.error(!0))}yr.macroKeywordCode=AA;function kA(r,e){var t;let{gen:n,keyword:i,schema:s,parentSchema:o,$data:a,it:c}=r;CA(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,o,c):e.validate,u=Ly(n,i,l),d=n.let("valid");r.block$data(d,f),r.ok((t=e.valid)!==null&&t!==void 0?t:d);function f(){if(e.errors===!1)h(),e.modifying&&Ny(r),y(()=>r.error());else{let g=e.async?p():m();e.modifying&&Ny(r),y(()=>PA(r,g))}}function p(){let g=n.let("ruleErrs",null);return n.try(()=>h((0,et._)`await `),b=>n.assign(d,!1).if((0,et._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(g,(0,et._)`${b}.errors`),()=>n.throw(b))),g}function m(){let g=(0,et._)`${u}.errors`;return n.assign(g,null),h(et.nil),g}function h(g=e.async?(0,et._)`await `:et.nil){let b=c.opts.passContext?Zn.default.this:Zn.default.self,v=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,et._)`${g}${(0,xA.callValidateCode)(r,u,b,v)}`,e.modifying)}function y(g){var b;n.if((0,et.not)((b=e.valid)!==null&&b!==void 0?b:d),g)}}yr.funcKeywordCode=kA;function Ny(r){let{gen:e,data:t,it:n}=r;e.if(n.parentData,()=>e.assign(t,(0,et._)`${n.parentData}[${n.parentDataProperty}]`))}function PA(r,e){let{gen:t}=r;t.if((0,et._)`Array.isArray(${e})`,()=>{t.assign(Zn.default.vErrors,(0,et._)`${Zn.default.vErrors} === null ? ${e} : ${Zn.default.vErrors}.concat(${e})`).assign(Zn.default.errors,(0,et._)`${Zn.default.vErrors}.length`),(0,EA.extendErrors)(r)},()=>r.error())}function CA({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function Ly(r,e,t){if(t===void 0)throw new Error(`keyword "${e}" failed to compile`);return r.scopeValue("keyword",typeof t=="function"?{ref:t}:{ref:t,code:(0,et.stringify)(t)})}function MA(r,e,t=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(r):n==="object"?r&&typeof r=="object"&&!Array.isArray(r):typeof r==n||t&&typeof r>"u")}yr.validSchemaType=MA;function TA({schema:r,opts:e,self:t,errSchemaPath:n},i,s){if(Array.isArray(i.keyword)?!i.keyword.includes(s):i.keyword!==s)throw new Error("ajv implementation error");let o=i.dependencies;if(o?.some(a=>!Object.prototype.hasOwnProperty.call(r,a)))throw new Error(`parent schema must have dependencies of ${s}: ${o.join(",")}`);if(i.validateSchema&&!i.validateSchema(r[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+t.errorsText(i.validateSchema.errors);if(e.validateSchema==="log")t.logger.error(c);else throw new Error(c)}}yr.validateKeywordUsage=TA});var qy=A(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.extendSubschemaMode=dn.extendSubschemaData=dn.getSubschema=void 0;var gr=U(),jy=Q();function RA(r,{keyword:e,schemaProp:t,schema:n,schemaPath:i,errSchemaPath:s,topSchemaRef:o}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=r.schema[e];return t===void 0?{schema:a,schemaPath:(0,gr._)`${r.schemaPath}${(0,gr.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:a[t],schemaPath:(0,gr._)`${r.schemaPath}${(0,gr.getProperty)(e)}${(0,gr.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,jy.escapeFragment)(t)}`}}if(n!==void 0){if(i===void 0||s===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:o,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}dn.getSubschema=RA;function IA(r,e,{dataProp:t,dataPropType:n,data:i,dataTypes:s,propertyName:o}){if(i!==void 0&&t!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(t!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=e,f=a.let("data",(0,gr._)`${e.data}${(0,gr.getProperty)(t)}`,!0);c(f),r.errorPath=(0,gr.str)`${l}${(0,jy.getErrorPath)(t,n,d.jsPropertySyntax)}`,r.parentDataProperty=(0,gr._)`${t}`,r.dataPathArr=[...u,r.parentDataProperty]}if(i!==void 0){let l=i instanceof gr.Name?i:a.let("data",i,!0);c(l),o!==void 0&&(r.propertyName=o)}s&&(r.dataTypes=s);function c(l){r.data=l,r.dataLevel=e.dataLevel+1,r.dataTypes=[],e.definedProperties=new Set,r.parentData=e.data,r.dataNames=[...e.dataNames,l]}}dn.extendSubschemaData=IA;function OA(r,{jtdDiscriminator:e,jtdMetadata:t,compositeRule:n,createErrors:i,allErrors:s}){n!==void 0&&(r.compositeRule=n),i!==void 0&&(r.createErrors=i),s!==void 0&&(r.allErrors=s),r.jtdDiscriminator=e,r.jtdMetadata=t}dn.extendSubschemaMode=OA});var fu=A((Mj,By)=>{"use strict";By.exports=function r(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return!1;var n,i,s;if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(i=n;i--!==0;)if(!r(e[i],t[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(t).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(t,s[i]))return!1;for(i=n;i--!==0;){var o=s[i];if(!r(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}});var Vy=A((Tj,Uy)=>{"use strict";var un=Uy.exports=function(r,e,t){typeof e=="function"&&(t=e,e={}),t=e.cb||t;var n=typeof t=="function"?t:t.pre||function(){},i=t.post||function(){};Ba(e,n,i,r,"",r)};un.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};un.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};un.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};un.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Ba(r,e,t,n,i,s,o,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,i,s,o,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in un.arrayKeywords)for(var f=0;f{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.getSchemaRefs=ut.resolveUrl=ut.normalizeId=ut._getFullPath=ut.getFullPath=ut.inlineRef=void 0;var NA=Q(),LA=fu(),FA=Vy(),jA=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function qA(r,e=!0){return typeof r=="boolean"?!0:e===!0?!pu(r):e?Hy(r)<=e:!1}ut.inlineRef=qA;var BA=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function pu(r){for(let e in r){if(BA.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(pu)||typeof t=="object"&&pu(t))return!0}return!1}function Hy(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!jA.has(t)&&(typeof r[t]=="object"&&(0,NA.eachItem)(r[t],n=>e+=Hy(n)),e===1/0))return 1/0}return e}function zy(r,e="",t){t!==!1&&(e=Di(e));let n=r.parse(e);return Ky(r,n)}ut.getFullPath=zy;function Ky(r,e){return r.serialize(e).split("#")[0]+"#"}ut._getFullPath=Ky;var UA=/#\/?$/;function Di(r){return r?r.replace(UA,""):""}ut.normalizeId=Di;function VA(r,e,t){return t=Di(t),r.resolve(e,t)}ut.resolveUrl=VA;var HA=/^[a-z_][-a-z0-9._]*$/i;function zA(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:n}=this.opts,i=Di(r[t]||e),s={"":i},o=zy(n,i,!1),a={},c=new Set;return FA(r,{allKeys:!0},(d,f,p,m)=>{if(m===void 0)return;let h=o+f,y=s[m];typeof d[t]=="string"&&(y=g.call(this,d[t])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),s[f]=y;function g(v){let S=this.opts.uriResolver.resolve;if(v=Di(y?S(y,v):v),c.has(v))throw u(v);c.add(v);let _=this.refs[v];return typeof _=="string"&&(_=this.refs[_]),typeof _=="object"?l(d,_.schema,v):v!==Di(h)&&(v[0]==="#"?(l(d,a[v],v),a[v]=d):this.refs[v]=h),v}function b(v){if(typeof v=="string"){if(!HA.test(v))throw new Error(`invalid anchor "${v}"`);g.call(this,`#${v}`)}}}),a;function l(d,f,p){if(f!==void 0&&!LA(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}ut.getSchemaRefs=zA});var Ni=A(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.getData=fn.KeywordCxt=fn.validateFunctionCode=void 0;var Xy=Ay(),Wy=Ws(),mu=su(),Ua=Ws(),KA=Iy(),Ys=Fy(),hu=qy(),j=U(),B=Dt(),WA=Gs(),jr=Q(),Js=Ks();function GA(r){if(eg(r)&&(tg(r),Zy(r))){XA(r);return}Qy(r,()=>(0,Xy.topBoolOrEmptySchema)(r))}fn.validateFunctionCode=GA;function Qy({gen:r,validateName:e,schema:t,schemaEnv:n,opts:i},s){i.code.es5?r.func(e,(0,j._)`${B.default.data}, ${B.default.valCxt}`,n.$async,()=>{r.code((0,j._)`"use strict"; ${Gy(t,i)}`),YA(r,i),r.code(s)}):r.func(e,(0,j._)`${B.default.data}, ${JA(i)}`,n.$async,()=>r.code(Gy(t,i)).code(s))}function JA(r){return(0,j._)`{${B.default.instancePath}="", ${B.default.parentData}, ${B.default.parentDataProperty}, ${B.default.rootData}=${B.default.data}${r.dynamicRef?(0,j._)`, ${B.default.dynamicAnchors}={}`:j.nil}}={}`}function YA(r,e){r.if(B.default.valCxt,()=>{r.var(B.default.instancePath,(0,j._)`${B.default.valCxt}.${B.default.instancePath}`),r.var(B.default.parentData,(0,j._)`${B.default.valCxt}.${B.default.parentData}`),r.var(B.default.parentDataProperty,(0,j._)`${B.default.valCxt}.${B.default.parentDataProperty}`),r.var(B.default.rootData,(0,j._)`${B.default.valCxt}.${B.default.rootData}`),e.dynamicRef&&r.var(B.default.dynamicAnchors,(0,j._)`${B.default.valCxt}.${B.default.dynamicAnchors}`)},()=>{r.var(B.default.instancePath,(0,j._)`""`),r.var(B.default.parentData,(0,j._)`undefined`),r.var(B.default.parentDataProperty,(0,j._)`undefined`),r.var(B.default.rootData,B.default.data),e.dynamicRef&&r.var(B.default.dynamicAnchors,(0,j._)`{}`)})}function XA(r){let{schema:e,opts:t,gen:n}=r;Qy(r,()=>{t.$comment&&e.$comment&&ng(r),rk(r),n.let(B.default.vErrors,null),n.let(B.default.errors,0),t.unevaluated&&QA(r),rg(r),sk(r)})}function QA(r){let{gen:e,validateName:t}=r;r.evaluated=e.const("evaluated",(0,j._)`${t}.evaluated`),e.if((0,j._)`${r.evaluated}.dynamicProps`,()=>e.assign((0,j._)`${r.evaluated}.props`,(0,j._)`undefined`)),e.if((0,j._)`${r.evaluated}.dynamicItems`,()=>e.assign((0,j._)`${r.evaluated}.items`,(0,j._)`undefined`))}function Gy(r,e){let t=typeof r=="object"&&r[e.schemaId];return t&&(e.code.source||e.code.process)?(0,j._)`/*# sourceURL=${t} */`:j.nil}function ZA(r,e){if(eg(r)&&(tg(r),Zy(r))){ek(r,e);return}(0,Xy.boolOrEmptySchema)(r,e)}function Zy({schema:r,self:e}){if(typeof r=="boolean")return!r;for(let t in r)if(e.RULES.all[t])return!0;return!1}function eg(r){return typeof r.schema!="boolean"}function ek(r,e){let{schema:t,gen:n,opts:i}=r;i.$comment&&t.$comment&&ng(r),nk(r),ik(r);let s=n.const("_errs",B.default.errors);rg(r,s),n.var(e,(0,j._)`${s} === ${B.default.errors}`)}function tg(r){(0,jr.checkUnknownRules)(r),tk(r)}function rg(r,e){if(r.opts.jtd)return Jy(r,[],!1,e);let t=(0,Wy.getSchemaTypes)(r.schema),n=(0,Wy.coerceAndCheckDataType)(r,t);Jy(r,t,!n,e)}function tk(r){let{schema:e,errSchemaPath:t,opts:n,self:i}=r;e.$ref&&n.ignoreKeywordsWithRef&&(0,jr.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function rk(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,jr.checkStrictMode)(r,"default is ignored in the schema root")}function nk(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,WA.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function ik(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function ng({gen:r,schemaEnv:e,schema:t,errSchemaPath:n,opts:i}){let s=t.$comment;if(i.$comment===!0)r.code((0,j._)`${B.default.self}.logger.log(${s})`);else if(typeof i.$comment=="function"){let o=(0,j.str)`${n}/$comment`,a=r.scopeValue("root",{ref:e.root});r.code((0,j._)`${B.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function sk(r){let{gen:e,schemaEnv:t,validateName:n,ValidationError:i,opts:s}=r;t.$async?e.if((0,j._)`${B.default.errors} === 0`,()=>e.return(B.default.data),()=>e.throw((0,j._)`new ${i}(${B.default.vErrors})`)):(e.assign((0,j._)`${n}.errors`,B.default.vErrors),s.unevaluated&&ok(r),e.return((0,j._)`${B.default.errors} === 0`))}function ok({gen:r,evaluated:e,props:t,items:n}){t instanceof j.Name&&r.assign((0,j._)`${e}.props`,t),n instanceof j.Name&&r.assign((0,j._)`${e}.items`,n)}function Jy(r,e,t,n){let{gen:i,schema:s,data:o,allErrors:a,opts:c,self:l}=r,{RULES:u}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,jr.schemaHasRulesButRef)(s,u))){i.block(()=>sg(r,"$ref",u.all.$ref.definition));return}c.jtd||ak(r,e),i.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,mu.shouldUseGroup)(s,f)&&(f.type?(i.if((0,Ua.checkDataType)(f.type,o,c.strictNumbers)),Yy(r,f),e.length===1&&e[0]===f.type&&t&&(i.else(),(0,Ua.reportTypeError)(r)),i.endIf()):Yy(r,f),a||i.if((0,j._)`${B.default.errors} === ${n||0}`))}}function Yy(r,e){let{gen:t,schema:n,opts:{useDefaults:i}}=r;i&&(0,KA.assignDefaults)(r,e.type),t.block(()=>{for(let s of e.rules)(0,mu.shouldUseRule)(n,s)&&sg(r,s.keyword,s.definition,e.type)})}function ak(r,e){r.schemaEnv.meta||!r.opts.strictTypes||(ck(r,e),r.opts.allowUnionTypes||lk(r,e),dk(r,r.dataTypes))}function ck(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{ig(r.dataTypes,t)||yu(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),fk(r,e)}}function lk(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&yu(r,"use allowUnionTypes to allow union type keyword")}function dk(r,e){let t=r.self.RULES.all;for(let n in t){let i=t[n];if(typeof i=="object"&&(0,mu.shouldUseRule)(r.schema,i)){let{type:s}=i.definition;s.length&&!s.some(o=>uk(e,o))&&yu(r,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function uk(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function ig(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function fk(r,e){let t=[];for(let n of r.dataTypes)ig(e,n)?t.push(n):e.includes("integer")&&n==="number"&&t.push("integer");r.dataTypes=t}function yu(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,jr.checkStrictMode)(r,e,r.opts.strictTypes)}var Va=class{constructor(e,t,n){if((0,Ys.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,jr.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",og(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ys.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const("_errs",B.default.errors))}result(e,t,n){this.failResult((0,j.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,j.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,j._)`${t} !== undefined && (${(0,j.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?Js.reportExtraError:Js.reportError)(this,this.def.error,t)}$dataError(){(0,Js.reportError)(this,this.def.$dataError||Js.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Js.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=j.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=j.nil,t=j.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:s,def:o}=this;n.if((0,j.or)((0,j._)`${i} === undefined`,t)),e!==j.nil&&n.assign(e,!0),(s.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==j.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:i,it:s}=this;return(0,j.or)(o(),a());function o(){if(n.length){if(!(t instanceof j.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,j._)`${(0,Ua.checkDataTypes)(c,t,s.opts.strictNumbers,Ua.DataType.Wrong)}`}return j.nil}function a(){if(i.validateSchema){let c=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,j._)`!${c}(${t})`}return j.nil}}subschema(e,t){let n=(0,hu.getSubschema)(this.it,e);(0,hu.extendSubschemaData)(n,this.it,e),(0,hu.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return ZA(i,t),i}mergeEvaluated(e,t){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=jr.mergeEvaluated.props(i,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=jr.mergeEvaluated.items(i,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(t,()=>this.mergeEvaluated(e,j.Name)),!0}};fn.KeywordCxt=Va;function sg(r,e,t,n){let i=new Va(r,t,e);"code"in t?t.code(i,n):i.$data&&t.validate?(0,Ys.funcKeywordCode)(i,t):"macro"in t?(0,Ys.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0,Ys.funcKeywordCode)(i,t)}var pk=/^\/(?:[^~]|~0|~1)*$/,hk=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function og(r,{dataLevel:e,dataNames:t,dataPathArr:n}){let i,s;if(r==="")return B.default.rootData;if(r[0]==="/"){if(!pk.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);i=r,s=B.default.rootData}else{let l=hk.exec(r);if(!l)throw new Error(`Invalid JSON-pointer: ${r}`);let u=+l[1];if(i=l[2],i==="#"){if(u>=e)throw new Error(c("property/index",u));return n[e-u]}if(u>e)throw new Error(c("data",u));if(s=t[e-u],!i)return s}let o=s,a=i.split("/");for(let l of a)l&&(s=(0,j._)`${s}${(0,j.getProperty)((0,jr.unescapeJsonPointer)(l))}`,o=(0,j._)`${o} && ${s}`);return o;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}fn.getData=og});var Xs=A(bu=>{"use strict";Object.defineProperty(bu,"__esModule",{value:!0});var gu=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};bu.default=gu});var Li=A(_u=>{"use strict";Object.defineProperty(_u,"__esModule",{value:!0});var vu=Gs(),wu=class extends Error{constructor(e,t,n,i){super(i||`can't resolve reference ${n} from id ${t}`),this.missingRef=(0,vu.resolveUrl)(e,t,n),this.missingSchema=(0,vu.normalizeId)((0,vu.getFullPath)(e,this.missingRef))}};_u.default=wu});var Qs=A(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.resolveSchema=Lt.getCompilingSchema=Lt.resolveRef=Lt.compileSchema=Lt.SchemaEnv=void 0;var Jt=U(),mk=Xs(),ei=Dt(),Yt=Gs(),ag=Q(),yk=Ni(),Fi=class{constructor(e){var t;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:(0,Yt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Lt.SchemaEnv=Fi;function $u(r){let e=cg.call(this,r);if(e)return e;let t=(0,Yt.getFullPath)(this.opts.uriResolver,r.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:s}=this.opts,o=new Jt.CodeGen(this.scope,{es5:n,lines:i,ownProperties:s}),a;r.$async&&(a=o.scopeValue("Error",{ref:mk.default,code:(0,Jt._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");r.validateName=c;let l={gen:o,allErrors:this.opts.allErrors,data:ei.default.data,parentData:ei.default.parentData,parentDataProperty:ei.default.parentDataProperty,dataNames:[ei.default.data],dataPathArr:[Jt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:r.schema,code:(0,Jt.stringify)(r.schema)}:{ref:r.schema}),validateName:c,ValidationError:a,schema:r.schema,schemaEnv:r,rootId:t,baseId:r.baseId||t,schemaPath:Jt.nil,errSchemaPath:r.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Jt._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(r),(0,yk.validateFunctionCode)(l),o.optimize(this.opts.code.optimize);let d=o.toString();u=`${o.scopeRefs(ei.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,r));let p=new Function(`${ei.default.self}`,`${ei.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=r.schema,p.schemaEnv=r,r.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:o._values}),this.opts.unevaluated){let{props:m,items:h}=l;p.evaluated={props:m instanceof Jt.Name?void 0:m,items:h instanceof Jt.Name?void 0:h,dynamicProps:m instanceof Jt.Name,dynamicItems:h instanceof Jt.Name},p.source&&(p.source.evaluated=(0,Jt.stringify)(p.evaluated))}return r.validate=p,r}catch(d){throw delete r.validate,delete r.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(r)}}Lt.compileSchema=$u;function gk(r,e,t){var n;t=(0,Yt.resolveUrl)(this.opts.uriResolver,e,t);let i=r.refs[t];if(i)return i;let s=wk.call(this,r,t);if(s===void 0){let o=(n=r.localRefs)===null||n===void 0?void 0:n[t],{schemaId:a}=this.opts;o&&(s=new Fi({schema:o,schemaId:a,root:r,baseId:e}))}if(s!==void 0)return r.refs[t]=bk.call(this,s)}Lt.resolveRef=gk;function bk(r){return(0,Yt.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:$u.call(this,r)}function cg(r){for(let e of this._compilations)if(vk(e,r))return e}Lt.getCompilingSchema=cg;function vk(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function wk(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||Ha.call(this,r,e)}function Ha(r,e){let t=this.opts.uriResolver.parse(e),n=(0,Yt._getFullPath)(this.opts.uriResolver,t),i=(0,Yt.getFullPath)(this.opts.uriResolver,r.baseId,void 0);if(Object.keys(r.schema).length>0&&n===i)return Su.call(this,t,r);let s=(0,Yt.normalizeId)(n),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=Ha.call(this,r,o);return typeof a?.schema!="object"?void 0:Su.call(this,t,a)}if(typeof o?.schema=="object"){if(o.validate||$u.call(this,o),s===(0,Yt.normalizeId)(e)){let{schema:a}=o,{schemaId:c}=this.opts,l=a[c];return l&&(i=(0,Yt.resolveUrl)(this.opts.uriResolver,i,l)),new Fi({schema:a,schemaId:c,root:r,baseId:i})}return Su.call(this,t,o)}}Lt.resolveSchema=Ha;var _k=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Su(r,{baseId:e,schema:t,root:n}){var i;if(((i=r.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let a of r.fragment.slice(1).split("/")){if(typeof t=="boolean")return;let c=t[(0,ag.unescapeFragment)(a)];if(c===void 0)return;t=c;let l=typeof t=="object"&&t[this.opts.schemaId];!_k.has(a)&&l&&(e=(0,Yt.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof t!="boolean"&&t.$ref&&!(0,ag.schemaHasRulesButRef)(t,this.RULES)){let a=(0,Yt.resolveUrl)(this.opts.uriResolver,e,t.$ref);s=Ha.call(this,n,a)}let{schemaId:o}=this.opts;if(s=s||new Fi({schema:t,schemaId:o,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var lg=A((Lj,Sk)=>{Sk.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Cu=A((Fj,yg)=>{"use strict";var $k=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Eu=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),xk=RegExp.prototype.test.bind(/^\d*$/u),ti=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Au=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),ug=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),ku=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),Ek=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),ft=new Array(256);{let r="0123456789ABCDEF";for(let e=0;e<256;e++)ft[e]="%"+r[e>>4]+r[e&15]}function ze(r){return r<2048?ft[192|r>>6]+ft[128|r&63]:r<65536?ft[224|r>>12]+ft[128|r>>6&63]+ft[128|r&63]:ft[240|r>>18]+ft[128|r>>12&63]+ft[128|r>>6&63]+ft[128|r&63]}function Ak(r){let e="",t=0,n=0;for(n=0;n=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return"";e+=r[n];break}for(n+=1;n=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return"";e+=r[n]}return e}var kk=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),Pk=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),Ck=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),Mk=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Tk(r){if(r.length===0)return!1;for(let e=0;et&&(t=i,e=n)):(n=-1,i=0);if(t<2)return r.join(":");let s=r.slice(0,e).join(":"),o=r.slice(e+t).join(":");return s+"::"+o}function Rk(r){let e=r.indexOf("::");if(e!==-1&&r.indexOf("::",e+1)!==-1)return;let t=e===-1?r.split(":"):r.slice(0,e).split(":"),n=e===-1?[]:r.slice(e+2).split(":");e!==-1&&(t.length===1&&t[0]===""&&(t.length=0),n.length===1&&n[0]===""&&(n.length=0));let i=t.concat(n),s=0;for(let a=0;a=8)return;let o=i.slice(0,t.length);for(let a=s;a<8;a++)o.push("0");for(let a=t.length;aDk[n])}function pg(r,e=!1){if(r.indexOf("%")===-1)return r;let t="";for(let n=0;n57343)e+=ze(i);else if(i<=56319&&t+1=56320&&s<=57343?(e+=ze(65536+(i-55296<<10)+(s-56320)),t++):e+=ze(65533)}else e+=ze(65533)}}return e}function jk(r,e=!1){let t="",n=e&&r[0]!=="/";for(let i=0;i57343)t+=ze(o);else if(o<=56319&&i+1=56320&&a<=57343?(t+=ze(65536+(o-55296<<10)+(a-56320)),i++):t+=ze(65533)}else t+=ze(65533)}}return t}function Pu(r,e){let t="";for(let n=0;n57343)t+=ze(s);else if(s<=56319&&n+1=56320&&o<=57343?(t+=ze(65536+(s-55296<<10)+(o-56320)),n++):t+=ze(65533)}else t+=ze(65533)}}return t}function hg(r){return Pu(r,Ek)}function qk(r){return Pu(r,ku)}function Bk(r){return Pu(r,ku)}function mg(r){return r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||r===42||r===43||r===45||r===46||r===47||r===64||r===95}function Uk(r){let e="";for(let t=0;t57343)e+=ze(i);else if(i<=56319&&t+1=56320&&s<=57343?(e+=ze(65536+(i-55296<<10)+(s-56320)),t++):e+=ze(65533)}else e+=ze(65533)}}return e}function Vk(r){let e="";for(let t=0;t{"use strict";var{isUUID:zk}=Cu(),Kk=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,Wk=["http","https","ws","wss","urn","urn:uuid"];function Gk(r){return Wk.indexOf(r)!==-1}function Mu(r){return r.secure===!0?!0:r.secure===!1?!1:r.scheme?r.scheme.length===3&&(r.scheme[0]==="w"||r.scheme[0]==="W")&&(r.scheme[1]==="s"||r.scheme[1]==="S")&&(r.scheme[2]==="s"||r.scheme[2]==="S"):!1}function gg(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function bg(r){let e=String(r.scheme).toLowerCase()==="https";return(r.port===(e?443:80)||r.port==="")&&(r.port=void 0),r.path||(r.path="/"),r}function Jk(r){return r.secure=Mu(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function Yk(r){if((r.port===(Mu(r)?443:80)||r.port==="")&&(r.port=void 0),typeof r.secure=="boolean"&&(r.scheme=r.secure?"wss":"ws",r.secure=void 0),r.resourceName){let e=r.resourceName.indexOf("?"),t=e===-1?r.resourceName:r.resourceName.slice(0,e);r.path=t&&t!=="/"?t:void 0,r.query=e===-1?void 0:r.resourceName.slice(e+1),r.resourceName=void 0}return r.fragment=void 0,r}function Xk(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(Kk);if(t&&t[0]===r.path){let n=e.scheme||r.scheme||"urn";r.nid=t[1].toLowerCase(),r.nss=t[2];let i=`${n}:${e.nid||r.nid}`,s=Tu(i);r.path=void 0,s&&(r=s.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function Qk(r,e){if(r.nid===void 0)throw new Error("URN without nid cannot be serialized");let t=e.scheme||r.scheme||"urn",n=r.nid.toLowerCase(),i=`${t}:${e.nid||n}`,s=Tu(i);s&&(r=s.serialize(r,e));let o=r,a=r.nss;return o.path=`${n||e.nid}:${a}`,e.skipEscape=!0,o}function Zk(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!zk(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function eP(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var vg={scheme:"http",domainHost:!0,parse:gg,serialize:bg},tP={scheme:"https",domainHost:vg.domainHost,parse:gg,serialize:bg},za={scheme:"ws",domainHost:!0,parse:Jk,serialize:Yk},rP={scheme:"wss",domainHost:za.domainHost,parse:za.parse,serialize:za.serialize},nP={scheme:"urn",parse:Xk,serialize:Qk,skipNormalize:!0},iP={scheme:"urn:uuid",parse:Zk,serialize:eP,skipNormalize:!0},Ka={http:vg,https:tP,ws:za,wss:rP,urn:nP,"urn:uuid":iP};Object.setPrototypeOf(Ka,null);function Tu(r){return r&&(Ka[r]||Ka[r.toLowerCase()])||void 0}wg.exports={wsIsSecure:Mu,SCHEMES:Ka,isValidSchemeName:Gk,getSchemeHandler:Tu}});var Dg=A((qj,Ja)=>{"use strict";var{normalizeIPv6:Ag,removeDotSegments:eo,recomposeAuthority:sP,normalizePercentEncoding:kg,normalizePathEncoding:oP,serializePathEncoding:Sg,normalizeQueryFragmentEncoding:$g,encodeQuery:aP,encodeFragment:cP,reescapeHostDelimiters:lP,isIPv4:Pg,nonSimpleDomain:dP}=Cu(),{SCHEMES:Cg,getSchemeHandler:Ru}=_g(),Mg=/^[A-Za-z][A-Za-z0-9+.-]*$/u,Tg="URI scheme is malformed.";function xg(r){let e=unescape(String(r));if(!Mg.test(e))throw new TypeError(Tg);return e}function uP(r,e){return typeof r=="string"?r=vP(r,e):typeof r=="object"&&(r=Ga(ri(r,e),e)),r}function fP(r,e,t){let n=t?Object.assign({scheme:"null"},t):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:s,malformedPercentEncoding:o,malformedSchemeSpecific:a,malformedHost:c,malformedScheme:l}=Wa(r,n),{parsed:u,malformedAuthorityOrPort:d,malformedPercentEncoding:f,malformedSchemeSpecific:p,malformedHost:m,malformedScheme:h}=Wa(e,n);if(s||d||o||f||a||p||c||m||l||h)throw new Error(i.error||u.error||"URI is malformed.");let y=Rg(i,u,n,!0),g=Ru(t&&t.scheme||y.scheme),b=y.host,v=b!==void 0&&b!==""&&(Pg(b)||Ag(b).isIPV6);Ig(y,t||{},g,v);let S=b&&b.indexOf("%")!==-1&&!/\P{ASCII}/u.test(b);if(y.error&&!S)throw new Error(y.error);return n.skipEscape=!0,ri(y,n)}function Rg(r,e,t,n){let i={};return n||(r=Ga(ri(r,t),t),e=Ga(ri(e,t),t)),t=t||{},!t.tolerant&&e.scheme?(i.scheme=e.scheme,i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=eo(e.path||""),i.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=eo(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=eo(e.path):((r.userinfo!==void 0||r.host!==void 0||r.port!==void 0)&&!r.path?i.path="/"+e.path:r.path?i.path=r.path.slice(0,r.path.lastIndexOf("/")+1)+e.path:i.path=e.path,i.path=eo(i.path)),i.query=e.query):(i.path=r.path,e.query!==void 0?i.query=e.query:i.query=r.query),i.userinfo=r.userinfo,i.host=r.host,i.port=r.port),i.scheme=r.scheme),i.fragment=e.fragment,i}function pP(r,e,t){let n=Eg(r,t),i=Eg(e,t);return n!==void 0&&i!==void 0&&n===i}function ri(r,e){let t={host:r.host,scheme:r.scheme,userinfo:r.userinfo,port:r.port,path:r.path,query:r.query,nid:r.nid,nss:r.nss,uuid:r.uuid,fragment:r.fragment,reference:r.reference,resourceName:r.resourceName,secure:r.secure,error:""},n=Object.assign({},e),i=[];t.scheme&&(t.scheme=xg(t.scheme));let s=Ru(n.scheme||t.scheme);s&&s.serialize&&s.serialize(t,n);let o=t.userinfo!==void 0||t.host!==void 0||t.port!==void 0,a=!n.skipEscape&&t.scheme===void 0&&!o;t.path!==void 0&&(n.skipEscape?t.path=kg(t.path):t.path=Sg(t.path,a)),n.reference!=="suffix"&&t.scheme&&(t.scheme=xg(t.scheme),i.push(t.scheme,":"));let c=sP(t);if(c!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(c),t.path&&t.path[0]!=="/"&&i.push("/")),t.path!==void 0){let l=t.path;!n.absolutePath&&(!s||!s.absolutePath)&&(l=eo(l)),a&&(l=Sg(l,!0)),c===void 0&&l[0]==="/"&&l[1]==="/"&&(l="/%2F"+l.slice(2)),i.push(l)}return t.query!==void 0&&i.push("?",aP(t.query)),t.fragment!==void 0&&i.push("#",cP(t.fragment)),i.join("")}var hP=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,mP=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,yP=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function gP(r,e){if(e[2]!==void 0&&r.path&&r.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof r.port=="number"&&(r.port<0||r.port>65535))return"URI port is malformed."}function Zs(r){if(r===void 0)return!1;let e=r.indexOf("%");for(;e!==-1;){if(e+2>=r.length||!/^[\da-f]{2}$/iu.test(r.slice(e+1,e+3)))return!0;e=r.indexOf("%",e+3)}return!1}function Iu(r){return r[0]==="["&&r[r.length-1]==="]"}function bP(r){let e=r[4];return Zs(r[3])||e!==void 0&&!Iu(e)&&Zs(e)||Zs(r[6])||Zs(r[7])||Zs(r[8])}function Ig(r,e,t,n){if(!e.unicodeSupport&&(!t||!t.unicodeSupport)&&r.host&&!Iu(r.host)&&(e.domainHost||t&&t.domainHost)&&n===!1&&dP(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(i){return r.error=r.error||"Host's domain name can not be converted to ASCII: "+i,!0}return!1}function Wa(r,e){let t=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=!1,s=!1,o=!1,a=!1,c=!1,l=!1,u=!1;t.reference==="suffix"&&(t.scheme?r=t.scheme+":"+r:r="//"+r);let d=r.match(mP);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let f=r.match(yP);if(f!==null){let m=f[1],h=m.replace(/[\t\n\r]/g,"");h.length>=2&&(h.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",i=!0):m.length!==h.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",i=!0))}let p=r.match(hP);if(p){if(n.scheme=p[1],n.userinfo=p[3],n.host=p[4],n.port=parseInt(p[5],10),n.path=p[6]||"",n.query=p[7],n.fragment=p[8],n.scheme!==void 0){let y=unescape(n.scheme);Mg.test(y)?n.scheme=y.toLowerCase():(n.error=n.error||Tg,l=!0)}s=bP(p),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=p[5]);let m=gP(n,p);if(m!==void 0&&(n.error=n.error||m,i=!0),n.host)if(Pg(n.host)===!1){let g=Iu(n.host),b=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,v=Ag(n.host);u=v.isIPV6||v.isIPVFuture===!0,c=b&&(!g||v.error===!0),n.host=u?v.host:v.host.toLowerCase(),c&&(n.error=n.error||"URI host is malformed.",i=!0)}else u=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",t.reference&&t.reference!=="suffix"&&t.reference!==n.reference&&(n.error=n.error||"URI is not a "+t.reference+" reference.");let h=Ru(t.scheme||n.scheme);if(c||(a=Ig(n,t,h,u)),!h||h&&!h.skipNormalize){if(r.indexOf("%")!==-1&&n.host!==void 0&&!c){let y=u?n.host:kg(n.host,!0);n.host=lP(y,u)}n.path&&(n.path=oP(n.path)),n.query&&(n.query=$g(n.query)),n.fragment&&(n.fragment=$g(n.fragment))}h&&h.parse&&(h.parse(n,t),h===Cg.urn&&n.nid===void 0&&(o=!0))}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:i,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:a,malformedScheme:l}}function Ga(r,e){return Wa(r,e).parsed}function vP(r,e){return Og(r,e).normalized}function Og(r,e){let{parsed:t,malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:a}=Wa(r,e);return{normalized:n||i||s||o||a?r:ri(t,e),malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:a}}function Eg(r,e){if(typeof r!="string"&&typeof r!="object")return;let t;try{t=typeof r=="string"?r:ri(r,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:i,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:a,malformedScheme:c}=Og(t,e);return i||s||o||a||c?void 0:n}var Ou={SCHEMES:Cg,normalize:uP,resolve:fP,resolveComponent:Rg,equal:pP,serialize:ri,parse:Ga};Ja.exports=Ou;Ja.exports.default=Ou;Ja.exports.fastUri=Ou});var Lg=A(Du=>{"use strict";Object.defineProperty(Du,"__esModule",{value:!0});var Ng=Dg();Ng.code='require("ajv/dist/runtime/uri").default';Du.default=Ng});var Fu=A(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.CodeGen=Le.Name=Le.nil=Le.stringify=Le.str=Le._=Le.KeywordCxt=void 0;var wP=Ni();Object.defineProperty(Le,"KeywordCxt",{enumerable:!0,get:function(){return wP.KeywordCxt}});var ji=U();Object.defineProperty(Le,"_",{enumerable:!0,get:function(){return ji._}});Object.defineProperty(Le,"str",{enumerable:!0,get:function(){return ji.str}});Object.defineProperty(Le,"stringify",{enumerable:!0,get:function(){return ji.stringify}});Object.defineProperty(Le,"nil",{enumerable:!0,get:function(){return ji.nil}});Object.defineProperty(Le,"Name",{enumerable:!0,get:function(){return ji.Name}});Object.defineProperty(Le,"CodeGen",{enumerable:!0,get:function(){return ji.CodeGen}});var _P=Xs(),Ug=Li(),SP=iu(),to=Qs(),$P=U(),ro=Gs(),Ya=Ws(),Lu=Q(),Fg=lg(),xP=Lg(),Vg=(r,e)=>new RegExp(r,e);Vg.code="new RegExp";var EP=["removeAdditional","useDefaults","coerceTypes"],AP=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),kP={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},PP={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},jg=200;function CP(r){var e,t,n,i,s,o,a,c,l,u,d,f,p,m,h,y,g,b,v,S,_,E,k,$,M;let x=r.strict,q=(e=r.code)===null||e===void 0?void 0:e.optimize,T=q===!0||q===void 0?1:q||0,V=(n=(t=r.code)===null||t===void 0?void 0:t.regExp)!==null&&n!==void 0?n:Vg,P=(i=r.uriResolver)!==null&&i!==void 0?i:xP.default;return{strictSchema:(o=(s=r.strictSchema)!==null&&s!==void 0?s:x)!==null&&o!==void 0?o:!0,strictNumbers:(c=(a=r.strictNumbers)!==null&&a!==void 0?a:x)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=r.strictTypes)!==null&&l!==void 0?l:x)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=r.strictTuples)!==null&&d!==void 0?d:x)!==null&&f!==void 0?f:"log",strictRequired:(m=(p=r.strictRequired)!==null&&p!==void 0?p:x)!==null&&m!==void 0?m:!1,code:r.code?{...r.code,optimize:T,regExp:V}:{optimize:T,regExp:V},loopRequired:(h=r.loopRequired)!==null&&h!==void 0?h:jg,loopEnum:(y=r.loopEnum)!==null&&y!==void 0?y:jg,meta:(g=r.meta)!==null&&g!==void 0?g:!0,messages:(b=r.messages)!==null&&b!==void 0?b:!0,inlineRefs:(v=r.inlineRefs)!==null&&v!==void 0?v:!0,schemaId:(S=r.schemaId)!==null&&S!==void 0?S:"$id",addUsedSchema:(_=r.addUsedSchema)!==null&&_!==void 0?_:!0,validateSchema:(E=r.validateSchema)!==null&&E!==void 0?E:!0,validateFormats:(k=r.validateFormats)!==null&&k!==void 0?k:!0,unicodeRegExp:($=r.unicodeRegExp)!==null&&$!==void 0?$:!0,int32range:(M=r.int32range)!==null&&M!==void 0?M:!0,uriResolver:P}}var no=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...CP(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new $P.ValueScope({scope:{},prefixes:AP,es5:t,lines:n}),this.logger=DP(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,SP.getRules)(),qg.call(this,kP,e,"NOT SUPPORTED"),qg.call(this,PP,e,"DEPRECATED","warn"),this._metaOpts=IP.call(this),e.formats&&TP.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&RP.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),MP.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,i=Fg;n==="id"&&(i={...Fg},i.id=i.$id,delete i.$id),t&&e&&this.addMetaSchema(i,i[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[t]||e:void 0}validate(e,t){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let i=n(t);return"$async"in n||(this.errors=n.errors),i}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return i.call(this,e,t);async function i(u,d){await s.call(this,u.$schema);let f=this._addSchema(u,d);return f.validate||o.call(this,f)}async function s(u){u&&!this.getSchema(u)&&await i.call(this,{$ref:u},!0)}async function o(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof Ug.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),o.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function c(u){let d=await l.call(this,u);this.refs[u]||await s.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,t)}async function l(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(e,t,n,i=this.opts.validateSchema){if(Array.isArray(e)){for(let o of e)this.addSchema(o,void 0,n,i);return this}let s;if(typeof e=="object"){let{schemaId:o}=this.opts;if(s=e[o],s!==void 0&&typeof s!="string")throw new Error(`schema ${o} must be string`)}return t=(0,ro.normalizeId)(t||s),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,i,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let i=this.validate(n,e);if(!i&&t){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return i}getSchema(e){let t;for(;typeof(t=Bg.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:n}=this.opts,i=new to.SchemaEnv({schema:{},schemaId:n});if(t=to.resolveSchema.call(this,i,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let t=Bg.call(this,e);return typeof t=="object"&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,ro.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e=="string")n=e,typeof t=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=n);else if(typeof e=="object"&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(LP.call(this,n,t),!t)return(0,Lu.eachItem)(n,s=>Nu.call(this,s)),this;jP.call(this,t);let i={...t,type:(0,Ya.getJSONTypes)(t.type),schemaType:(0,Ya.getJSONTypes)(t.schemaType)};return(0,Lu.eachItem)(n,i.type.length===0?s=>Nu.call(this,s,i):s=>i.type.forEach(o=>Nu.call(this,s,i,o))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t=="object"?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let i=n.rules.findIndex(s=>s.keyword===e);i>=0&&n.rules.splice(i,1)}return this}addFormat(e,t){return typeof t=="string"&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,s)=>i+t+s)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of t){let s=i.split("/").slice(1),o=e;for(let a of s)o=o[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=o[a];l&&u&&(o[a]=Hg(u))}}return e}_removeAllSchemas(e,t){for(let n in e){let i=e[n];(!t||t.test(n))&&(typeof i=="string"?delete e[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete e[n]))}}_addSchema(e,t,n,i=this.opts.validateSchema,s=this.opts.addUsedSchema){let o,{schemaId:a}=this.opts;if(typeof e=="object")o=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,ro.normalizeId)(o||n);let l=ro.getSchemaRefs.call(this,e,n);return c=new to.SchemaEnv({schema:e,schemaId:a,meta:t,baseId:n,localRefs:l}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),i&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):to.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{to.compileSchema.call(this,e)}finally{this.opts=t}}};no.ValidationError=_P.default;no.MissingRefError=Ug.default;Le.default=no;function qg(r,e,t,n="error"){for(let i in r){let s=i;s in e&&this.logger[n](`${t}: option ${i}. ${r[s]}`)}}function Bg(r){return r=(0,ro.normalizeId)(r),this.schemas[r]||this.refs[r]}function MP(){let r=this.opts.schemas;if(r)if(Array.isArray(r))this.addSchema(r);else for(let e in r)this.addSchema(r[e],e)}function TP(){for(let r in this.opts.formats){let e=this.opts.formats[r];e&&this.addFormat(r,e)}}function RP(r){if(Array.isArray(r)){this.addVocabulary(r);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in r){let t=r[e];t.keyword||(t.keyword=e),this.addKeyword(t)}}function IP(){let r={...this.opts};for(let e of EP)delete r[e];return r}var OP={log(){},warn(){},error(){}};function DP(r){if(r===!1)return OP;if(r===void 0)return console;if(r.log&&r.warn&&r.error)return r;throw new Error("logger must implement log, warn and error methods")}var NP=/^[a-z_$][a-z0-9_$:-]*$/i;function LP(r,e){let{RULES:t}=this;if((0,Lu.eachItem)(r,n=>{if(t.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!NP.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Nu(r,e,t){var n;let i=e?.post;if(t&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,o=i?s.post:s.rules.find(({type:c})=>c===t);if(o||(o={type:t,rules:[]},s.rules.push(o)),s.keywords[r]=!0,!e)return;let a={keyword:r,definition:{...e,type:(0,Ya.getJSONTypes)(e.type),schemaType:(0,Ya.getJSONTypes)(e.schemaType)}};e.before?FP.call(this,o,a,e.before):o.rules.push(a),s.all[r]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function FP(r,e,t){let n=r.rules.findIndex(i=>i.keyword===t);n>=0?r.rules.splice(n,0,e):(r.rules.push(e),this.logger.warn(`rule ${t} is not defined`))}function jP(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=Hg(e)),r.validateSchema=this.compile(e,!0))}var qP={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Hg(r){return{anyOf:[r,qP]}}});var zg=A(ju=>{"use strict";Object.defineProperty(ju,"__esModule",{value:!0});var BP={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ju.default=BP});var Za=A(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.callRef=ni.getValidate=void 0;var UP=Li(),Kg=Nt(),pt=U(),qi=Dt(),Wg=Qs(),Xa=Q(),VP={keyword:"$ref",schemaType:"string",code(r){let{gen:e,schema:t,it:n}=r,{baseId:i,schemaEnv:s,validateName:o,opts:a,self:c}=n,{root:l}=s;if((t==="#"||t==="#/")&&i===l.baseId)return d();let u=Wg.resolveRef.call(c,l,i,t);if(u===void 0)throw new UP.default(n.opts.uriResolver,i,t);if(u instanceof Wg.SchemaEnv)return f(u);return p(u);function d(){if(s===l)return Qa(r,o,s,s.$async);let m=e.scopeValue("root",{ref:l});return Qa(r,(0,pt._)`${m}.validate`,l,l.$async)}function f(m){let h=Gg(r,m);Qa(r,h,m,m.$async)}function p(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,pt.stringify)(m)}:{ref:m}),y=e.name("valid"),g=r.subschema({schema:m,dataTypes:[],schemaPath:pt.nil,topSchemaRef:h,errSchemaPath:t},y);r.mergeEvaluated(g),r.ok(y)}}};function Gg(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,pt._)`${t.scopeValue("wrapper",{ref:e})}.validate`}ni.getValidate=Gg;function Qa(r,e,t,n){let{gen:i,it:s}=r,{allErrors:o,schemaEnv:a,opts:c}=s,l=c.passContext?qi.default.this:pt.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=i.let("valid");i.try(()=>{i.code((0,pt._)`await ${(0,Kg.callValidateCode)(r,e,l)}`),p(e),o||i.assign(m,!0)},h=>{i.if((0,pt._)`!(${h} instanceof ${s.ValidationError})`,()=>i.throw(h)),f(h),o||i.assign(m,!1)}),r.ok(m)}function d(){r.result((0,Kg.callValidateCode)(r,e,l),()=>p(e),()=>f(e))}function f(m){let h=(0,pt._)`${m}.errors`;i.assign(qi.default.vErrors,(0,pt._)`${qi.default.vErrors} === null ? ${h} : ${qi.default.vErrors}.concat(${h})`),i.assign(qi.default.errors,(0,pt._)`${qi.default.vErrors}.length`)}function p(m){var h;if(!s.opts.unevaluated)return;let y=(h=t?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=Xa.mergeEvaluated.props(i,y.props,s.props));else{let g=i.var("props",(0,pt._)`${m}.evaluated.props`);s.props=Xa.mergeEvaluated.props(i,g,s.props,pt.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Xa.mergeEvaluated.items(i,y.items,s.items));else{let g=i.var("items",(0,pt._)`${m}.evaluated.items`);s.items=Xa.mergeEvaluated.items(i,g,s.items,pt.Name)}}}ni.callRef=Qa;ni.default=VP});var Bu=A(qu=>{"use strict";Object.defineProperty(qu,"__esModule",{value:!0});var HP=zg(),zP=Za(),KP=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",HP.default,zP.default];qu.default=KP});var Jg=A(Uu=>{"use strict";Object.defineProperty(Uu,"__esModule",{value:!0});var ec=U(),pn=ec.operators,tc={maximum:{okStr:"<=",ok:pn.LTE,fail:pn.GT},minimum:{okStr:">=",ok:pn.GTE,fail:pn.LT},exclusiveMaximum:{okStr:"<",ok:pn.LT,fail:pn.GTE},exclusiveMinimum:{okStr:">",ok:pn.GT,fail:pn.LTE}},WP={message:({keyword:r,schemaCode:e})=>(0,ec.str)`must be ${tc[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,ec._)`{comparison: ${tc[r].okStr}, limit: ${e}}`},GP={keyword:Object.keys(tc),type:"number",schemaType:"number",$data:!0,error:WP,code(r){let{keyword:e,data:t,schemaCode:n}=r;r.fail$data((0,ec._)`${t} ${tc[e].fail} ${n} || isNaN(${t})`)}};Uu.default=GP});var Yg=A(Vu=>{"use strict";Object.defineProperty(Vu,"__esModule",{value:!0});var io=U(),JP={message:({schemaCode:r})=>(0,io.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,io._)`{multipleOf: ${r}}`},YP={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:JP,code(r){let{gen:e,data:t,schemaCode:n,it:i}=r,s=i.opts.multipleOfPrecision,o=e.let("res"),a=s?(0,io._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,io._)`${o} !== parseInt(${o})`;r.fail$data((0,io._)`(${n} === 0 || (${o} = ${t}/${n}, ${a}))`)}};Vu.default=YP});var Qg=A(Hu=>{"use strict";Object.defineProperty(Hu,"__esModule",{value:!0});function Xg(r){let e=r.length,t=0,n=0,i;for(;n=55296&&i<=56319&&n{"use strict";Object.defineProperty(zu,"__esModule",{value:!0});var ii=U(),XP=Q(),QP=Qg(),ZP={message({keyword:r,schemaCode:e}){let t=r==="maxLength"?"more":"fewer";return(0,ii.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:r})=>(0,ii._)`{limit: ${r}}`},e1={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:ZP,code(r){let{keyword:e,data:t,schemaCode:n,it:i}=r,s=e==="maxLength"?ii.operators.GT:ii.operators.LT,o=i.opts.unicode===!1?(0,ii._)`${t}.length`:(0,ii._)`${(0,XP.useFunc)(r.gen,QP.default)}(${t})`;r.fail$data((0,ii._)`${o} ${s} ${n}`)}};zu.default=e1});var eb=A(Ku=>{"use strict";Object.defineProperty(Ku,"__esModule",{value:!0});var t1=Nt(),r1=Q(),Bi=U(),n1={message:({schemaCode:r})=>(0,Bi.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,Bi._)`{pattern: ${r}}`},i1={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:n1,code(r){let{gen:e,data:t,$data:n,schema:i,schemaCode:s,it:o}=r,a=o.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=o.opts.code,l=c.code==="new RegExp"?(0,Bi._)`new RegExp`:(0,r1.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Bi._)`${l}(${s}, ${a}).test(${t})`),()=>e.assign(u,!1)),r.fail$data((0,Bi._)`!${u}`)}else{let c=(0,t1.usePattern)(r,i);r.fail$data((0,Bi._)`!${c}.test(${t})`)}}};Ku.default=i1});var tb=A(Wu=>{"use strict";Object.defineProperty(Wu,"__esModule",{value:!0});var so=U(),s1={message({keyword:r,schemaCode:e}){let t=r==="maxProperties"?"more":"fewer";return(0,so.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:r})=>(0,so._)`{limit: ${r}}`},o1={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:s1,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxProperties"?so.operators.GT:so.operators.LT;r.fail$data((0,so._)`Object.keys(${t}).length ${i} ${n}`)}};Wu.default=o1});var rb=A(Gu=>{"use strict";Object.defineProperty(Gu,"__esModule",{value:!0});var oo=Nt(),ao=U(),a1=Q(),c1={message:({params:{missingProperty:r}})=>(0,ao.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,ao._)`{missingProperty: ${r}}`},l1={keyword:"required",type:"object",schemaType:"array",$data:!0,error:c1,code(r){let{gen:e,schema:t,schemaCode:n,data:i,$data:s,it:o}=r,{opts:a}=o;if(!s&&t.length===0)return;let c=t.length>=a.loopRequired;if(o.allErrors?l():u(),a.strictRequired){let p=r.parentSchema.properties,{definedProperties:m}=r.it;for(let h of t)if(p?.[h]===void 0&&!m.has(h)){let y=o.schemaEnv.baseId+o.errSchemaPath,g=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,a1.checkStrictMode)(o,g,o.opts.strictRequired)}}function l(){if(c||s)r.block$data(ao.nil,d);else for(let p of t)(0,oo.checkReportMissingProp)(r,p)}function u(){let p=e.let("missing");if(c||s){let m=e.let("valid",!0);r.block$data(m,()=>f(p,m)),r.ok(m)}else e.if((0,oo.checkMissingProp)(r,t,p)),(0,oo.reportMissingProp)(r,p),e.else()}function d(){e.forOf("prop",n,p=>{r.setParams({missingProperty:p}),e.if((0,oo.noPropertyInData)(e,i,p,a.ownProperties),()=>r.error())})}function f(p,m){r.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(m,(0,oo.propertyInData)(e,i,p,a.ownProperties)),e.if((0,ao.not)(m),()=>{r.error(),e.break()})},ao.nil)}}};Gu.default=l1});var nb=A(Ju=>{"use strict";Object.defineProperty(Ju,"__esModule",{value:!0});var co=U(),d1={message({keyword:r,schemaCode:e}){let t=r==="maxItems"?"more":"fewer";return(0,co.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:r})=>(0,co._)`{limit: ${r}}`},u1={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:d1,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxItems"?co.operators.GT:co.operators.LT;r.fail$data((0,co._)`${t}.length ${i} ${n}`)}};Ju.default=u1});var rc=A(Yu=>{"use strict";Object.defineProperty(Yu,"__esModule",{value:!0});var ib=fu();ib.code='require("ajv/dist/runtime/equal").default';Yu.default=ib});var sb=A(Qu=>{"use strict";Object.defineProperty(Qu,"__esModule",{value:!0});var Xu=Ws(),Fe=U(),f1=Q(),p1=rc(),h1={message:({params:{i:r,j:e}})=>(0,Fe.str)`must NOT have duplicate items (items ## ${e} and ${r} are identical)`,params:({params:{i:r,j:e}})=>(0,Fe._)`{i: ${r}, j: ${e}}`},m1={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:h1,code(r){let{gen:e,data:t,$data:n,schema:i,parentSchema:s,schemaCode:o,it:a}=r;if(!n&&!i)return;let c=e.let("valid"),l=s.items?(0,Xu.getSchemaTypes)(s.items):[];r.block$data(c,u,(0,Fe._)`${o} === false`),r.ok(c);function u(){let m=e.let("i",(0,Fe._)`${t}.length`),h=e.let("j");r.setParams({i:m,j:h}),e.assign(c,!0),e.if((0,Fe._)`${m} > 1`,()=>(d()?f:p)(m,h))}function d(){return l.length>0&&!l.some(m=>m==="object"||m==="array")}function f(m,h){let y=e.name("item"),g=(0,Xu.checkDataTypes)(l,y,a.opts.strictNumbers,Xu.DataType.Wrong),b=e.const("indices",(0,Fe._)`{}`);e.for((0,Fe._)`;${m}--;`,()=>{e.let(y,(0,Fe._)`${t}[${m}]`),e.if(g,(0,Fe._)`continue`),l.length>1&&e.if((0,Fe._)`typeof ${y} == "string"`,(0,Fe._)`${y} += "_"`),e.if((0,Fe._)`typeof ${b}[${y}] == "number"`,()=>{e.assign(h,(0,Fe._)`${b}[${y}]`),r.error(),e.assign(c,!1).break()}).code((0,Fe._)`${b}[${y}] = ${m}`)})}function p(m,h){let y=(0,f1.useFunc)(e,p1.default),g=e.name("outer");e.label(g).for((0,Fe._)`;${m}--;`,()=>e.for((0,Fe._)`${h} = ${m}; ${h}--;`,()=>e.if((0,Fe._)`${y}(${t}[${m}], ${t}[${h}])`,()=>{r.error(),e.assign(c,!1).break(g)})))}}};Qu.default=m1});var ob=A(ef=>{"use strict";Object.defineProperty(ef,"__esModule",{value:!0});var Zu=U(),y1=Q(),g1=rc(),b1={message:"must be equal to constant",params:({schemaCode:r})=>(0,Zu._)`{allowedValue: ${r}}`},v1={keyword:"const",$data:!0,error:b1,code(r){let{gen:e,data:t,$data:n,schemaCode:i,schema:s}=r;n||s&&typeof s=="object"?r.fail$data((0,Zu._)`!${(0,y1.useFunc)(e,g1.default)}(${t}, ${i})`):r.fail((0,Zu._)`${s} !== ${t}`)}};ef.default=v1});var ab=A(tf=>{"use strict";Object.defineProperty(tf,"__esModule",{value:!0});var lo=U(),w1=Q(),_1=rc(),S1={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,lo._)`{allowedValues: ${r}}`},$1={keyword:"enum",schemaType:"array",$data:!0,error:S1,code(r){let{gen:e,data:t,$data:n,schema:i,schemaCode:s,it:o}=r;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let a=i.length>=o.opts.loopEnum,c,l=()=>c??(c=(0,w1.useFunc)(e,_1.default)),u;if(a||n)u=e.let("valid"),r.block$data(u,d);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let p=e.const("vSchema",s);u=(0,lo.or)(...i.map((m,h)=>f(p,h)))}r.pass(u);function d(){e.assign(u,!1),e.forOf("v",s,p=>e.if((0,lo._)`${l()}(${t}, ${p})`,()=>e.assign(u,!0).break()))}function f(p,m){let h=i[m];return typeof h=="object"&&h!==null?(0,lo._)`${l()}(${t}, ${p}[${m}])`:(0,lo._)`${t} === ${h}`}}};tf.default=$1});var nf=A(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});var x1=Jg(),E1=Yg(),A1=Zg(),k1=eb(),P1=tb(),C1=rb(),M1=nb(),T1=sb(),R1=ob(),I1=ab(),O1=[x1.default,E1.default,A1.default,k1.default,P1.default,C1.default,M1.default,T1.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},R1.default,I1.default];rf.default=O1});var of=A(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.validateAdditionalItems=void 0;var si=U(),sf=Q(),D1={message:({params:{len:r}})=>(0,si.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,si._)`{limit: ${r}}`},N1={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:D1,code(r){let{parentSchema:e,it:t}=r,{items:n}=e;if(!Array.isArray(n)){(0,sf.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}cb(r,n)}};function cb(r,e){let{gen:t,schema:n,data:i,keyword:s,it:o}=r;o.items=!0;let a=t.const("len",(0,si._)`${i}.length`);if(n===!1)r.setParams({len:e.length}),r.pass((0,si._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,sf.alwaysValidSchema)(o,n)){let l=t.var("valid",(0,si._)`${a} <= ${e.length}`);t.if((0,si.not)(l),()=>c(l)),r.ok(l)}function c(l){t.forRange("i",e.length,a,u=>{r.subschema({keyword:s,dataProp:u,dataPropType:sf.Type.Num},l),o.allErrors||t.if((0,si.not)(l),()=>t.break())})}}uo.validateAdditionalItems=cb;uo.default=N1});var af=A(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.validateTuple=void 0;var lb=U(),nc=Q(),L1=Nt(),F1={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return db(r,"additionalItems",e);t.items=!0,!(0,nc.alwaysValidSchema)(t,e)&&r.ok((0,L1.validateArray)(r))}};function db(r,e,t=r.schema){let{gen:n,parentSchema:i,data:s,keyword:o,it:a}=r;u(i),a.opts.unevaluated&&t.length&&a.items!==!0&&(a.items=nc.mergeEvaluated.items(n,t.length,a.items));let c=n.name("valid"),l=n.const("len",(0,lb._)`${s}.length`);t.forEach((d,f)=>{(0,nc.alwaysValidSchema)(a,d)||(n.if((0,lb._)`${l} > ${f}`,()=>r.subschema({keyword:o,schemaProp:f,dataProp:f},c)),r.ok(c))});function u(d){let{opts:f,errSchemaPath:p}=a,m=t.length,h=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(f.strictTuples&&!h){let y=`"${o}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,nc.checkStrictMode)(a,y,f.strictTuples)}}}fo.validateTuple=db;fo.default=F1});var ub=A(cf=>{"use strict";Object.defineProperty(cf,"__esModule",{value:!0});var j1=af(),q1={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,j1.validateTuple)(r,"items")};cf.default=q1});var pb=A(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});var fb=U(),B1=Q(),U1=Nt(),V1=of(),H1={message:({params:{len:r}})=>(0,fb.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,fb._)`{limit: ${r}}`},z1={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:H1,code(r){let{schema:e,parentSchema:t,it:n}=r,{prefixItems:i}=t;n.items=!0,!(0,B1.alwaysValidSchema)(n,e)&&(i?(0,V1.validateAdditionalItems)(r,i):r.ok((0,U1.validateArray)(r)))}};lf.default=z1});var hb=A(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});var Ft=U(),ic=Q(),K1={message:({params:{min:r,max:e}})=>e===void 0?(0,Ft.str)`must contain at least ${r} valid item(s)`:(0,Ft.str)`must contain at least ${r} and no more than ${e} valid item(s)`,params:({params:{min:r,max:e}})=>e===void 0?(0,Ft._)`{minContains: ${r}}`:(0,Ft._)`{minContains: ${r}, maxContains: ${e}}`},W1={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:K1,code(r){let{gen:e,schema:t,parentSchema:n,data:i,it:s}=r,o,a,{minContains:c,maxContains:l}=n;s.opts.next?(o=c===void 0?1:c,a=l):o=1;let u=e.const("len",(0,Ft._)`${i}.length`);if(r.setParams({min:o,max:a}),a===void 0&&o===0){(0,ic.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,ic.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,ic.alwaysValidSchema)(s,t)){let h=(0,Ft._)`${u} >= ${o}`;a!==void 0&&(h=(0,Ft._)`${h} && ${u} <= ${a}`),r.pass(h);return}s.items=!0;let d=e.name("valid");a===void 0&&o===1?p(d,()=>e.if(d,()=>e.break())):o===0?(e.let(d,!0),a!==void 0&&e.if((0,Ft._)`${i}.length > 0`,f)):(e.let(d,!1),f()),r.result(d,()=>r.reset());function f(){let h=e.name("_valid"),y=e.let("count",0);p(h,()=>e.if(h,()=>m(y)))}function p(h,y){e.forRange("i",0,u,g=>{r.subschema({keyword:"contains",dataProp:g,dataPropType:ic.Type.Num,compositeRule:!0},h),y()})}function m(h){e.code((0,Ft._)`${h}++`),a===void 0?e.if((0,Ft._)`${h} >= ${o}`,()=>e.assign(d,!0).break()):(e.if((0,Ft._)`${h} > ${a}`,()=>e.assign(d,!1).break()),o===1?e.assign(d,!0):e.if((0,Ft._)`${h} >= ${o}`,()=>e.assign(d,!0)))}}};df.default=W1});var sc=A(br=>{"use strict";Object.defineProperty(br,"__esModule",{value:!0});br.validateSchemaDeps=br.validatePropertyDeps=br.error=void 0;var uf=U(),G1=Q(),po=Nt();br.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let n=e===1?"property":"properties";return(0,uf.str)`must have ${n} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:n}})=>(0,uf._)`{property: ${r}, +var tE=Object.create;var Ma=Object.defineProperty;var rE=Object.getOwnPropertyDescriptor;var nE=Object.getOwnPropertyNames;var iE=Object.getPrototypeOf,sE=Object.prototype.hasOwnProperty;var ly=(r,e)=>()=>(r&&(e=r(r=0)),e);var A=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),dy=(r,e)=>{for(var t in e)Ma(r,t,{get:e[t],enumerable:!0})},uy=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of nE(e))!sE.call(r,i)&&i!==t&&Ma(r,i,{get:()=>e[i],enumerable:!(n=rE(e,i))||n.enumerable});return r};var Kn=(r,e,t)=>(t=r!=null?tE(iE(r)):{},uy(e||!r||!r.__esModule?Ma(t,"default",{value:r,enumerable:!0}):t,r)),oE=r=>uy(Ma({},"__esModule",{value:!0}),r);var Bs=A(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.regexpCode=se.getEsmExportName=se.getProperty=se.safeStringify=se.stringify=se.strConcat=se.addCodeArg=se.str=se._=se.nil=se._Code=se.Name=se.IDENTIFIER=se._CodeOrName=void 0;var js=class{};se._CodeOrName=js;se.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Gn=class extends js{constructor(e){if(super(),!se.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};se.Name=Gn;var Ot=class extends js{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((t,n)=>`${t}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((t,n)=>(n instanceof Gn&&(t[n.str]=(t[n.str]||0)+1),t),{})}};se._Code=Ot;se.nil=new Ot("");function hy(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=Bs(),Bd=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Ia;(function(r){r[r.Started=0]="Started",r[r.Completed=1]="Completed"})(Ia||(dt.UsedValueState=Ia={}));dt.varKinds={const:new lt.Name("const"),let:new lt.Name("let"),var:new lt.Name("var")};var Oa=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=Oa;var Da=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=Da;var _E=(0,lt._)`\n`,Ud=class extends Oa{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?_E:lt.nil}}get(){return this._scope}name(e){return new Da(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,Ia.Started);let u=t(l);if(u){let d=this.opts.es5?dt.varKinds.var:dt.varKinds.const;s=(0,lt._)`${s}${d} ${l} = ${u};${this.opts._n}`}else if(u=i?.(l))s=(0,lt._)`${s}${u}${this.opts._n}`;else throw new Bd(l);c.set(l,Ia.Completed)})}return s}};dt.ValueScope=Ud});var U=A(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.or=Y.and=Y.not=Y.CodeGen=Y.operators=Y.varKinds=Y.ValueScopeName=Y.ValueScope=Y.Scope=Y.Name=Y.regexpCode=Y.stringify=Y.getProperty=Y.nil=Y.strConcat=Y.str=Y._=void 0;var re=Bs(),Jt=Vd(),an=Bs();Object.defineProperty(Y,"_",{enumerable:!0,get:function(){return an._}});Object.defineProperty(Y,"str",{enumerable:!0,get:function(){return an.str}});Object.defineProperty(Y,"strConcat",{enumerable:!0,get:function(){return an.strConcat}});Object.defineProperty(Y,"nil",{enumerable:!0,get:function(){return an.nil}});Object.defineProperty(Y,"getProperty",{enumerable:!0,get:function(){return an.getProperty}});Object.defineProperty(Y,"stringify",{enumerable:!0,get:function(){return an.stringify}});Object.defineProperty(Y,"regexpCode",{enumerable:!0,get:function(){return an.regexpCode}});Object.defineProperty(Y,"Name",{enumerable:!0,get:function(){return an.Name}});var ja=Vd();Object.defineProperty(Y,"Scope",{enumerable:!0,get:function(){return ja.Scope}});Object.defineProperty(Y,"ValueScope",{enumerable:!0,get:function(){return ja.ValueScope}});Object.defineProperty(Y,"ValueScopeName",{enumerable:!0,get:function(){return ja.ValueScopeName}});Object.defineProperty(Y,"varKinds",{enumerable:!0,get:function(){return ja.varKinds}});Y.operators={GT:new re._Code(">"),GTE:new re._Code(">="),LT:new re._Code("<"),LTE:new re._Code("<="),EQ:new re._Code("==="),NEQ:new re._Code("!=="),NOT:new re._Code("!"),OR:new re._Code("||"),AND:new re._Code("&&"),ADD:new re._Code("+")};var Nr=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},Hd=class extends Nr{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let n=e?Jt.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=Ci(this.rhs,e,t)),this}get names(){return this.rhs instanceof re._CodeOrName?this.rhs.names:{}}},Na=class extends Nr{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(!(this.lhs instanceof re.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Ci(this.rhs,e,t),this}get names(){let e=this.lhs instanceof re.Name?{}:{...this.lhs.names};return Fa(e,this.rhs)}},zd=class extends Na{constructor(e,t,n,i){super(e,n,i),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Kd=class extends Nr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Wd=class extends Nr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Gd=class extends Nr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Jd=class extends Nr{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=Ci(this.code,e,t),this}get names(){return this.code instanceof re._CodeOrName?this.code.names:{}}},Us=class extends Nr{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)||(SE(e,s.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>Xn(e,t.names),{})}},Lr=class extends Us{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Yd=class extends Us{},Mi=class extends Lr{};Mi.kind="else";var Jn=class r extends Lr{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 Mi(n):n}if(t)return e===!1?t instanceof r?t:t.nodes:this.nodes.length?this:new r(yy(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=Ci(this.condition,e,t),this}get names(){let e=super.names;return Fa(e,this.condition),this.else&&Xn(e,this.else.names),e}};Jn.kind="if";var Yn=class extends Lr{};Yn.kind="for";var Xd=class extends Yn{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=Ci(this.iteration,e,t),this}get names(){return Xn(super.names,this.iteration.names)}},Qd=class extends Yn{constructor(e,t,n,i){super(),this.varKind=e,this.name=t,this.from=n,this.to=i}render(e){let t=e.es5?Jt.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=Fa(super.names,this.from);return Fa(e,this.to)}},La=class extends Yn{constructor(e,t,n,i){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=i}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=Ci(this.iterable,e,t),this}get names(){return Xn(super.names,this.iterable.names)}},Vs=class extends Lr{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)}};Vs.kind="func";var Hs=class extends Us{render(e){return"return "+super.render(e)}};Hs.kind="return";var Zd=class extends Lr{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(t=this.finally)===null||t===void 0||t.optimizeNodes(),this}optimizeNames(e,t){var n,i;return super.optimizeNames(e,t),(n=this.catch)===null||n===void 0||n.optimizeNames(e,t),(i=this.finally)===null||i===void 0||i.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&Xn(e,this.catch.names),this.finally&&Xn(e,this.finally.names),e}},zs=class extends Lr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};zs.kind="catch";var Ks=class extends Lr{render(e){return"finally"+super.render(e)}};Ks.kind="finally";var eu=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?` +`:""},this._extScope=e,this._scope=new Jt.Scope({parent:e}),this._nodes=[new Yd]}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 Hd(e,s,n)),s}const(e,t,n){return this._def(Jt.varKinds.const,e,t,n)}let(e,t,n){return this._def(Jt.varKinds.let,e,t,n)}var(e,t,n){return this._def(Jt.varKinds.var,e,t,n)}assign(e,t,n){return this._leafNode(new Na(e,t,n))}add(e,t){return this._leafNode(new zd(e,Y.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==re.nil&&this._leafNode(new Jd(e)),this}object(...e){let t=["{"];for(let[n,i]of e)t.length>1&&t.push(","),t.push(n),(n!==i||this.opts.es5)&&(t.push(":"),(0,re.addCodeArg)(t,i));return t.push("}"),new re._Code(t)}if(e,t,n){if(this._blockNode(new Jn(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Jn(e))}else(){return this._elseNode(new Mi)}endIf(){return this._endBlockNode(Jn,Mi)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new Xd(e),t)}forRange(e,t,n,i,s=this.opts.es5?Jt.varKinds.var:Jt.varKinds.let){let o=this._scope.toName(e);return this._for(new Qd(s,o,t,n),()=>i(o))}forOf(e,t,n,i=Jt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let o=t instanceof re.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0,re._)`${o}.length`,a=>{this.var(s,(0,re._)`${o}[${a}]`),n(s)})}return this._for(new La("of",i,s,t),()=>n(s))}forIn(e,t,n,i=this.opts.es5?Jt.varKinds.var:Jt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,re._)`Object.keys(${t})`,n);let s=this._scope.toName(e);return this._for(new La("in",i,s,t),()=>n(s))}endFor(){return this._endBlockNode(Yn)}label(e){return this._leafNode(new Kd(e))}break(e){return this._leafNode(new Wd(e))}return(e){let t=new Hs;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Hs)}try(e,t,n){if(!t&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new Zd;if(this._blockNode(i),this.code(e),t){let s=this.name("e");this._currNode=i.catch=new zs(s),t(s)}return n&&(this._currNode=i.finally=new Ks,this.code(n)),this._endBlockNode(zs,Ks)}throw(e){return this._leafNode(new Gd(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=re.nil,n,i){return this._blockNode(new Vs(e,t,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(Vs)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof Jn))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};Y.CodeGen=eu;function Xn(r,e){for(let t in e)r[t]=(r[t]||0)+(e[t]||0);return r}function Fa(r,e){return e instanceof re._CodeOrName?Xn(r,e.names):r}function Ci(r,e,t){if(r instanceof re.Name)return n(r);if(!i(r))return r;return new re._Code(r._items.reduce((s,o)=>(o instanceof re.Name&&(o=n(o)),o instanceof re._Code?s.push(...o._items):s.push(o),s),[]));function n(s){let o=t[s.str];return o===void 0||e[s.str]!==1?s:(delete e[s.str],o)}function i(s){return s instanceof re._Code&&s._items.some(o=>o instanceof re.Name&&e[o.str]===1&&t[o.str]!==void 0)}}function SE(r,e){for(let t in e)r[t]=(r[t]||0)-(e[t]||0)}function yy(r){return typeof r=="boolean"||typeof r=="number"||r===null?!r:(0,re._)`!${tu(r)}`}Y.not=yy;var xE=gy(Y.operators.AND);function $E(...r){return r.reduce(xE)}Y.and=$E;var EE=gy(Y.operators.OR);function AE(...r){return r.reduce(EE)}Y.or=AE;function gy(r){return(e,t)=>e===re.nil?t:t===re.nil?e:(0,re._)`${tu(e)} ${r} ${tu(t)}`}function tu(r){return r instanceof re.Name?r:(0,re._)`(${r})`}});var Q=A(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.checkStrictMode=X.getErrorPath=X.Type=X.useFunc=X.setEvaluated=X.evaluatedPropsToName=X.mergeEvaluated=X.eachItem=X.unescapeJsonPointer=X.escapeJsonPointer=X.escapeFragment=X.unescapeFragment=X.schemaRefOrVal=X.schemaHasRulesButRef=X.schemaHasRules=X.checkUnknownRules=X.alwaysValidSchema=X.toHash=void 0;var de=U(),kE=Bs();function PE(r){let e={};for(let t of r)e[t]=!0;return e}X.toHash=PE;function ME(r,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(wy(r,e),!_y(e,r.self.RULES.all))}X.alwaysValidSchema=ME;function wy(r,e=r.schema){let{opts:t,self:n}=r;if(!t.strictSchema||typeof e=="boolean")return;let i=n.RULES.keywords;for(let s in e)i[s]||$y(r,`unknown keyword: "${s}"`)}X.checkUnknownRules=wy;function _y(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(e[t])return!0;return!1}X.schemaHasRules=_y;function CE(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(t!=="$ref"&&e.all[t])return!0;return!1}X.schemaHasRulesButRef=CE;function TE({topSchemaRef:r,schemaPath:e},t,n,i){if(!i){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return(0,de._)`${t}`}return(0,de._)`${r}${e}${(0,de.getProperty)(n)}`}X.schemaRefOrVal=TE;function RE(r){return Sy(decodeURIComponent(r))}X.unescapeFragment=RE;function IE(r){return encodeURIComponent(nu(r))}X.escapeFragment=IE;function nu(r){return typeof r=="number"?`${r}`:r.replace(/~/g,"~0").replace(/\//g,"~1")}X.escapeJsonPointer=nu;function Sy(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}X.unescapeJsonPointer=Sy;function OE(r,e){if(Array.isArray(r))for(let t of r)e(t);else e(r)}X.eachItem=OE;function by({mergeNames:r,mergeToName:e,mergeValues:t,resultToName:n}){return(i,s,o,a)=>{let c=o===void 0?s:o instanceof de.Name?(s instanceof de.Name?r(i,s,o):e(i,s,o),o):s instanceof de.Name?(e(i,o,s),s):t(s,o);return a===de.Name&&!(c instanceof de.Name)?n(i,c):c}}X.mergeEvaluated={props:by({mergeNames:(r,e,t)=>r.if((0,de._)`${t} !== true && ${e} !== undefined`,()=>{r.if((0,de._)`${e} === true`,()=>r.assign(t,!0),()=>r.assign(t,(0,de._)`${t} || {}`).code((0,de._)`Object.assign(${t}, ${e})`))}),mergeToName:(r,e,t)=>r.if((0,de._)`${t} !== true`,()=>{e===!0?r.assign(t,!0):(r.assign(t,(0,de._)`${t} || {}`),iu(r,t,e))}),mergeValues:(r,e)=>r===!0?!0:{...r,...e},resultToName:xy}),items:by({mergeNames:(r,e,t)=>r.if((0,de._)`${t} !== true && ${e} !== undefined`,()=>r.assign(t,(0,de._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(r,e,t)=>r.if((0,de._)`${t} !== true`,()=>r.assign(t,e===!0?!0:(0,de._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(r,e)=>r===!0?!0:Math.max(r,e),resultToName:(r,e)=>r.var("items",e)})};function xy(r,e){if(e===!0)return r.var("props",!0);let t=r.var("props",(0,de._)`{}`);return e!==void 0&&iu(r,t,e),t}X.evaluatedPropsToName=xy;function iu(r,e,t){Object.keys(t).forEach(n=>r.assign((0,de._)`${e}${(0,de.getProperty)(n)}`,!0))}X.setEvaluated=iu;var vy={};function DE(r,e){return r.scopeValue("func",{ref:e,code:vy[e.code]||(vy[e.code]=new kE._Code(e.code))})}X.useFunc=DE;var ru;(function(r){r[r.Num=0]="Num",r[r.Str=1]="Str"})(ru||(X.Type=ru={}));function NE(r,e,t){if(r instanceof de.Name){let n=e===ru.Num;return t?n?(0,de._)`"[" + ${r} + "]"`:(0,de._)`"['" + ${r} + "']"`:n?(0,de._)`"/" + ${r}`:(0,de._)`"/" + ${r}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0,de.getProperty)(r).toString():"/"+nu(r)}X.getErrorPath=NE;function $y(r,e,t=r.opts.strictSchema){if(t){if(e=`strict mode: ${e}`,t===!0)throw new Error(e);r.self.logger.warn(e)}}X.checkStrictMode=$y});var Dt=A(su=>{"use strict";Object.defineProperty(su,"__esModule",{value:!0});var Ue=U(),LE={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")};su.default=LE});var Ws=A(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.extendErrors=Ve.resetErrorsCount=Ve.reportExtraError=Ve.reportError=Ve.keyword$DataError=Ve.keywordError=void 0;var ie=U(),qa=Q(),et=Dt();Ve.keywordError={message:({keyword:r})=>(0,ie.str)`must pass "${r}" keyword validation`};Ve.keyword$DataError={message:({keyword:r,schemaType:e})=>e?(0,ie.str)`"${r}" keyword must be ${e} ($data)`:(0,ie.str)`"${r}" keyword is invalid ($data)`};function FE(r,e=Ve.keywordError,t,n){let{it:i}=r,{gen:s,compositeRule:o,allErrors:a}=i,c=ky(r,e,t);n??(o||a)?Ey(s,c):Ay(i,(0,ie._)`[${c}]`)}Ve.reportError=FE;function jE(r,e=Ve.keywordError,t){let{it:n}=r,{gen:i,compositeRule:s,allErrors:o}=n,a=ky(r,e,t);Ey(i,a),s||o||Ay(n,et.default.vErrors)}Ve.reportExtraError=jE;function qE(r,e){r.assign(et.default.errors,e),r.if((0,ie._)`${et.default.vErrors} !== null`,()=>r.if(e,()=>r.assign((0,ie._)`${et.default.vErrors}.length`,e),()=>r.assign(et.default.vErrors,null)))}Ve.resetErrorsCount=qE;function BE({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,et.default.errors,a=>{r.const(o,(0,ie._)`${et.default.vErrors}[${a}]`),r.if((0,ie._)`${o}.instancePath === undefined`,()=>r.assign((0,ie._)`${o}.instancePath`,(0,ie.strConcat)(et.default.instancePath,s.errorPath))),r.assign((0,ie._)`${o}.schemaPath`,(0,ie.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(r.assign((0,ie._)`${o}.schema`,t),r.assign((0,ie._)`${o}.data`,n))})}Ve.extendErrors=BE;function Ey(r,e){let t=r.const("err",e);r.if((0,ie._)`${et.default.vErrors} === null`,()=>r.assign(et.default.vErrors,(0,ie._)`[${t}]`),(0,ie._)`${et.default.vErrors}.push(${t})`),r.code((0,ie._)`${et.default.errors}++`)}function Ay(r,e){let{gen:t,validateName:n,schemaEnv:i}=r;i.$async?t.throw((0,ie._)`new ${r.ValidationError}(${e})`):(t.assign((0,ie._)`${n}.errors`,e),t.return(!1))}var Qn={keyword:new ie.Name("keyword"),schemaPath:new ie.Name("schemaPath"),params:new ie.Name("params"),propertyName:new ie.Name("propertyName"),message:new ie.Name("message"),schema:new ie.Name("schema"),parentSchema:new ie.Name("parentSchema")};function ky(r,e,t){let{createErrors:n}=r.it;return n===!1?(0,ie._)`{}`:UE(r,e,t)}function UE(r,e,t={}){let{gen:n,it:i}=r,s=[VE(i,t),HE(r,t)];return zE(r,e,s),n.object(...s)}function VE({errorPath:r},{instancePath:e}){let t=e?(0,ie.str)`${r}${(0,qa.getErrorPath)(e,qa.Type.Str)}`:r;return[et.default.instancePath,(0,ie.strConcat)(et.default.instancePath,t)]}function HE({keyword:r,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:n}){let i=n?e:(0,ie.str)`${e}/${r}`;return t&&(i=(0,ie.str)`${i}${(0,qa.getErrorPath)(t,qa.Type.Str)}`),[Qn.schemaPath,i]}function zE(r,{params:e,message:t},n){let{keyword:i,data:s,schemaValue:o,it:a}=r,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;n.push([Qn.keyword,i],[Qn.params,typeof e=="function"?e(r):e||(0,ie._)`{}`]),c.messages&&n.push([Qn.message,typeof t=="function"?t(r):t]),c.verbose&&n.push([Qn.schema,o],[Qn.parentSchema,(0,ie._)`${u}${d}`],[et.default.data,s]),l&&n.push([Qn.propertyName,l])}});var My=A(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.boolOrEmptySchema=Ti.topBoolOrEmptySchema=void 0;var KE=Ws(),WE=U(),GE=Dt(),JE={message:"boolean schema is false"};function YE(r){let{gen:e,schema:t,validateName:n}=r;t===!1?Py(r,!1):typeof t=="object"&&t.$async===!0?e.return(GE.default.data):(e.assign((0,WE._)`${n}.errors`,null),e.return(!0))}Ti.topBoolOrEmptySchema=YE;function XE(r,e){let{gen:t,schema:n}=r;n===!1?(t.var(e,!1),Py(r)):t.var(e,!0)}Ti.boolOrEmptySchema=XE;function Py(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,KE.reportError)(i,JE,void 0,e)}});var ou=A(Ri=>{"use strict";Object.defineProperty(Ri,"__esModule",{value:!0});Ri.getRules=Ri.isJSONType=void 0;var QE=["string","number","integer","boolean","null","object","array"],ZE=new Set(QE);function eA(r){return typeof r=="string"&&ZE.has(r)}Ri.isJSONType=eA;function tA(){let r={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...r,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},r.number,r.string,r.array,r.object],post:{rules:[]},all:{},keywords:{}}}Ri.getRules=tA});var au=A(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.shouldUseRule=cn.shouldUseGroup=cn.schemaHasRulesForType=void 0;function rA({schema:r,self:e},t){let n=e.RULES.types[t];return n&&n!==!0&&Cy(r,n)}cn.schemaHasRulesForType=rA;function Cy(r,e){return e.rules.some(t=>Ty(r,t))}cn.shouldUseGroup=Cy;function Ty(r,e){var t;return r[e.keyword]!==void 0||((t=e.definition.implements)===null||t===void 0?void 0:t.some(n=>r[n]!==void 0))}cn.shouldUseRule=Ty});var Gs=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 nA=ou(),iA=au(),sA=Ws(),z=U(),Ry=Q(),Ii;(function(r){r[r.Correct=0]="Correct",r[r.Wrong=1]="Wrong"})(Ii||(He.DataType=Ii={}));function oA(r){let e=Iy(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=oA;function Iy(r){let e=Array.isArray(r)?r:r?[r]:[];if(e.every(nA.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}He.getJSONTypes=Iy;function aA(r,e){let{gen:t,data:n,opts:i}=r,s=cA(e,i.coerceTypes),o=e.length>0&&!(s.length===0&&e.length===1&&(0,iA.schemaHasRulesForType)(r,e[0]));if(o){let a=lu(e,n,i.strictNumbers,Ii.Wrong);t.if(a,()=>{s.length?lA(r,e,s):du(r)})}return o}He.coerceAndCheckDataType=aA;var Oy=new Set(["string","number","integer","boolean","null"]);function cA(r,e){return e?r.filter(t=>Oy.has(t)||e==="array"&&t==="array"):[]}function lA(r,e,t){let{gen:n,data:i,opts:s}=r,o=n.let("dataType",(0,z._)`typeof ${i}`),a=n.let("coerced",(0,z._)`undefined`);s.coerceTypes==="array"&&n.if((0,z._)`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,z._)`${i}[0]`).assign(o,(0,z._)`typeof ${i}`).if(lu(e,i,s.strictNumbers),()=>n.assign(a,i))),n.if((0,z._)`${a} !== undefined`);for(let l of t)(Oy.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),du(r),n.endIf(),n.if((0,z._)`${a} !== undefined`,()=>{n.assign(i,a),dA(r,a)});function c(l){switch(l){case"string":n.elseIf((0,z._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,z._)`"" + ${i}`).elseIf((0,z._)`${i} === null`).assign(a,(0,z._)`""`);return;case"number":n.elseIf((0,z._)`${o} == "boolean" || ${i} === null + || (${o} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,z._)`+${i}`);return;case"integer":n.elseIf((0,z._)`${o} === "boolean" || ${i} === null + || (${o} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(a,(0,z._)`+${i}`);return;case"boolean":n.elseIf((0,z._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(a,!1).elseIf((0,z._)`${i} === "true" || ${i} === 1`).assign(a,!0);return;case"null":n.elseIf((0,z._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(a,null);return;case"array":n.elseIf((0,z._)`${o} === "string" || ${o} === "number" + || ${o} === "boolean" || ${i} === null`).assign(a,(0,z._)`[${i}]`)}}}function dA({gen:r,parentData:e,parentDataProperty:t},n){r.if((0,z._)`${e} !== undefined`,()=>r.assign((0,z._)`${e}[${t}]`,n))}function cu(r,e,t,n=Ii.Correct){let i=n===Ii.Correct?z.operators.EQ:z.operators.NEQ,s;switch(r){case"null":return(0,z._)`${e} ${i} null`;case"array":s=(0,z._)`Array.isArray(${e})`;break;case"object":s=(0,z._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=o((0,z._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=o();break;default:return(0,z._)`typeof ${e} ${i} ${r}`}return n===Ii.Correct?s:(0,z.not)(s);function o(a=z.nil){return(0,z.and)((0,z._)`typeof ${e} == "number"`,a,t?(0,z._)`isFinite(${e})`:z.nil)}}He.checkDataType=cu;function lu(r,e,t,n){if(r.length===1)return cu(r[0],e,t,n);let i,s=(0,Ry.toHash)(r);if(s.array&&s.object){let o=(0,z._)`typeof ${e} != "object"`;i=s.null?o:(0,z._)`!${e} || ${o}`,delete s.null,delete s.array,delete s.object}else i=z.nil;s.number&&delete s.integer;for(let o in s)i=(0,z.and)(i,cu(o,e,t,n));return i}He.checkDataTypes=lu;var uA={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,z._)`{type: ${r}}`:(0,z._)`{type: ${e}}`};function du(r){let e=fA(r);(0,sA.reportError)(e,uA)}He.reportTypeError=du;function fA(r){let{gen:e,data:t,schema:n}=r,i=(0,Ry.schemaRefOrVal)(r,n,"type");return{gen:e,keyword:"type",data:t,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:r}}});var Ny=A(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.assignDefaults=void 0;var Oi=U(),pA=Q();function hA(r,e){let{properties:t,items:n}=r.schema;if(e==="object"&&t)for(let i in t)Dy(r,i,t[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,s)=>Dy(r,s,i.default))}Ba.assignDefaults=hA;function Dy(r,e,t){let{gen:n,compositeRule:i,data:s,opts:o}=r;if(t===void 0)return;let a=(0,Oi._)`${s}${(0,Oi.getProperty)(e)}`;if(i){(0,pA.checkStrictMode)(r,`default is ignored for: ${a}`);return}let c=(0,Oi._)`${a} === undefined`;o.useDefaults==="empty"&&(c=(0,Oi._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Oi._)`${a} = ${(0,Oi.stringify)(t)}`)}});var Nt=A(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.validateUnion=le.validateArray=le.usePattern=le.callValidateCode=le.schemaProperties=le.allSchemaProperties=le.noPropertyInData=le.propertyInData=le.isOwnProperty=le.hasPropFunc=le.reportMissingProp=le.checkMissingProp=le.checkReportMissingProp=void 0;var me=U(),uu=Q(),ln=Dt(),mA=Q();function yA(r,e){let{gen:t,data:n,it:i}=r;t.if(pu(t,n,e,i.opts.ownProperties),()=>{r.setParams({missingProperty:(0,me._)`${e}`},!0),r.error()})}le.checkReportMissingProp=yA;function gA({gen:r,data:e,it:{opts:t}},n,i){return(0,me.or)(...n.map(s=>(0,me.and)(pu(r,e,s,t.ownProperties),(0,me._)`${i} = ${s}`)))}le.checkMissingProp=gA;function bA(r,e){r.setParams({missingProperty:e},!0),r.error()}le.reportMissingProp=bA;function Ly(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,me._)`Object.prototype.hasOwnProperty`})}le.hasPropFunc=Ly;function fu(r,e,t){return(0,me._)`${Ly(r)}.call(${e}, ${t})`}le.isOwnProperty=fu;function vA(r,e,t,n){let i=(0,me._)`${e}${(0,me.getProperty)(t)} !== undefined`;return n?(0,me._)`${i} && ${fu(r,e,t)}`:i}le.propertyInData=vA;function pu(r,e,t,n){let i=(0,me._)`${e}${(0,me.getProperty)(t)} === undefined`;return n?(0,me.or)(i,(0,me.not)(fu(r,e,t))):i}le.noPropertyInData=pu;function Fy(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}le.allSchemaProperties=Fy;function wA(r,e){return Fy(e).filter(t=>!(0,uu.alwaysValidSchema)(r,e[t]))}le.schemaProperties=wA;function _A({schemaCode:r,data:e,it:{gen:t,topSchemaRef:n,schemaPath:i,errorPath:s},it:o},a,c,l){let u=l?(0,me._)`${r}, ${e}, ${n}${i}`:e,d=[[ln.default.instancePath,(0,me.strConcat)(ln.default.instancePath,s)],[ln.default.parentData,o.parentData],[ln.default.parentDataProperty,o.parentDataProperty],[ln.default.rootData,ln.default.rootData]];o.opts.dynamicRef&&d.push([ln.default.dynamicAnchors,ln.default.dynamicAnchors]);let f=(0,me._)`${u}, ${t.object(...d)}`;return c!==me.nil?(0,me._)`${a}.call(${c}, ${f})`:(0,me._)`${a}(${f})`}le.callValidateCode=_A;var SA=(0,me._)`new RegExp`;function xA({gen:r,it:{opts:e}},t){let n=e.unicodeRegExp?"u":"",{regExp:i}=e.code,s=i(t,n);return r.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,me._)`${i.code==="new RegExp"?SA:(0,mA.useFunc)(r,i)}(${t}, ${n})`})}le.usePattern=xA;function $A(r){let{gen:e,data:t,keyword:n,it:i}=r,s=e.name("valid");if(i.allErrors){let a=e.let("valid",!0);return o(()=>e.assign(a,!1)),a}return e.var(s,!0),o(()=>e.break()),s;function o(a){let c=e.const("len",(0,me._)`${t}.length`);e.forRange("i",0,c,l=>{r.subschema({keyword:n,dataProp:l,dataPropType:uu.Type.Num},s),e.if((0,me.not)(s),a)})}}le.validateArray=$A;function EA(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,uu.alwaysValidSchema)(i,c))&&!i.opts.unevaluated)return;let o=e.let("valid",!1),a=e.name("_valid");e.block(()=>t.forEach((c,l)=>{let u=r.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);e.assign(o,(0,me._)`${o} || ${a}`),r.mergeValidEvaluated(u,a)||e.if((0,me.not)(o))})),r.result(o,()=>r.reset(),()=>r.error(!0))}le.validateUnion=EA});var By=A(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.validateKeywordUsage=yr.validSchemaType=yr.funcKeywordCode=yr.macroKeywordCode=void 0;var tt=U(),Zn=Dt(),AA=Nt(),kA=Ws();function PA(r,e){let{gen:t,keyword:n,schema:i,parentSchema:s,it:o}=r,a=e.macro.call(o.self,i,s,o),c=qy(t,n,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);let l=t.name("valid");r.subschema({schema:a,schemaPath:tt.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),r.pass(l,()=>r.error(!0))}yr.macroKeywordCode=PA;function MA(r,e){var t;let{gen:n,keyword:i,schema:s,parentSchema:o,$data:a,it:c}=r;TA(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,o,c):e.validate,u=qy(n,i,l),d=n.let("valid");r.block$data(d,f),r.ok((t=e.valid)!==null&&t!==void 0?t:d);function f(){if(e.errors===!1)m(),e.modifying&&jy(r),y(()=>r.error());else{let g=e.async?p():h();e.modifying&&jy(r),y(()=>CA(r,g))}}function p(){let g=n.let("ruleErrs",null);return n.try(()=>m((0,tt._)`await `),b=>n.assign(d,!1).if((0,tt._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(g,(0,tt._)`${b}.errors`),()=>n.throw(b))),g}function h(){let g=(0,tt._)`${u}.errors`;return n.assign(g,null),m(tt.nil),g}function m(g=e.async?(0,tt._)`await `:tt.nil){let b=c.opts.passContext?Zn.default.this:Zn.default.self,v=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,tt._)`${g}${(0,AA.callValidateCode)(r,u,b,v)}`,e.modifying)}function y(g){var b;n.if((0,tt.not)((b=e.valid)!==null&&b!==void 0?b:d),g)}}yr.funcKeywordCode=MA;function jy(r){let{gen:e,data:t,it:n}=r;e.if(n.parentData,()=>e.assign(t,(0,tt._)`${n.parentData}[${n.parentDataProperty}]`))}function CA(r,e){let{gen:t}=r;t.if((0,tt._)`Array.isArray(${e})`,()=>{t.assign(Zn.default.vErrors,(0,tt._)`${Zn.default.vErrors} === null ? ${e} : ${Zn.default.vErrors}.concat(${e})`).assign(Zn.default.errors,(0,tt._)`${Zn.default.vErrors}.length`),(0,kA.extendErrors)(r)},()=>r.error())}function TA({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function qy(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,tt.stringify)(t)})}function RA(r,e,t=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(r):n==="object"?r&&typeof r=="object"&&!Array.isArray(r):typeof r==n||t&&typeof r>"u")}yr.validSchemaType=RA;function IA({schema:r,opts:e,self:t,errSchemaPath:n},i,s){if(Array.isArray(i.keyword)?!i.keyword.includes(s):i.keyword!==s)throw new Error("ajv implementation error");let o=i.dependencies;if(o?.some(a=>!Object.prototype.hasOwnProperty.call(r,a)))throw new Error(`parent schema must have dependencies of ${s}: ${o.join(",")}`);if(i.validateSchema&&!i.validateSchema(r[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+t.errorsText(i.validateSchema.errors);if(e.validateSchema==="log")t.logger.error(c);else throw new Error(c)}}yr.validateKeywordUsage=IA});var Vy=A(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.extendSubschemaMode=dn.extendSubschemaData=dn.getSubschema=void 0;var gr=U(),Uy=Q();function OA(r,{keyword:e,schemaProp:t,schema:n,schemaPath:i,errSchemaPath:s,topSchemaRef:o}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=r.schema[e];return t===void 0?{schema:a,schemaPath:(0,gr._)`${r.schemaPath}${(0,gr.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:a[t],schemaPath:(0,gr._)`${r.schemaPath}${(0,gr.getProperty)(e)}${(0,gr.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,Uy.escapeFragment)(t)}`}}if(n!==void 0){if(i===void 0||s===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:o,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}dn.getSubschema=OA;function DA(r,e,{dataProp:t,dataPropType:n,data:i,dataTypes:s,propertyName:o}){if(i!==void 0&&t!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(t!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=e,f=a.let("data",(0,gr._)`${e.data}${(0,gr.getProperty)(t)}`,!0);c(f),r.errorPath=(0,gr.str)`${l}${(0,Uy.getErrorPath)(t,n,d.jsPropertySyntax)}`,r.parentDataProperty=(0,gr._)`${t}`,r.dataPathArr=[...u,r.parentDataProperty]}if(i!==void 0){let l=i instanceof gr.Name?i:a.let("data",i,!0);c(l),o!==void 0&&(r.propertyName=o)}s&&(r.dataTypes=s);function c(l){r.data=l,r.dataLevel=e.dataLevel+1,r.dataTypes=[],e.definedProperties=new Set,r.parentData=e.data,r.dataNames=[...e.dataNames,l]}}dn.extendSubschemaData=DA;function NA(r,{jtdDiscriminator:e,jtdMetadata:t,compositeRule:n,createErrors:i,allErrors:s}){n!==void 0&&(r.compositeRule=n),i!==void 0&&(r.createErrors=i),s!==void 0&&(r.allErrors=s),r.jtdDiscriminator=e,r.jtdMetadata=t}dn.extendSubschemaMode=NA});var hu=A((Tj,Hy)=>{"use strict";Hy.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 Ky=A((Rj,zy)=>{"use strict";var un=zy.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(){};Ua(e,n,i,r,"",r)};un.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};un.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};un.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};un.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Ua(r,e,t,n,i,s,o,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,i,s,o,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in un.arrayKeywords)for(var f=0;f{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.getSchemaRefs=ut.resolveUrl=ut.normalizeId=ut._getFullPath=ut.getFullPath=ut.inlineRef=void 0;var FA=Q(),jA=hu(),qA=Ky(),BA=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function UA(r,e=!0){return typeof r=="boolean"?!0:e===!0?!mu(r):e?Wy(r)<=e:!1}ut.inlineRef=UA;var VA=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function mu(r){for(let e in r){if(VA.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(mu)||typeof t=="object"&&mu(t))return!0}return!1}function Wy(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!BA.has(t)&&(typeof r[t]=="object"&&(0,FA.eachItem)(r[t],n=>e+=Wy(n)),e===1/0))return 1/0}return e}function Gy(r,e="",t){t!==!1&&(e=Di(e));let n=r.parse(e);return Jy(r,n)}ut.getFullPath=Gy;function Jy(r,e){return r.serialize(e).split("#")[0]+"#"}ut._getFullPath=Jy;var HA=/#\/?$/;function Di(r){return r?r.replace(HA,""):""}ut.normalizeId=Di;function zA(r,e,t){return t=Di(t),r.resolve(e,t)}ut.resolveUrl=zA;var KA=/^[a-z_][-a-z0-9._]*$/i;function WA(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:n}=this.opts,i=Di(r[t]||e),s={"":i},o=Gy(n,i,!1),a={},c=new Set;return qA(r,{allKeys:!0},(d,f,p,h)=>{if(h===void 0)return;let m=o+f,y=s[h];typeof d[t]=="string"&&(y=g.call(this,d[t])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),s[f]=y;function g(v){let S=this.opts.uriResolver.resolve;if(v=Di(y?S(y,v):v),c.has(v))throw u(v);c.add(v);let _=this.refs[v];return typeof _=="string"&&(_=this.refs[_]),typeof _=="object"?l(d,_.schema,v):v!==Di(m)&&(v[0]==="#"?(l(d,a[v],v),a[v]=d):this.refs[v]=m),v}function b(v){if(typeof v=="string"){if(!KA.test(v))throw new Error(`invalid anchor "${v}"`);g.call(this,`#${v}`)}}}),a;function l(d,f,p){if(f!==void 0&&!jA(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}ut.getSchemaRefs=WA});var Ni=A(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.getData=fn.KeywordCxt=fn.validateFunctionCode=void 0;var eg=My(),Yy=Gs(),gu=au(),Va=Gs(),GA=Ny(),Xs=By(),yu=Vy(),j=U(),B=Dt(),JA=Js(),Fr=Q(),Ys=Ws();function YA(r){if(ng(r)&&(ig(r),rg(r))){ZA(r);return}tg(r,()=>(0,eg.topBoolOrEmptySchema)(r))}fn.validateFunctionCode=YA;function tg({gen:r,validateName:e,schema:t,schemaEnv:n,opts:i},s){i.code.es5?r.func(e,(0,j._)`${B.default.data}, ${B.default.valCxt}`,n.$async,()=>{r.code((0,j._)`"use strict"; ${Xy(t,i)}`),QA(r,i),r.code(s)}):r.func(e,(0,j._)`${B.default.data}, ${XA(i)}`,n.$async,()=>r.code(Xy(t,i)).code(s))}function XA(r){return(0,j._)`{${B.default.instancePath}="", ${B.default.parentData}, ${B.default.parentDataProperty}, ${B.default.rootData}=${B.default.data}${r.dynamicRef?(0,j._)`, ${B.default.dynamicAnchors}={}`:j.nil}}={}`}function QA(r,e){r.if(B.default.valCxt,()=>{r.var(B.default.instancePath,(0,j._)`${B.default.valCxt}.${B.default.instancePath}`),r.var(B.default.parentData,(0,j._)`${B.default.valCxt}.${B.default.parentData}`),r.var(B.default.parentDataProperty,(0,j._)`${B.default.valCxt}.${B.default.parentDataProperty}`),r.var(B.default.rootData,(0,j._)`${B.default.valCxt}.${B.default.rootData}`),e.dynamicRef&&r.var(B.default.dynamicAnchors,(0,j._)`${B.default.valCxt}.${B.default.dynamicAnchors}`)},()=>{r.var(B.default.instancePath,(0,j._)`""`),r.var(B.default.parentData,(0,j._)`undefined`),r.var(B.default.parentDataProperty,(0,j._)`undefined`),r.var(B.default.rootData,B.default.data),e.dynamicRef&&r.var(B.default.dynamicAnchors,(0,j._)`{}`)})}function ZA(r){let{schema:e,opts:t,gen:n}=r;tg(r,()=>{t.$comment&&e.$comment&&og(r),ik(r),n.let(B.default.vErrors,null),n.let(B.default.errors,0),t.unevaluated&&ek(r),sg(r),ak(r)})}function ek(r){let{gen:e,validateName:t}=r;r.evaluated=e.const("evaluated",(0,j._)`${t}.evaluated`),e.if((0,j._)`${r.evaluated}.dynamicProps`,()=>e.assign((0,j._)`${r.evaluated}.props`,(0,j._)`undefined`)),e.if((0,j._)`${r.evaluated}.dynamicItems`,()=>e.assign((0,j._)`${r.evaluated}.items`,(0,j._)`undefined`))}function Xy(r,e){let t=typeof r=="object"&&r[e.schemaId];return t&&(e.code.source||e.code.process)?(0,j._)`/*# sourceURL=${t} */`:j.nil}function tk(r,e){if(ng(r)&&(ig(r),rg(r))){rk(r,e);return}(0,eg.boolOrEmptySchema)(r,e)}function rg({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 ng(r){return typeof r.schema!="boolean"}function rk(r,e){let{schema:t,gen:n,opts:i}=r;i.$comment&&t.$comment&&og(r),sk(r),ok(r);let s=n.const("_errs",B.default.errors);sg(r,s),n.var(e,(0,j._)`${s} === ${B.default.errors}`)}function ig(r){(0,Fr.checkUnknownRules)(r),nk(r)}function sg(r,e){if(r.opts.jtd)return Qy(r,[],!1,e);let t=(0,Yy.getSchemaTypes)(r.schema),n=(0,Yy.coerceAndCheckDataType)(r,t);Qy(r,t,!n,e)}function nk(r){let{schema:e,errSchemaPath:t,opts:n,self:i}=r;e.$ref&&n.ignoreKeywordsWithRef&&(0,Fr.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function ik(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,Fr.checkStrictMode)(r,"default is ignored in the schema root")}function sk(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,JA.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function ok(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function og({gen:r,schemaEnv:e,schema:t,errSchemaPath:n,opts:i}){let s=t.$comment;if(i.$comment===!0)r.code((0,j._)`${B.default.self}.logger.log(${s})`);else if(typeof i.$comment=="function"){let o=(0,j.str)`${n}/$comment`,a=r.scopeValue("root",{ref:e.root});r.code((0,j._)`${B.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function ak(r){let{gen:e,schemaEnv:t,validateName:n,ValidationError:i,opts:s}=r;t.$async?e.if((0,j._)`${B.default.errors} === 0`,()=>e.return(B.default.data),()=>e.throw((0,j._)`new ${i}(${B.default.vErrors})`)):(e.assign((0,j._)`${n}.errors`,B.default.vErrors),s.unevaluated&&ck(r),e.return((0,j._)`${B.default.errors} === 0`))}function ck({gen:r,evaluated:e,props:t,items:n}){t instanceof j.Name&&r.assign((0,j._)`${e}.props`,t),n instanceof j.Name&&r.assign((0,j._)`${e}.items`,n)}function Qy(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,Fr.schemaHasRulesButRef)(s,u))){i.block(()=>cg(r,"$ref",u.all.$ref.definition));return}c.jtd||lk(r,e),i.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,gu.shouldUseGroup)(s,f)&&(f.type?(i.if((0,Va.checkDataType)(f.type,o,c.strictNumbers)),Zy(r,f),e.length===1&&e[0]===f.type&&t&&(i.else(),(0,Va.reportTypeError)(r)),i.endIf()):Zy(r,f),a||i.if((0,j._)`${B.default.errors} === ${n||0}`))}}function Zy(r,e){let{gen:t,schema:n,opts:{useDefaults:i}}=r;i&&(0,GA.assignDefaults)(r,e.type),t.block(()=>{for(let s of e.rules)(0,gu.shouldUseRule)(n,s)&&cg(r,s.keyword,s.definition,e.type)})}function lk(r,e){r.schemaEnv.meta||!r.opts.strictTypes||(dk(r,e),r.opts.allowUnionTypes||uk(r,e),fk(r,r.dataTypes))}function dk(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{ag(r.dataTypes,t)||bu(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),hk(r,e)}}function uk(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&bu(r,"use allowUnionTypes to allow union type keyword")}function fk(r,e){let t=r.self.RULES.all;for(let n in t){let i=t[n];if(typeof i=="object"&&(0,gu.shouldUseRule)(r.schema,i)){let{type:s}=i.definition;s.length&&!s.some(o=>pk(e,o))&&bu(r,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function pk(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function ag(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function hk(r,e){let t=[];for(let n of r.dataTypes)ag(e,n)?t.push(n):e.includes("integer")&&n==="number"&&t.push("integer");r.dataTypes=t}function bu(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,Fr.checkStrictMode)(r,e,r.opts.strictTypes)}var Ha=class{constructor(e,t,n){if((0,Xs.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,Fr.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",lg(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Xs.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const("_errs",B.default.errors))}result(e,t,n){this.failResult((0,j.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,j.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,j._)`${t} !== undefined && (${(0,j.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?Ys.reportExtraError:Ys.reportError)(this,this.def.error,t)}$dataError(){(0,Ys.reportError)(this,this.def.$dataError||Ys.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Ys.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=j.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=j.nil,t=j.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:s,def:o}=this;n.if((0,j.or)((0,j._)`${i} === undefined`,t)),e!==j.nil&&n.assign(e,!0),(s.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==j.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:i,it:s}=this;return(0,j.or)(o(),a());function o(){if(n.length){if(!(t instanceof j.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,j._)`${(0,Va.checkDataTypes)(c,t,s.opts.strictNumbers,Va.DataType.Wrong)}`}return j.nil}function a(){if(i.validateSchema){let c=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,j._)`!${c}(${t})`}return j.nil}}subschema(e,t){let n=(0,yu.getSubschema)(this.it,e);(0,yu.extendSubschemaData)(n,this.it,e),(0,yu.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return tk(i,t),i}mergeEvaluated(e,t){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Fr.mergeEvaluated.props(i,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=Fr.mergeEvaluated.items(i,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(t,()=>this.mergeEvaluated(e,j.Name)),!0}};fn.KeywordCxt=Ha;function cg(r,e,t,n){let i=new Ha(r,t,e);"code"in t?t.code(i,n):i.$data&&t.validate?(0,Xs.funcKeywordCode)(i,t):"macro"in t?(0,Xs.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0,Xs.funcKeywordCode)(i,t)}var mk=/^\/(?:[^~]|~0|~1)*$/,yk=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function lg(r,{dataLevel:e,dataNames:t,dataPathArr:n}){let i,s;if(r==="")return B.default.rootData;if(r[0]==="/"){if(!mk.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);i=r,s=B.default.rootData}else{let l=yk.exec(r);if(!l)throw new Error(`Invalid JSON-pointer: ${r}`);let u=+l[1];if(i=l[2],i==="#"){if(u>=e)throw new Error(c("property/index",u));return n[e-u]}if(u>e)throw new Error(c("data",u));if(s=t[e-u],!i)return s}let o=s,a=i.split("/");for(let l of a)l&&(s=(0,j._)`${s}${(0,j.getProperty)((0,Fr.unescapeJsonPointer)(l))}`,o=(0,j._)`${o} && ${s}`);return o;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}fn.getData=lg});var Qs=A(wu=>{"use strict";Object.defineProperty(wu,"__esModule",{value:!0});var vu=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};wu.default=vu});var Li=A(xu=>{"use strict";Object.defineProperty(xu,"__esModule",{value:!0});var _u=Js(),Su=class extends Error{constructor(e,t,n,i){super(i||`can't resolve reference ${n} from id ${t}`),this.missingRef=(0,_u.resolveUrl)(e,t,n),this.missingSchema=(0,_u.normalizeId)((0,_u.getFullPath)(e,this.missingRef))}};xu.default=Su});var Zs=A(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.resolveSchema=Lt.getCompilingSchema=Lt.resolveRef=Lt.compileSchema=Lt.SchemaEnv=void 0;var Yt=U(),gk=Qs(),ei=Dt(),Xt=Js(),dg=Q(),bk=Ni(),Fi=class{constructor(e){var t;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:(0,Xt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Lt.SchemaEnv=Fi;function Eu(r){let e=ug.call(this,r);if(e)return e;let t=(0,Xt.getFullPath)(this.opts.uriResolver,r.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:s}=this.opts,o=new Yt.CodeGen(this.scope,{es5:n,lines:i,ownProperties:s}),a;r.$async&&(a=o.scopeValue("Error",{ref:gk.default,code:(0,Yt._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");r.validateName=c;let l={gen:o,allErrors:this.opts.allErrors,data:ei.default.data,parentData:ei.default.parentData,parentDataProperty:ei.default.parentDataProperty,dataNames:[ei.default.data],dataPathArr:[Yt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:r.schema,code:(0,Yt.stringify)(r.schema)}:{ref:r.schema}),validateName:c,ValidationError:a,schema:r.schema,schemaEnv:r,rootId:t,baseId:r.baseId||t,schemaPath:Yt.nil,errSchemaPath:r.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Yt._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(r),(0,bk.validateFunctionCode)(l),o.optimize(this.opts.code.optimize);let d=o.toString();u=`${o.scopeRefs(ei.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,r));let p=new Function(`${ei.default.self}`,`${ei.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=r.schema,p.schemaEnv=r,r.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:o._values}),this.opts.unevaluated){let{props:h,items:m}=l;p.evaluated={props:h instanceof Yt.Name?void 0:h,items:m instanceof Yt.Name?void 0:m,dynamicProps:h instanceof Yt.Name,dynamicItems:m instanceof Yt.Name},p.source&&(p.source.evaluated=(0,Yt.stringify)(p.evaluated))}return r.validate=p,r}catch(d){throw delete r.validate,delete r.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(r)}}Lt.compileSchema=Eu;function vk(r,e,t){var n;t=(0,Xt.resolveUrl)(this.opts.uriResolver,e,t);let i=r.refs[t];if(i)return i;let s=Sk.call(this,r,t);if(s===void 0){let o=(n=r.localRefs)===null||n===void 0?void 0:n[t],{schemaId:a}=this.opts;o&&(s=new Fi({schema:o,schemaId:a,root:r,baseId:e}))}if(s!==void 0)return r.refs[t]=wk.call(this,s)}Lt.resolveRef=vk;function wk(r){return(0,Xt.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:Eu.call(this,r)}function ug(r){for(let e of this._compilations)if(_k(e,r))return e}Lt.getCompilingSchema=ug;function _k(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function Sk(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||za.call(this,r,e)}function za(r,e){let t=this.opts.uriResolver.parse(e),n=(0,Xt._getFullPath)(this.opts.uriResolver,t),i=(0,Xt.getFullPath)(this.opts.uriResolver,r.baseId,void 0);if(Object.keys(r.schema).length>0&&n===i)return $u.call(this,t,r);let s=(0,Xt.normalizeId)(n),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=za.call(this,r,o);return typeof a?.schema!="object"?void 0:$u.call(this,t,a)}if(typeof o?.schema=="object"){if(o.validate||Eu.call(this,o),s===(0,Xt.normalizeId)(e)){let{schema:a}=o,{schemaId:c}=this.opts,l=a[c];return l&&(i=(0,Xt.resolveUrl)(this.opts.uriResolver,i,l)),new Fi({schema:a,schemaId:c,root:r,baseId:i})}return $u.call(this,t,o)}}Lt.resolveSchema=za;var xk=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function $u(r,{baseId:e,schema:t,root:n}){var i;if(((i=r.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let a of r.fragment.slice(1).split("/")){if(typeof t=="boolean")return;let c=t[(0,dg.unescapeFragment)(a)];if(c===void 0)return;t=c;let l=typeof t=="object"&&t[this.opts.schemaId];!xk.has(a)&&l&&(e=(0,Xt.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof t!="boolean"&&t.$ref&&!(0,dg.schemaHasRulesButRef)(t,this.RULES)){let a=(0,Xt.resolveUrl)(this.opts.uriResolver,e,t.$ref);s=za.call(this,n,a)}let{schemaId:o}=this.opts;if(s=s||new Fi({schema:t,schemaId:o,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var fg=A((Fj,$k)=>{$k.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Tu=A((jj,vg)=>{"use strict";var Ek=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),ku=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),Ak=RegExp.prototype.test.bind(/^\d*$/u),ti=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Pu=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),hg=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Mu=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),kk=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),ft=new Array(256);{let r="0123456789ABCDEF";for(let e=0;e<256;e++)ft[e]="%"+r[e>>4]+r[e&15]}function ze(r){return r<2048?ft[192|r>>6]+ft[128|r&63]:r<65536?ft[224|r>>12]+ft[128|r>>6&63]+ft[128|r&63]:ft[240|r>>18]+ft[128|r>>12&63]+ft[128|r>>6&63]+ft[128|r&63]}function Pk(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 Mk=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),Ck=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),Tk=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),Rk=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Ik(r){if(r.length===0)return!1;for(let e=0;et&&(t=i,e=n)):(n=-1,i=0);if(t<2)return r.join(":");let s=r.slice(0,e).join(":"),o=r.slice(e+t).join(":");return s+"::"+o}function Ok(r){let e=r.indexOf("::");if(e!==-1&&r.indexOf("::",e+1)!==-1)return;let t=e===-1?r.split(":"):r.slice(0,e).split(":"),n=e===-1?[]:r.slice(e+2).split(":");e!==-1&&(t.length===1&&t[0]===""&&(t.length=0),n.length===1&&n[0]===""&&(n.length=0));let i=t.concat(n),s=0;for(let a=0;a=8)return;let o=i.slice(0,t.length);for(let a=s;a<8;a++)o.push("0");for(let a=t.length;aLk[n])}function yg(r,e=!1){if(r.indexOf("%")===-1)return r;let t="";for(let n=0;n57343)e+=ze(i);else if(i<=56319&&t+1=56320&&s<=57343?(e+=ze(65536+(i-55296<<10)+(s-56320)),t++):e+=ze(65533)}else e+=ze(65533)}}return e}function Bk(r,e=!1){let t="",n=e&&r[0]!=="/";for(let i=0;i57343)t+=ze(o);else if(o<=56319&&i+1=56320&&a<=57343?(t+=ze(65536+(o-55296<<10)+(a-56320)),i++):t+=ze(65533)}else t+=ze(65533)}}return t}function Cu(r,e){let t="";for(let n=0;n57343)t+=ze(s);else if(s<=56319&&n+1=56320&&o<=57343?(t+=ze(65536+(s-55296<<10)+(o-56320)),n++):t+=ze(65533)}else t+=ze(65533)}}return t}function gg(r){return Cu(r,kk)}function Uk(r){return Cu(r,Mu)}function Vk(r){return Cu(r,Mu)}function bg(r){return r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||r===42||r===43||r===45||r===46||r===47||r===64||r===95}function Hk(r){let e="";for(let t=0;t57343)e+=ze(i);else if(i<=56319&&t+1=56320&&s<=57343?(e+=ze(65536+(i-55296<<10)+(s-56320)),t++):e+=ze(65533)}else e+=ze(65533)}}return e}function zk(r){let e="";for(let t=0;t{"use strict";var{isUUID:Wk}=Tu(),Gk=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,Jk=["http","https","ws","wss","urn","urn:uuid"];function Yk(r){return Jk.indexOf(r)!==-1}function Ru(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 wg(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function _g(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 Xk(r){return r.secure=Ru(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function Qk(r){if((r.port===(Ru(r)?443:80)||r.port==="")&&(r.port=void 0),typeof r.secure=="boolean"&&(r.scheme=r.secure?"wss":"ws",r.secure=void 0),r.resourceName){let e=r.resourceName.indexOf("?"),t=e===-1?r.resourceName:r.resourceName.slice(0,e);r.path=t&&t!=="/"?t:void 0,r.query=e===-1?void 0:r.resourceName.slice(e+1),r.resourceName=void 0}return r.fragment=void 0,r}function Zk(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(Gk);if(t&&t[0]===r.path){let n=e.scheme||r.scheme||"urn";r.nid=t[1].toLowerCase(),r.nss=t[2];let i=`${n}:${e.nid||r.nid}`,s=Iu(i);r.path=void 0,s&&(r=s.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function eP(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=Iu(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 tP(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!Wk(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function rP(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var Sg={scheme:"http",domainHost:!0,parse:wg,serialize:_g},nP={scheme:"https",domainHost:Sg.domainHost,parse:wg,serialize:_g},Ka={scheme:"ws",domainHost:!0,parse:Xk,serialize:Qk},iP={scheme:"wss",domainHost:Ka.domainHost,parse:Ka.parse,serialize:Ka.serialize},sP={scheme:"urn",parse:Zk,serialize:eP,skipNormalize:!0},oP={scheme:"urn:uuid",parse:tP,serialize:rP,skipNormalize:!0},Wa={http:Sg,https:nP,ws:Ka,wss:iP,urn:sP,"urn:uuid":oP};Object.setPrototypeOf(Wa,null);function Iu(r){return r&&(Wa[r]||Wa[r.toLowerCase()])||void 0}xg.exports={wsIsSecure:Ru,SCHEMES:Wa,isValidSchemeName:Yk,getSchemeHandler:Iu}});var Fg=A((Bj,Ya)=>{"use strict";var{normalizeIPv6:Mg,removeDotSegments:to,recomposeAuthority:aP,normalizePercentEncoding:Cg,normalizePathEncoding:cP,serializePathEncoding:Eg,normalizeQueryFragmentEncoding:Ag,encodeQuery:lP,encodeFragment:dP,reescapeHostDelimiters:uP,isIPv4:Tg,nonSimpleDomain:fP}=Tu(),{SCHEMES:Rg,getSchemeHandler:Ou}=$g(),Ig=/^[A-Za-z][A-Za-z0-9+.-]*$/u,Og="URI scheme is malformed.";function kg(r){let e=unescape(String(r));if(!Ig.test(e))throw new TypeError(Og);return e}function pP(r,e){return typeof r=="string"?r=_P(r,e):typeof r=="object"&&(r=Ja(ri(r,e),e)),r}function hP(r,e,t){let n=t?Object.assign({scheme:"null"},t):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:s,malformedPercentEncoding:o,malformedSchemeSpecific:a,malformedHost:c,malformedScheme:l}=Ga(r,n),{parsed:u,malformedAuthorityOrPort:d,malformedPercentEncoding:f,malformedSchemeSpecific:p,malformedHost:h,malformedScheme:m}=Ga(e,n);if(s||d||o||f||a||p||c||h||l||m)throw new Error(i.error||u.error||"URI is malformed.");let y=Dg(i,u,n,!0),g=Ou(t&&t.scheme||y.scheme),b=y.host,v=b!==void 0&&b!==""&&(Tg(b)||Mg(b).isIPV6);Ng(y,t||{},g,v);let S=b&&b.indexOf("%")!==-1&&!/\P{ASCII}/u.test(b);if(y.error&&!S)throw new Error(y.error);return n.skipEscape=!0,ri(y,n)}function Dg(r,e,t,n){let i={};return n||(r=Ja(ri(r,t),t),e=Ja(ri(e,t),t)),t=t||{},!t.tolerant&&e.scheme?(i.scheme=e.scheme,i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=to(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=to(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=to(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=to(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 mP(r,e,t){let n=Pg(r,t),i=Pg(e,t);return n!==void 0&&i!==void 0&&n===i}function ri(r,e){let t={host:r.host,scheme:r.scheme,userinfo:r.userinfo,port:r.port,path:r.path,query:r.query,nid:r.nid,nss:r.nss,uuid:r.uuid,fragment:r.fragment,reference:r.reference,resourceName:r.resourceName,secure:r.secure,error:""},n=Object.assign({},e),i=[];t.scheme&&(t.scheme=kg(t.scheme));let s=Ou(n.scheme||t.scheme);s&&s.serialize&&s.serialize(t,n);let o=t.userinfo!==void 0||t.host!==void 0||t.port!==void 0,a=!n.skipEscape&&t.scheme===void 0&&!o;t.path!==void 0&&(n.skipEscape?t.path=Cg(t.path):t.path=Eg(t.path,a)),n.reference!=="suffix"&&t.scheme&&(t.scheme=kg(t.scheme),i.push(t.scheme,":"));let c=aP(t);if(c!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(c),t.path&&t.path[0]!=="/"&&i.push("/")),t.path!==void 0){let l=t.path;!n.absolutePath&&(!s||!s.absolutePath)&&(l=to(l)),a&&(l=Eg(l,!0)),c===void 0&&l[0]==="/"&&l[1]==="/"&&(l="/%2F"+l.slice(2)),i.push(l)}return t.query!==void 0&&i.push("?",lP(t.query)),t.fragment!==void 0&&i.push("#",dP(t.fragment)),i.join("")}var yP=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,gP=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,bP=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function vP(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 eo(r){if(r===void 0)return!1;let e=r.indexOf("%");for(;e!==-1;){if(e+2>=r.length||!/^[\da-f]{2}$/iu.test(r.slice(e+1,e+3)))return!0;e=r.indexOf("%",e+3)}return!1}function Du(r){return r[0]==="["&&r[r.length-1]==="]"}function wP(r){let e=r[4];return eo(r[3])||e!==void 0&&!Du(e)&&eo(e)||eo(r[6])||eo(r[7])||eo(r[8])}function Ng(r,e,t,n){if(!e.unicodeSupport&&(!t||!t.unicodeSupport)&&r.host&&!Du(r.host)&&(e.domainHost||t&&t.domainHost)&&n===!1&&fP(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(i){return r.error=r.error||"Host's domain name can not be converted to ASCII: "+i,!0}return!1}function Ga(r,e){let t=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=!1,s=!1,o=!1,a=!1,c=!1,l=!1,u=!1;t.reference==="suffix"&&(t.scheme?r=t.scheme+":"+r:r="//"+r);let d=r.match(gP);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let f=r.match(bP);if(f!==null){let h=f[1],m=h.replace(/[\t\n\r]/g,"");m.length>=2&&(m.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",i=!0):h.length!==m.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",i=!0))}let p=r.match(yP);if(p){if(n.scheme=p[1],n.userinfo=p[3],n.host=p[4],n.port=parseInt(p[5],10),n.path=p[6]||"",n.query=p[7],n.fragment=p[8],n.scheme!==void 0){let y=unescape(n.scheme);Ig.test(y)?n.scheme=y.toLowerCase():(n.error=n.error||Og,l=!0)}s=wP(p),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=p[5]);let h=vP(n,p);if(h!==void 0&&(n.error=n.error||h,i=!0),n.host)if(Tg(n.host)===!1){let g=Du(n.host),b=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,v=Mg(n.host);u=v.isIPV6||v.isIPVFuture===!0,c=b&&(!g||v.error===!0),n.host=u?v.host:v.host.toLowerCase(),c&&(n.error=n.error||"URI host is malformed.",i=!0)}else u=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",t.reference&&t.reference!=="suffix"&&t.reference!==n.reference&&(n.error=n.error||"URI is not a "+t.reference+" reference.");let m=Ou(t.scheme||n.scheme);if(c||(a=Ng(n,t,m,u)),!m||m&&!m.skipNormalize){if(r.indexOf("%")!==-1&&n.host!==void 0&&!c){let y=u?n.host:Cg(n.host,!0);n.host=uP(y,u)}n.path&&(n.path=cP(n.path)),n.query&&(n.query=Ag(n.query)),n.fragment&&(n.fragment=Ag(n.fragment))}m&&m.parse&&(m.parse(n,t),m===Rg.urn&&n.nid===void 0&&(o=!0))}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:i,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:a,malformedScheme:l}}function Ja(r,e){return Ga(r,e).parsed}function _P(r,e){return Lg(r,e).normalized}function Lg(r,e){let{parsed:t,malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:a}=Ga(r,e);return{normalized:n||i||s||o||a?r:ri(t,e),malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:a}}function Pg(r,e){if(typeof r!="string"&&typeof r!="object")return;let t;try{t=typeof r=="string"?r:ri(r,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:i,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:a,malformedScheme:c}=Lg(t,e);return i||s||o||a||c?void 0:n}var Nu={SCHEMES:Rg,normalize:pP,resolve:hP,resolveComponent:Dg,equal:mP,serialize:ri,parse:Ja};Ya.exports=Nu;Ya.exports.default=Nu;Ya.exports.fastUri=Nu});var qg=A(Lu=>{"use strict";Object.defineProperty(Lu,"__esModule",{value:!0});var jg=Fg();jg.code='require("ajv/dist/runtime/uri").default';Lu.default=jg});var qu=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 SP=Ni();Object.defineProperty(Le,"KeywordCxt",{enumerable:!0,get:function(){return SP.KeywordCxt}});var ji=U();Object.defineProperty(Le,"_",{enumerable:!0,get:function(){return ji._}});Object.defineProperty(Le,"str",{enumerable:!0,get:function(){return ji.str}});Object.defineProperty(Le,"stringify",{enumerable:!0,get:function(){return ji.stringify}});Object.defineProperty(Le,"nil",{enumerable:!0,get:function(){return ji.nil}});Object.defineProperty(Le,"Name",{enumerable:!0,get:function(){return ji.Name}});Object.defineProperty(Le,"CodeGen",{enumerable:!0,get:function(){return ji.CodeGen}});var xP=Qs(),zg=Li(),$P=ou(),ro=Zs(),EP=U(),no=Js(),Xa=Gs(),ju=Q(),Bg=fg(),AP=qg(),Kg=(r,e)=>new RegExp(r,e);Kg.code="new RegExp";var kP=["removeAdditional","useDefaults","coerceTypes"],PP=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),MP={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},CP={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Ug=200;function TP(r){var e,t,n,i,s,o,a,c,l,u,d,f,p,h,m,y,g,b,v,S,_,E,k,x,T;let $=r.strict,q=(e=r.code)===null||e===void 0?void 0:e.optimize,C=q===!0||q===void 0?1:q||0,V=(n=(t=r.code)===null||t===void 0?void 0:t.regExp)!==null&&n!==void 0?n:Kg,P=(i=r.uriResolver)!==null&&i!==void 0?i:AP.default;return{strictSchema:(o=(s=r.strictSchema)!==null&&s!==void 0?s:$)!==null&&o!==void 0?o:!0,strictNumbers:(c=(a=r.strictNumbers)!==null&&a!==void 0?a:$)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=r.strictTypes)!==null&&l!==void 0?l:$)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=r.strictTuples)!==null&&d!==void 0?d:$)!==null&&f!==void 0?f:"log",strictRequired:(h=(p=r.strictRequired)!==null&&p!==void 0?p:$)!==null&&h!==void 0?h:!1,code:r.code?{...r.code,optimize:C,regExp:V}:{optimize:C,regExp:V},loopRequired:(m=r.loopRequired)!==null&&m!==void 0?m:Ug,loopEnum:(y=r.loopEnum)!==null&&y!==void 0?y:Ug,meta:(g=r.meta)!==null&&g!==void 0?g:!0,messages:(b=r.messages)!==null&&b!==void 0?b:!0,inlineRefs:(v=r.inlineRefs)!==null&&v!==void 0?v:!0,schemaId:(S=r.schemaId)!==null&&S!==void 0?S:"$id",addUsedSchema:(_=r.addUsedSchema)!==null&&_!==void 0?_:!0,validateSchema:(E=r.validateSchema)!==null&&E!==void 0?E:!0,validateFormats:(k=r.validateFormats)!==null&&k!==void 0?k:!0,unicodeRegExp:(x=r.unicodeRegExp)!==null&&x!==void 0?x:!0,int32range:(T=r.int32range)!==null&&T!==void 0?T:!0,uriResolver:P}}var io=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,...TP(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new EP.ValueScope({scope:{},prefixes:PP,es5:t,lines:n}),this.logger=LP(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,$P.getRules)(),Vg.call(this,MP,e,"NOT SUPPORTED"),Vg.call(this,CP,e,"DEPRECATED","warn"),this._metaOpts=DP.call(this),e.formats&&IP.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&OP.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),RP.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,i=Bg;n==="id"&&(i={...Bg},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 zg.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,no.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=Hg.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:n}=this.opts,i=new ro.SchemaEnv({schema:{},schemaId:n});if(t=ro.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=Hg.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,no.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(jP.call(this,n,t),!t)return(0,ju.eachItem)(n,s=>Fu.call(this,s)),this;BP.call(this,t);let i={...t,type:(0,Xa.getJSONTypes)(t.type),schemaType:(0,Xa.getJSONTypes)(t.schemaType)};return(0,ju.eachItem)(n,i.type.length===0?s=>Fu.call(this,s,i):s=>i.type.forEach(o=>Fu.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]=Wg(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,no.normalizeId)(o||n);let l=no.getSchemaRefs.call(this,e,n);return c=new ro.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):ro.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{ro.compileSchema.call(this,e)}finally{this.opts=t}}};io.ValidationError=xP.default;io.MissingRefError=zg.default;Le.default=io;function Vg(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 Hg(r){return r=(0,no.normalizeId)(r),this.schemas[r]||this.refs[r]}function RP(){let r=this.opts.schemas;if(r)if(Array.isArray(r))this.addSchema(r);else for(let e in r)this.addSchema(r[e],e)}function IP(){for(let r in this.opts.formats){let e=this.opts.formats[r];e&&this.addFormat(r,e)}}function OP(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 DP(){let r={...this.opts};for(let e of kP)delete r[e];return r}var NP={log(){},warn(){},error(){}};function LP(r){if(r===!1)return NP;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 FP=/^[a-z_$][a-z0-9_$:-]*$/i;function jP(r,e){let{RULES:t}=this;if((0,ju.eachItem)(r,n=>{if(t.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!FP.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 Fu(r,e,t){var n;let i=e?.post;if(t&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,o=i?s.post:s.rules.find(({type:c})=>c===t);if(o||(o={type:t,rules:[]},s.rules.push(o)),s.keywords[r]=!0,!e)return;let a={keyword:r,definition:{...e,type:(0,Xa.getJSONTypes)(e.type),schemaType:(0,Xa.getJSONTypes)(e.schemaType)}};e.before?qP.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 qP(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 BP(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=Wg(e)),r.validateSchema=this.compile(e,!0))}var UP={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Wg(r){return{anyOf:[r,UP]}}});var Gg=A(Bu=>{"use strict";Object.defineProperty(Bu,"__esModule",{value:!0});var VP={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Bu.default=VP});var ec=A(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.callRef=ni.getValidate=void 0;var HP=Li(),Jg=Nt(),pt=U(),qi=Dt(),Yg=Zs(),Qa=Q(),zP={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=Yg.resolveRef.call(c,l,i,t);if(u===void 0)throw new HP.default(n.opts.uriResolver,i,t);if(u instanceof Yg.SchemaEnv)return f(u);return p(u);function d(){if(s===l)return Za(r,o,s,s.$async);let h=e.scopeValue("root",{ref:l});return Za(r,(0,pt._)`${h}.validate`,l,l.$async)}function f(h){let m=Xg(r,h);Za(r,m,h,h.$async)}function p(h){let m=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,pt.stringify)(h)}:{ref:h}),y=e.name("valid"),g=r.subschema({schema:h,dataTypes:[],schemaPath:pt.nil,topSchemaRef:m,errSchemaPath:t},y);r.mergeEvaluated(g),r.ok(y)}}};function Xg(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,pt._)`${t.scopeValue("wrapper",{ref:e})}.validate`}ni.getValidate=Xg;function Za(r,e,t,n){let{gen:i,it:s}=r,{allErrors:o,schemaEnv:a,opts:c}=s,l=c.passContext?qi.default.this:pt.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=i.let("valid");i.try(()=>{i.code((0,pt._)`await ${(0,Jg.callValidateCode)(r,e,l)}`),p(e),o||i.assign(h,!0)},m=>{i.if((0,pt._)`!(${m} instanceof ${s.ValidationError})`,()=>i.throw(m)),f(m),o||i.assign(h,!1)}),r.ok(h)}function d(){r.result((0,Jg.callValidateCode)(r,e,l),()=>p(e),()=>f(e))}function f(h){let m=(0,pt._)`${h}.errors`;i.assign(qi.default.vErrors,(0,pt._)`${qi.default.vErrors} === null ? ${m} : ${qi.default.vErrors}.concat(${m})`),i.assign(qi.default.errors,(0,pt._)`${qi.default.vErrors}.length`)}function p(h){var m;if(!s.opts.unevaluated)return;let y=(m=t?.validate)===null||m===void 0?void 0:m.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=Qa.mergeEvaluated.props(i,y.props,s.props));else{let g=i.var("props",(0,pt._)`${h}.evaluated.props`);s.props=Qa.mergeEvaluated.props(i,g,s.props,pt.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Qa.mergeEvaluated.items(i,y.items,s.items));else{let g=i.var("items",(0,pt._)`${h}.evaluated.items`);s.items=Qa.mergeEvaluated.items(i,g,s.items,pt.Name)}}}ni.callRef=Za;ni.default=zP});var Vu=A(Uu=>{"use strict";Object.defineProperty(Uu,"__esModule",{value:!0});var KP=Gg(),WP=ec(),GP=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",KP.default,WP.default];Uu.default=GP});var Qg=A(Hu=>{"use strict";Object.defineProperty(Hu,"__esModule",{value:!0});var tc=U(),pn=tc.operators,rc={maximum:{okStr:"<=",ok:pn.LTE,fail:pn.GT},minimum:{okStr:">=",ok:pn.GTE,fail:pn.LT},exclusiveMaximum:{okStr:"<",ok:pn.LT,fail:pn.GTE},exclusiveMinimum:{okStr:">",ok:pn.GT,fail:pn.LTE}},JP={message:({keyword:r,schemaCode:e})=>(0,tc.str)`must be ${rc[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,tc._)`{comparison: ${rc[r].okStr}, limit: ${e}}`},YP={keyword:Object.keys(rc),type:"number",schemaType:"number",$data:!0,error:JP,code(r){let{keyword:e,data:t,schemaCode:n}=r;r.fail$data((0,tc._)`${t} ${rc[e].fail} ${n} || isNaN(${t})`)}};Hu.default=YP});var Zg=A(zu=>{"use strict";Object.defineProperty(zu,"__esModule",{value:!0});var so=U(),XP={message:({schemaCode:r})=>(0,so.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,so._)`{multipleOf: ${r}}`},QP={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:XP,code(r){let{gen:e,data:t,schemaCode:n,it:i}=r,s=i.opts.multipleOfPrecision,o=e.let("res"),a=s?(0,so._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,so._)`${o} !== parseInt(${o})`;r.fail$data((0,so._)`(${n} === 0 || (${o} = ${t}/${n}, ${a}))`)}};zu.default=QP});var tb=A(Ku=>{"use strict";Object.defineProperty(Ku,"__esModule",{value:!0});function eb(r){let e=r.length,t=0,n=0,i;for(;n=55296&&i<=56319&&n{"use strict";Object.defineProperty(Wu,"__esModule",{value:!0});var ii=U(),ZP=Q(),e1=tb(),t1={message({keyword:r,schemaCode:e}){let t=r==="maxLength"?"more":"fewer";return(0,ii.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:r})=>(0,ii._)`{limit: ${r}}`},r1={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:t1,code(r){let{keyword:e,data:t,schemaCode:n,it:i}=r,s=e==="maxLength"?ii.operators.GT:ii.operators.LT,o=i.opts.unicode===!1?(0,ii._)`${t}.length`:(0,ii._)`${(0,ZP.useFunc)(r.gen,e1.default)}(${t})`;r.fail$data((0,ii._)`${o} ${s} ${n}`)}};Wu.default=r1});var nb=A(Gu=>{"use strict";Object.defineProperty(Gu,"__esModule",{value:!0});var n1=Nt(),i1=Q(),Bi=U(),s1={message:({schemaCode:r})=>(0,Bi.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,Bi._)`{pattern: ${r}}`},o1={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:s1,code(r){let{gen:e,data:t,$data:n,schema:i,schemaCode:s,it:o}=r,a=o.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=o.opts.code,l=c.code==="new RegExp"?(0,Bi._)`new RegExp`:(0,i1.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Bi._)`${l}(${s}, ${a}).test(${t})`),()=>e.assign(u,!1)),r.fail$data((0,Bi._)`!${u}`)}else{let c=(0,n1.usePattern)(r,i);r.fail$data((0,Bi._)`!${c}.test(${t})`)}}};Gu.default=o1});var ib=A(Ju=>{"use strict";Object.defineProperty(Ju,"__esModule",{value:!0});var oo=U(),a1={message({keyword:r,schemaCode:e}){let t=r==="maxProperties"?"more":"fewer";return(0,oo.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:r})=>(0,oo._)`{limit: ${r}}`},c1={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:a1,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxProperties"?oo.operators.GT:oo.operators.LT;r.fail$data((0,oo._)`Object.keys(${t}).length ${i} ${n}`)}};Ju.default=c1});var sb=A(Yu=>{"use strict";Object.defineProperty(Yu,"__esModule",{value:!0});var ao=Nt(),co=U(),l1=Q(),d1={message:({params:{missingProperty:r}})=>(0,co.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,co._)`{missingProperty: ${r}}`},u1={keyword:"required",type:"object",schemaType:"array",$data:!0,error:d1,code(r){let{gen:e,schema:t,schemaCode:n,data:i,$data:s,it:o}=r,{opts:a}=o;if(!s&&t.length===0)return;let c=t.length>=a.loopRequired;if(o.allErrors?l():u(),a.strictRequired){let p=r.parentSchema.properties,{definedProperties:h}=r.it;for(let m of t)if(p?.[m]===void 0&&!h.has(m)){let y=o.schemaEnv.baseId+o.errSchemaPath,g=`required property "${m}" is not defined at "${y}" (strictRequired)`;(0,l1.checkStrictMode)(o,g,o.opts.strictRequired)}}function l(){if(c||s)r.block$data(co.nil,d);else for(let p of t)(0,ao.checkReportMissingProp)(r,p)}function u(){let p=e.let("missing");if(c||s){let h=e.let("valid",!0);r.block$data(h,()=>f(p,h)),r.ok(h)}else e.if((0,ao.checkMissingProp)(r,t,p)),(0,ao.reportMissingProp)(r,p),e.else()}function d(){e.forOf("prop",n,p=>{r.setParams({missingProperty:p}),e.if((0,ao.noPropertyInData)(e,i,p,a.ownProperties),()=>r.error())})}function f(p,h){r.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(h,(0,ao.propertyInData)(e,i,p,a.ownProperties)),e.if((0,co.not)(h),()=>{r.error(),e.break()})},co.nil)}}};Yu.default=u1});var ob=A(Xu=>{"use strict";Object.defineProperty(Xu,"__esModule",{value:!0});var lo=U(),f1={message({keyword:r,schemaCode:e}){let t=r==="maxItems"?"more":"fewer";return(0,lo.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:r})=>(0,lo._)`{limit: ${r}}`},p1={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:f1,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxItems"?lo.operators.GT:lo.operators.LT;r.fail$data((0,lo._)`${t}.length ${i} ${n}`)}};Xu.default=p1});var nc=A(Qu=>{"use strict";Object.defineProperty(Qu,"__esModule",{value:!0});var ab=hu();ab.code='require("ajv/dist/runtime/equal").default';Qu.default=ab});var cb=A(ef=>{"use strict";Object.defineProperty(ef,"__esModule",{value:!0});var Zu=Gs(),Fe=U(),h1=Q(),m1=nc(),y1={message:({params:{i:r,j:e}})=>(0,Fe.str)`must NOT have duplicate items (items ## ${e} and ${r} are identical)`,params:({params:{i:r,j:e}})=>(0,Fe._)`{i: ${r}, j: ${e}}`},g1={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:y1,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,Zu.getSchemaTypes)(s.items):[];r.block$data(c,u,(0,Fe._)`${o} === false`),r.ok(c);function u(){let h=e.let("i",(0,Fe._)`${t}.length`),m=e.let("j");r.setParams({i:h,j:m}),e.assign(c,!0),e.if((0,Fe._)`${h} > 1`,()=>(d()?f:p)(h,m))}function d(){return l.length>0&&!l.some(h=>h==="object"||h==="array")}function f(h,m){let y=e.name("item"),g=(0,Zu.checkDataTypes)(l,y,a.opts.strictNumbers,Zu.DataType.Wrong),b=e.const("indices",(0,Fe._)`{}`);e.for((0,Fe._)`;${h}--;`,()=>{e.let(y,(0,Fe._)`${t}[${h}]`),e.if(g,(0,Fe._)`continue`),l.length>1&&e.if((0,Fe._)`typeof ${y} == "string"`,(0,Fe._)`${y} += "_"`),e.if((0,Fe._)`typeof ${b}[${y}] == "number"`,()=>{e.assign(m,(0,Fe._)`${b}[${y}]`),r.error(),e.assign(c,!1).break()}).code((0,Fe._)`${b}[${y}] = ${h}`)})}function p(h,m){let y=(0,h1.useFunc)(e,m1.default),g=e.name("outer");e.label(g).for((0,Fe._)`;${h}--;`,()=>e.for((0,Fe._)`${m} = ${h}; ${m}--;`,()=>e.if((0,Fe._)`${y}(${t}[${h}], ${t}[${m}])`,()=>{r.error(),e.assign(c,!1).break(g)})))}}};ef.default=g1});var lb=A(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});var tf=U(),b1=Q(),v1=nc(),w1={message:"must be equal to constant",params:({schemaCode:r})=>(0,tf._)`{allowedValue: ${r}}`},_1={keyword:"const",$data:!0,error:w1,code(r){let{gen:e,data:t,$data:n,schemaCode:i,schema:s}=r;n||s&&typeof s=="object"?r.fail$data((0,tf._)`!${(0,b1.useFunc)(e,v1.default)}(${t}, ${i})`):r.fail((0,tf._)`${s} !== ${t}`)}};rf.default=_1});var db=A(nf=>{"use strict";Object.defineProperty(nf,"__esModule",{value:!0});var uo=U(),S1=Q(),x1=nc(),$1={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,uo._)`{allowedValues: ${r}}`},E1={keyword:"enum",schemaType:"array",$data:!0,error:$1,code(r){let{gen:e,data:t,$data:n,schema:i,schemaCode:s,it:o}=r;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let a=i.length>=o.opts.loopEnum,c,l=()=>c??(c=(0,S1.useFunc)(e,x1.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,uo.or)(...i.map((h,m)=>f(p,m)))}r.pass(u);function d(){e.assign(u,!1),e.forOf("v",s,p=>e.if((0,uo._)`${l()}(${t}, ${p})`,()=>e.assign(u,!0).break()))}function f(p,h){let m=i[h];return typeof m=="object"&&m!==null?(0,uo._)`${l()}(${t}, ${p}[${h}])`:(0,uo._)`${t} === ${m}`}}};nf.default=E1});var of=A(sf=>{"use strict";Object.defineProperty(sf,"__esModule",{value:!0});var A1=Qg(),k1=Zg(),P1=rb(),M1=nb(),C1=ib(),T1=sb(),R1=ob(),I1=cb(),O1=lb(),D1=db(),N1=[A1.default,k1.default,P1.default,M1.default,C1.default,T1.default,R1.default,I1.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},O1.default,D1.default];sf.default=N1});var cf=A(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.validateAdditionalItems=void 0;var si=U(),af=Q(),L1={message:({params:{len:r}})=>(0,si.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,si._)`{limit: ${r}}`},F1={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:L1,code(r){let{parentSchema:e,it:t}=r,{items:n}=e;if(!Array.isArray(n)){(0,af.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}ub(r,n)}};function ub(r,e){let{gen:t,schema:n,data:i,keyword:s,it:o}=r;o.items=!0;let a=t.const("len",(0,si._)`${i}.length`);if(n===!1)r.setParams({len:e.length}),r.pass((0,si._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,af.alwaysValidSchema)(o,n)){let l=t.var("valid",(0,si._)`${a} <= ${e.length}`);t.if((0,si.not)(l),()=>c(l)),r.ok(l)}function c(l){t.forRange("i",e.length,a,u=>{r.subschema({keyword:s,dataProp:u,dataPropType:af.Type.Num},l),o.allErrors||t.if((0,si.not)(l),()=>t.break())})}}fo.validateAdditionalItems=ub;fo.default=F1});var lf=A(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});po.validateTuple=void 0;var fb=U(),ic=Q(),j1=Nt(),q1={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return pb(r,"additionalItems",e);t.items=!0,!(0,ic.alwaysValidSchema)(t,e)&&r.ok((0,j1.validateArray)(r))}};function pb(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=ic.mergeEvaluated.items(n,t.length,a.items));let c=n.name("valid"),l=n.const("len",(0,fb._)`${s}.length`);t.forEach((d,f)=>{(0,ic.alwaysValidSchema)(a,d)||(n.if((0,fb._)`${l} > ${f}`,()=>r.subschema({keyword:o,schemaProp:f,dataProp:f},c)),r.ok(c))});function u(d){let{opts:f,errSchemaPath:p}=a,h=t.length,m=h===d.minItems&&(h===d.maxItems||d[e]===!1);if(f.strictTuples&&!m){let y=`"${o}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,ic.checkStrictMode)(a,y,f.strictTuples)}}}po.validateTuple=pb;po.default=q1});var hb=A(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});var B1=lf(),U1={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,B1.validateTuple)(r,"items")};df.default=U1});var yb=A(uf=>{"use strict";Object.defineProperty(uf,"__esModule",{value:!0});var mb=U(),V1=Q(),H1=Nt(),z1=cf(),K1={message:({params:{len:r}})=>(0,mb.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,mb._)`{limit: ${r}}`},W1={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:K1,code(r){let{schema:e,parentSchema:t,it:n}=r,{prefixItems:i}=t;n.items=!0,!(0,V1.alwaysValidSchema)(n,e)&&(i?(0,z1.validateAdditionalItems)(r,i):r.ok((0,H1.validateArray)(r)))}};uf.default=W1});var gb=A(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var Ft=U(),sc=Q(),G1={message:({params:{min:r,max:e}})=>e===void 0?(0,Ft.str)`must contain at least ${r} valid item(s)`:(0,Ft.str)`must contain at least ${r} and no more than ${e} valid item(s)`,params:({params:{min:r,max:e}})=>e===void 0?(0,Ft._)`{minContains: ${r}}`:(0,Ft._)`{minContains: ${r}, maxContains: ${e}}`},J1={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:G1,code(r){let{gen:e,schema:t,parentSchema:n,data:i,it:s}=r,o,a,{minContains:c,maxContains:l}=n;s.opts.next?(o=c===void 0?1:c,a=l):o=1;let u=e.const("len",(0,Ft._)`${i}.length`);if(r.setParams({min:o,max:a}),a===void 0&&o===0){(0,sc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,sc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,sc.alwaysValidSchema)(s,t)){let m=(0,Ft._)`${u} >= ${o}`;a!==void 0&&(m=(0,Ft._)`${m} && ${u} <= ${a}`),r.pass(m);return}s.items=!0;let d=e.name("valid");a===void 0&&o===1?p(d,()=>e.if(d,()=>e.break())):o===0?(e.let(d,!0),a!==void 0&&e.if((0,Ft._)`${i}.length > 0`,f)):(e.let(d,!1),f()),r.result(d,()=>r.reset());function f(){let m=e.name("_valid"),y=e.let("count",0);p(m,()=>e.if(m,()=>h(y)))}function p(m,y){e.forRange("i",0,u,g=>{r.subschema({keyword:"contains",dataProp:g,dataPropType:sc.Type.Num,compositeRule:!0},m),y()})}function h(m){e.code((0,Ft._)`${m}++`),a===void 0?e.if((0,Ft._)`${m} >= ${o}`,()=>e.assign(d,!0).break()):(e.if((0,Ft._)`${m} > ${a}`,()=>e.assign(d,!1).break()),o===1?e.assign(d,!0):e.if((0,Ft._)`${m} >= ${o}`,()=>e.assign(d,!0)))}}};ff.default=J1});var oc=A(br=>{"use strict";Object.defineProperty(br,"__esModule",{value:!0});br.validateSchemaDeps=br.validatePropertyDeps=br.error=void 0;var pf=U(),Y1=Q(),ho=Nt();br.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let n=e===1?"property":"properties";return(0,pf.str)`must have ${n} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:n}})=>(0,pf._)`{property: ${r}, missingProperty: ${n}, depsCount: ${e}, - deps: ${t}}`};var J1={keyword:"dependencies",type:"object",schemaType:"object",error:br.error,code(r){let[e,t]=Y1(r);mb(r,e),yb(r,t)}};function Y1({schema:r}){let e={},t={};for(let n in r){if(n==="__proto__")continue;let i=Array.isArray(r[n])?e:t;i[n]=r[n]}return[e,t]}function mb(r,e=r.schema){let{gen:t,data:n,it:i}=r;if(Object.keys(e).length===0)return;let s=t.let("missing");for(let o in e){let a=e[o];if(a.length===0)continue;let c=(0,po.propertyInData)(t,n,o,i.opts.ownProperties);r.setParams({property:o,depsCount:a.length,deps:a.join(", ")}),i.allErrors?t.if(c,()=>{for(let l of a)(0,po.checkReportMissingProp)(r,l)}):(t.if((0,uf._)`${c} && (${(0,po.checkMissingProp)(r,a,s)})`),(0,po.reportMissingProp)(r,s),t.else())}}br.validatePropertyDeps=mb;function yb(r,e=r.schema){let{gen:t,data:n,keyword:i,it:s}=r,o=t.name("valid");for(let a in e)(0,G1.alwaysValidSchema)(s,e[a])||(t.if((0,po.propertyInData)(t,n,a,s.opts.ownProperties),()=>{let c=r.subschema({keyword:i,schemaProp:a},o);r.mergeValidEvaluated(c,o)},()=>t.var(o,!0)),r.ok(o))}br.validateSchemaDeps=yb;br.default=J1});var bb=A(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var gb=U(),X1=Q(),Q1={message:"property name must be valid",params:({params:r})=>(0,gb._)`{propertyName: ${r.propertyName}}`},Z1={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Q1,code(r){let{gen:e,schema:t,data:n,it:i}=r;if((0,X1.alwaysValidSchema)(i,t))return;let s=e.name("valid");e.forIn("key",n,o=>{r.setParams({propertyName:o}),r.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},s),e.if((0,gb.not)(s),()=>{r.error(!0),i.allErrors||e.break()})}),r.ok(s)}};ff.default=Z1});var hf=A(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});var oc=Nt(),Xt=U(),eC=Dt(),ac=Q(),tC={message:"must NOT have additional properties",params:({params:r})=>(0,Xt._)`{additionalProperty: ${r.additionalProperty}}`},rC={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:tC,code(r){let{gen:e,schema:t,parentSchema:n,data:i,errsCount:s,it:o}=r;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,ac.alwaysValidSchema)(o,t))return;let l=(0,oc.allSchemaProperties)(n.properties),u=(0,oc.allSchemaProperties)(n.patternProperties);d(),r.ok((0,Xt._)`${s} === ${eC.default.errors}`);function d(){e.forIn("key",i,y=>{!l.length&&!u.length?m(y):e.if(f(y),()=>m(y))})}function f(y){let g;if(l.length>8){let b=(0,ac.schemaRefOrVal)(o,n.properties,"properties");g=(0,oc.isOwnProperty)(e,b,y)}else l.length?g=(0,Xt.or)(...l.map(b=>(0,Xt._)`${y} === ${b}`)):g=Xt.nil;return u.length&&(g=(0,Xt.or)(g,...u.map(b=>(0,Xt._)`${(0,oc.usePattern)(r,b)}.test(${y})`))),(0,Xt.not)(g)}function p(y){e.code((0,Xt._)`delete ${i}[${y}]`)}function m(y){if(c.removeAdditional==="all"||c.removeAdditional&&t===!1){p(y);return}if(t===!1){r.setParams({additionalProperty:y}),r.error(),a||e.break();return}if(typeof t=="object"&&!(0,ac.alwaysValidSchema)(o,t)){let g=e.name("valid");c.removeAdditional==="failing"?(h(y,g,!1),e.if((0,Xt.not)(g),()=>{r.reset(),p(y)})):(h(y,g),a||e.if((0,Xt.not)(g),()=>e.break()))}}function h(y,g,b){let v={keyword:"additionalProperties",dataProp:y,dataPropType:ac.Type.Str};b===!1&&Object.assign(v,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(v,g)}}};pf.default=rC});var _b=A(yf=>{"use strict";Object.defineProperty(yf,"__esModule",{value:!0});var nC=Ni(),vb=Nt(),mf=Q(),wb=hf(),iC={keyword:"properties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,parentSchema:n,data:i,it:s}=r;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&wb.default.code(new nC.KeywordCxt(s,wb.default,"additionalProperties"));let o=(0,vb.allSchemaProperties)(t);for(let d of o)s.definedProperties.add(d);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=mf.mergeEvaluated.props(e,(0,mf.toHash)(o),s.props));let a=o.filter(d=>!(0,mf.alwaysValidSchema)(s,t[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)l(d)?u(d):(e.if((0,vb.propertyInData)(e,i,d,s.opts.ownProperties)),u(d),s.allErrors||e.else().var(c,!0),e.endIf()),r.it.definedProperties.add(d),r.ok(c);function l(d){return s.opts.useDefaults&&!s.compositeRule&&t[d].default!==void 0}function u(d){r.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};yf.default=iC});var Eb=A(gf=>{"use strict";Object.defineProperty(gf,"__esModule",{value:!0});var Sb=Nt(),cc=U(),$b=Q(),xb=Q(),sC={keyword:"patternProperties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,data:n,parentSchema:i,it:s}=r,{opts:o}=s,a=(0,Sb.allSchemaProperties)(t),c=a.filter(h=>(0,$b.alwaysValidSchema)(s,t[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=o.strictSchema&&!o.allowMatchingProperties&&i.properties,u=e.name("valid");s.props!==!0&&!(s.props instanceof cc.Name)&&(s.props=(0,xb.evaluatedPropsToName)(e,s.props));let{props:d}=s;f();function f(){for(let h of a)l&&p(h),s.allErrors?m(h):(e.var(u,!0),m(h),e.if(u))}function p(h){for(let y in l)new RegExp(h).test(y)&&(0,$b.checkStrictMode)(s,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,y=>{e.if((0,cc._)`${(0,Sb.usePattern)(r,h)}.test(${y})`,()=>{let g=c.includes(h);g||r.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:xb.Type.Str},u),s.opts.unevaluated&&d!==!0?e.assign((0,cc._)`${d}[${y}]`,!0):!g&&!s.allErrors&&e.if((0,cc.not)(u),()=>e.break())})})}}};gf.default=sC});var Ab=A(bf=>{"use strict";Object.defineProperty(bf,"__esModule",{value:!0});var oC=Q(),aC={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,oC.alwaysValidSchema)(n,t)){r.fail();return}let i=e.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),r.failResult(i,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};bf.default=aC});var kb=A(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0});var cC=Nt(),lC={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:cC.validateUnion,error:{message:"must match a schema in anyOf"}};vf.default=lC});var Pb=A(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0});var lc=U(),dC=Q(),uC={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,lc._)`{passingSchemas: ${r.passing}}`},fC={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:uC,code(r){let{gen:e,schema:t,parentSchema:n,it:i}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let s=t,o=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");r.setParams({passing:a}),e.block(l),r.result(o,()=>r.reset(),()=>r.error(!0));function l(){s.forEach((u,d)=>{let f;(0,dC.alwaysValidSchema)(i,u)?e.var(c,!0):f=r.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,lc._)`${c} && ${o}`).assign(o,!1).assign(a,(0,lc._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(a,d),f&&r.mergeEvaluated(f,lc.Name)})})}}};wf.default=fC});var Cb=A(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var pC=Q(),hC={keyword:"allOf",schemaType:"array",code(r){let{gen:e,schema:t,it:n}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");let i=e.name("valid");t.forEach((s,o)=>{if((0,pC.alwaysValidSchema)(n,s))return;let a=r.subschema({keyword:"allOf",schemaProp:o},i);r.ok(i),r.mergeEvaluated(a)})}};_f.default=hC});var Rb=A(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0});var dc=U(),Tb=Q(),mC={message:({params:r})=>(0,dc.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,dc._)`{failingKeyword: ${r.ifClause}}`},yC={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:mC,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,Tb.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=Mb(n,"then"),s=Mb(n,"else");if(!i&&!s)return;let o=e.let("valid",!0),a=e.name("_valid");if(c(),r.reset(),i&&s){let u=e.let("ifClause");r.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else i?e.if(a,l("then")):e.if((0,dc.not)(a),l("else"));r.pass(o,()=>r.error(!0));function c(){let u=r.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);r.mergeEvaluated(u)}function l(u,d){return()=>{let f=r.subschema({keyword:u},a);e.assign(o,a),r.mergeValidEvaluated(f,o),d?e.assign(d,(0,dc._)`${u}`):r.setParams({ifClause:u})}}}};function Mb(r,e){let t=r.schema[e];return t!==void 0&&!(0,Tb.alwaysValidSchema)(r,t)}Sf.default=yC});var Ib=A($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0});var gC=Q(),bC={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,gC.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};$f.default=bC});var Ef=A(xf=>{"use strict";Object.defineProperty(xf,"__esModule",{value:!0});var vC=of(),wC=ub(),_C=af(),SC=pb(),$C=hb(),xC=sc(),EC=bb(),AC=hf(),kC=_b(),PC=Eb(),CC=Ab(),MC=kb(),TC=Pb(),RC=Cb(),IC=Rb(),OC=Ib();function DC(r=!1){let e=[CC.default,MC.default,TC.default,RC.default,IC.default,OC.default,EC.default,AC.default,xC.default,kC.default,PC.default];return r?e.push(wC.default,SC.default):e.push(vC.default,_C.default),e.push($C.default),e}xf.default=DC});var kf=A(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});ho.dynamicAnchor=void 0;var Af=U(),NC=Dt(),Ob=Qs(),LC=Za(),FC={keyword:"$dynamicAnchor",schemaType:"string",code:r=>Db(r,r.schema)};function Db(r,e){let{gen:t,it:n}=r;n.schemaEnv.root.dynamicAnchors[e]=!0;let i=(0,Af._)`${NC.default.dynamicAnchors}${(0,Af.getProperty)(e)}`,s=n.errSchemaPath==="#"?n.validateName:jC(r);t.if((0,Af._)`!${i}`,()=>t.assign(i,s))}ho.dynamicAnchor=Db;function jC(r){let{schemaEnv:e,schema:t,self:n}=r.it,{root:i,baseId:s,localRefs:o,meta:a}=e.root,{schemaId:c}=n.opts,l=new Ob.SchemaEnv({schema:t,schemaId:c,root:i,baseId:s,localRefs:o,meta:a});return Ob.compileSchema.call(n,l),(0,LC.getValidate)(r,l)}ho.default=FC});var Pf=A(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.dynamicRef=void 0;var Nb=U(),qC=Dt(),Lb=Za(),BC={keyword:"$dynamicRef",schemaType:"string",code:r=>Fb(r,r.schema)};function Fb(r,e){let{gen:t,keyword:n,it:i}=r;if(e[0]!=="#")throw new Error(`"${n}" only supports hash fragment reference`);let s=e.slice(1);if(i.allErrors)o();else{let c=t.let("valid",!1);o(c),r.ok(c)}function o(c){if(i.schemaEnv.root.dynamicAnchors[s]){let l=t.let("_v",(0,Nb._)`${qC.default.dynamicAnchors}${(0,Nb.getProperty)(s)}`);t.if(l,a(l,c),a(i.validateName,c))}else a(i.validateName,c)()}function a(c,l){return l?()=>t.block(()=>{(0,Lb.callRef)(r,c),t.let(l,!0)}):()=>(0,Lb.callRef)(r,c)}}mo.dynamicRef=Fb;mo.default=BC});var jb=A(Cf=>{"use strict";Object.defineProperty(Cf,"__esModule",{value:!0});var UC=kf(),VC=Q(),HC={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,UC.dynamicAnchor)(r,""):(0,VC.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};Cf.default=HC});var qb=A(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var zC=Pf(),KC={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,zC.dynamicRef)(r,r.schema)};Mf.default=KC});var Bb=A(Tf=>{"use strict";Object.defineProperty(Tf,"__esModule",{value:!0});var WC=kf(),GC=Pf(),JC=jb(),YC=qb(),XC=[WC.default,GC.default,JC.default,YC.default];Tf.default=XC});var Vb=A(Rf=>{"use strict";Object.defineProperty(Rf,"__esModule",{value:!0});var Ub=sc(),QC={keyword:"dependentRequired",type:"object",schemaType:"object",error:Ub.error,code:r=>(0,Ub.validatePropertyDeps)(r)};Rf.default=QC});var Hb=A(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var ZC=sc(),eM={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,ZC.validateSchemaDeps)(r)};If.default=eM});var zb=A(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var tM=Q(),rM={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,tM.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};Of.default=rM});var Kb=A(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var nM=Vb(),iM=Hb(),sM=zb(),oM=[nM.default,iM.default,sM.default];Df.default=oM});var Gb=A(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var hn=U(),Wb=Q(),aM=Dt(),cM={message:"must NOT have unevaluated properties",params:({params:r})=>(0,hn._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},lM={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:cM,code(r){let{gen:e,schema:t,data:n,errsCount:i,it:s}=r;if(!i)throw new Error("ajv implementation error");let{allErrors:o,props:a}=s;a instanceof hn.Name?e.if((0,hn._)`${a} !== true`,()=>e.forIn("key",n,d=>e.if(l(a,d),()=>c(d)))):a!==!0&&e.forIn("key",n,d=>a===void 0?c(d):e.if(u(a,d),()=>c(d))),s.props=!0,r.ok((0,hn._)`${i} === ${aM.default.errors}`);function c(d){if(t===!1){r.setParams({unevaluatedProperty:d}),r.error(),o||e.break();return}if(!(0,Wb.alwaysValidSchema)(s,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:d,dataPropType:Wb.Type.Str},f),o||e.if((0,hn.not)(f),()=>e.break())}}function l(d,f){return(0,hn._)`!${d} || !${d}[${f}]`}function u(d,f){let p=[];for(let m in d)d[m]===!0&&p.push((0,hn._)`${f} !== ${m}`);return(0,hn.and)(...p)}}};Nf.default=lM});var Yb=A(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var oi=U(),Jb=Q(),dM={message:({params:{len:r}})=>(0,oi.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,oi._)`{limit: ${r}}`},uM={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:dM,code(r){let{gen:e,schema:t,data:n,it:i}=r,s=i.items||0;if(s===!0)return;let o=e.const("len",(0,oi._)`${n}.length`);if(t===!1)r.setParams({len:s}),r.fail((0,oi._)`${o} > ${s}`);else if(typeof t=="object"&&!(0,Jb.alwaysValidSchema)(i,t)){let c=e.var("valid",(0,oi._)`${o} <= ${s}`);e.if((0,oi.not)(c),()=>a(c,s)),r.ok(c)}i.items=!0;function a(c,l){e.forRange("i",l,o,u=>{r.subschema({keyword:"unevaluatedItems",dataProp:u,dataPropType:Jb.Type.Num},c),i.allErrors||e.if((0,oi.not)(c),()=>e.break())})}}};Lf.default=uM});var Xb=A(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var fM=Gb(),pM=Yb(),hM=[fM.default,pM.default];Ff.default=hM});var Qb=A(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var $e=U(),mM={message:({schemaCode:r})=>(0,$e.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,$e._)`{format: ${r}}`},yM={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:mM,code(r,e){let{gen:t,data:n,$data:i,schema:s,schemaCode:o,it:a}=r,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;i?f():p();function f(){let m=t.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=t.const("fDef",(0,$e._)`${m}[${o}]`),y=t.let("fType"),g=t.let("format");t.if((0,$e._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>t.assign(y,(0,$e._)`${h}.type || "string"`).assign(g,(0,$e._)`${h}.validate`),()=>t.assign(y,(0,$e._)`"string"`).assign(g,h)),r.fail$data((0,$e.or)(b(),v()));function b(){return c.strictSchema===!1?$e.nil:(0,$e._)`${o} && !${g}`}function v(){let S=u.$async?(0,$e._)`(${h}.async ? await ${g}(${n}) : ${g}(${n}))`:(0,$e._)`${g}(${n})`,_=(0,$e._)`(typeof ${g} == "function" ? ${S} : ${g}.test(${n}))`;return(0,$e._)`${g} && ${g} !== true && ${y} === ${e} && !${_}`}}function p(){let m=d.formats[s];if(!m){b();return}if(m===!0)return;let[h,y,g]=v(m);h===e&&r.pass(S());function b(){if(c.strictSchema===!1){d.logger.warn(_());return}throw new Error(_());function _(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function v(_){let E=_ instanceof RegExp?(0,$e.regexpCode)(_):c.code.formats?(0,$e._)`${c.code.formats}${(0,$e.getProperty)(s)}`:void 0,k=t.scopeValue("formats",{key:s,ref:_,code:E});return typeof _=="object"&&!(_ instanceof RegExp)?[_.type||"string",_.validate,(0,$e._)`${k}.validate`]:["string",_,k]}function S(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,$e._)`await ${g}(${n})`}return typeof y=="function"?(0,$e._)`${g}(${n})`:(0,$e._)`${g}.test(${n})`}}}};jf.default=yM});var Bf=A(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var gM=Qb(),bM=[gM.default];qf.default=bM});var Uf=A(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.contentVocabulary=Ui.metadataVocabulary=void 0;Ui.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Ui.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var ev=A(Vf=>{"use strict";Object.defineProperty(Vf,"__esModule",{value:!0});var vM=Bu(),wM=nf(),_M=Ef(),SM=Bb(),$M=Kb(),xM=Xb(),EM=Bf(),Zb=Uf(),AM=[SM.default,vM.default,wM.default,(0,_M.default)(!0),EM.default,Zb.metadataVocabulary,Zb.contentVocabulary,$M.default,xM.default];Vf.default=AM});var rv=A(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.DiscrError=void 0;var tv;(function(r){r.Tag="tag",r.Mapping="mapping"})(tv||(uc.DiscrError=tv={}))});var Kf=A(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var Vi=U(),Hf=rv(),nv=Qs(),kM=Li(),PM=Q(),CM={message:({params:{discrError:r,tagName:e}})=>r===Hf.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,Vi._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},MM={keyword:"discriminator",type:"object",schemaType:"object",error:CM,code(r){let{gen:e,data:t,schema:n,parentSchema:i,it:s}=r,{oneOf:o}=i;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,Vi._)`${t}${(0,Vi.getProperty)(a)}`);e.if((0,Vi._)`typeof ${l} == "string"`,()=>u(),()=>r.error(!1,{discrError:Hf.DiscrError.Tag,tag:l,tagName:a})),r.ok(c);function u(){let p=f();e.if(!1);for(let m in p)e.elseIf((0,Vi._)`${l} === ${m}`),e.assign(c,d(p[m]));e.else(),r.error(!1,{discrError:Hf.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function d(p){let m=e.name("valid"),h=r.subschema({keyword:"oneOf",schemaProp:p},m);return r.mergeEvaluated(h,Vi.Name),m}function f(){var p;let m={},h=g(i),y=!0;for(let S=0;S{TM.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var sv=A((Bq,RM)=>{RM.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var ov=A((Uq,IM)=>{IM.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var av=A((Vq,OM)=>{OM.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var cv=A((Hq,DM)=>{DM.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var lv=A((zq,NM)=>{NM.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var dv=A((Kq,LM)=>{LM.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var uv=A((Wq,FM)=>{FM.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var fv=A(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0});var jM=iv(),qM=sv(),BM=ov(),UM=av(),VM=cv(),HM=lv(),zM=dv(),KM=uv(),WM=["/properties"];function GM(r){return[jM,qM,BM,UM,VM,e(this,HM),zM,e(this,KM)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,n){return r?t.$dataMetaSchema(n,WM):n}}Wf.default=GM});var Yf=A((ye,Jf)=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.MissingRefError=ye.ValidationError=ye.CodeGen=ye.Name=ye.nil=ye.stringify=ye.str=ye._=ye.KeywordCxt=ye.Ajv2020=void 0;var JM=Fu(),YM=ev(),XM=Kf(),QM=fv(),Gf="https://json-schema.org/draft/2020-12/schema",Hi=class extends JM.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),YM.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(XM.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(QM.default.call(this,e),this.refs["http://json-schema.org/schema"]=Gf)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Gf)?Gf:void 0)}};ye.Ajv2020=Hi;Jf.exports=ye=Hi;Jf.exports.Ajv2020=Hi;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=Hi;var ZM=Ni();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return ZM.KeywordCxt}});var zi=U();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return zi._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return zi.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return zi.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return zi.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return zi.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return zi.CodeGen}});var eT=Xs();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return eT.default}});var tT=Li();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return tT.default}})});var wv=A(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.formatNames=wr.fastFormats=wr.fullFormats=void 0;function vr(r,e){return{validate:r,compare:e}}wr.fullFormats={date:vr(yv,ep),time:vr(Qf(!0),tp),"date-time":vr(pv(!0),bv),"iso-time":vr(Qf(),gv),"iso-date-time":vr(pv(),vv),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:aT,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:hT,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:cT,int32:{type:"number",validate:uT},int64:{type:"number",validate:fT},float:{type:"number",validate:mv},double:{type:"number",validate:mv},password:!0,binary:!0};wr.fastFormats={...wr.fullFormats,date:vr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ep),time:vr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,tp),"date-time":vr(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,bv),"iso-time":vr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,gv),"iso-date-time":vr(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,vv),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};wr.formatNames=Object.keys(wr.fullFormats);function rT(r){return r%4===0&&(r%100!==0||r%400===0)}var nT=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,iT=[0,31,28,31,30,31,30,31,31,30,31,30,31];function yv(r){let e=nT.exec(r);if(!e)return!1;let t=+e[1],n=+e[2],i=+e[3];return n>=1&&n<=12&&i>=1&&i<=(n===2&&rT(t)?29:iT[n])}function ep(r,e){if(r&&e)return r>e?1:r23||u>59||r&&!a)return!1;if(i<=23&&s<=59&&o<60)return!0;let d=s-u*c,f=i-l*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&o<61}}function tp(r,e){if(!(r&&e))return;let t=new Date("2020-01-01T"+r).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(t&&n)return t-n}function gv(r,e){if(!(r&&e))return;let t=Xf.exec(r),n=Xf.exec(e);if(t&&n)return r=t[1]+t[2]+t[3],e=n[1]+n[2]+n[3],r>e?1:r=lT}function fT(r){return Number.isInteger(r)}function mv(){return!0}var pT=/[^\\]\\Z/;function hT(r){if(pT.test(r))return!1;try{return new RegExp(r),!0}catch{return!1}}});var Sv=A(rp=>{"use strict";Object.defineProperty(rp,"__esModule",{value:!0});var mT=Bu(),yT=nf(),gT=Ef(),bT=Bf(),_v=Uf(),vT=[mT.default,yT.default,(0,gT.default)(),bT.default,_v.metadataVocabulary,_v.contentVocabulary];rp.default=vT});var $v=A((Xq,wT)=>{wT.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var Ev=A((ge,np)=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.MissingRefError=ge.ValidationError=ge.CodeGen=ge.Name=ge.nil=ge.stringify=ge.str=ge._=ge.KeywordCxt=ge.Ajv=void 0;var _T=Fu(),ST=Sv(),$T=Kf(),xv=$v(),xT=["/properties"],fc="http://json-schema.org/draft-07/schema",Ki=class extends _T.default{_addVocabularies(){super._addVocabularies(),ST.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword($T.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(xv,xT):xv;this.addMetaSchema(e,fc,!1),this.refs["http://json-schema.org/schema"]=fc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(fc)?fc:void 0)}};ge.Ajv=Ki;np.exports=ge=Ki;np.exports.Ajv=Ki;Object.defineProperty(ge,"__esModule",{value:!0});ge.default=Ki;var ET=Ni();Object.defineProperty(ge,"KeywordCxt",{enumerable:!0,get:function(){return ET.KeywordCxt}});var Wi=U();Object.defineProperty(ge,"_",{enumerable:!0,get:function(){return Wi._}});Object.defineProperty(ge,"str",{enumerable:!0,get:function(){return Wi.str}});Object.defineProperty(ge,"stringify",{enumerable:!0,get:function(){return Wi.stringify}});Object.defineProperty(ge,"nil",{enumerable:!0,get:function(){return Wi.nil}});Object.defineProperty(ge,"Name",{enumerable:!0,get:function(){return Wi.Name}});Object.defineProperty(ge,"CodeGen",{enumerable:!0,get:function(){return Wi.CodeGen}});var AT=Xs();Object.defineProperty(ge,"ValidationError",{enumerable:!0,get:function(){return AT.default}});var kT=Li();Object.defineProperty(ge,"MissingRefError",{enumerable:!0,get:function(){return kT.default}})});var Av=A(Gi=>{"use strict";Object.defineProperty(Gi,"__esModule",{value:!0});Gi.formatLimitDefinition=void 0;var PT=Ev(),Qt=U(),mn=Qt.operators,pc={formatMaximum:{okStr:"<=",ok:mn.LTE,fail:mn.GT},formatMinimum:{okStr:">=",ok:mn.GTE,fail:mn.LT},formatExclusiveMaximum:{okStr:"<",ok:mn.LT,fail:mn.GTE},formatExclusiveMinimum:{okStr:">",ok:mn.GT,fail:mn.LTE}},CT={message:({keyword:r,schemaCode:e})=>(0,Qt.str)`should be ${pc[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Qt._)`{comparison: ${pc[r].okStr}, limit: ${e}}`};Gi.formatLimitDefinition={keyword:Object.keys(pc),type:"string",schemaType:"string",$data:!0,error:CT,code(r){let{gen:e,data:t,schemaCode:n,keyword:i,it:s}=r,{opts:o,self:a}=s;if(!o.validateFormats)return;let c=new PT.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let f=e.scopeValue("formats",{ref:a.formats,code:o.code.formats}),p=e.const("fmt",(0,Qt._)`${f}[${c.schemaCode}]`);r.fail$data((0,Qt.or)((0,Qt._)`typeof ${p} != "object"`,(0,Qt._)`${p} instanceof RegExp`,(0,Qt._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let f=c.schema,p=a.formats[f];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${i}": format "${f}" does not define "compare" function`);let m=e.scopeValue("formats",{key:f,ref:p,code:o.code.formats?(0,Qt._)`${o.code.formats}${(0,Qt.getProperty)(f)}`:void 0});r.fail$data(d(m))}function d(f){return(0,Qt._)`${f}.compare(${t}, ${n}) ${pc[i].fail} 0`}},dependencies:["format"]};var MT=r=>(r.addKeyword(Gi.formatLimitDefinition),r);Gi.default=MT});var op=A((yo,Cv)=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});var Ji=wv(),TT=Av(),ip=U(),kv=new ip.Name("fullFormats"),RT=new ip.Name("fastFormats"),sp=(r,e={keywords:!0})=>{if(Array.isArray(e))return Pv(r,e,Ji.fullFormats,kv),r;let[t,n]=e.mode==="fast"?[Ji.fastFormats,RT]:[Ji.fullFormats,kv],i=e.formats||Ji.formatNames;return Pv(r,i,t,n),e.keywords&&(0,TT.default)(r),r};sp.get=(r,e="full")=>{let n=(e==="fast"?Ji.fastFormats:Ji.fullFormats)[r];if(!n)throw new Error(`Unknown format "${r}"`);return n};function Pv(r,e,t,n){var i,s;(i=(s=r.opts.code).formats)!==null&&i!==void 0||(s.formats=(0,ip._)`require("ajv-formats/dist/formats").${n}`);for(let o of e)r.addFormat(o,t[o])}Cv.exports=yo=sp;Object.defineProperty(yo,"__esModule",{value:!0});yo.default=sp});var go=A((Zq,Ov)=>{"use strict";var Mv="[^\\\\/]",IT="(?=.)",Tv="[^/]",ap="(?:\\/|$)",Rv="(?:^|\\/)",cp=`\\.{1,2}${ap}`,OT="(?!\\.)",DT=`(?!${Rv}${cp})`,NT=`(?!\\.{0,1}${ap})`,LT=`(?!${cp})`,FT="[^.\\/]",jT=`${Tv}*?`,qT="/",Iv={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:IT,QMARK:Tv,END_ANCHOR:ap,DOTS_SLASH:cp,NO_DOT:OT,NO_DOTS:DT,NO_DOT_SLASH:NT,NO_DOTS_SLASH:LT,QMARK_NO_DOT:FT,STAR:jT,START_ANCHOR:Rv,SEP:qT},BT={...Iv,SLASH_LITERAL:"[\\\\/]",QMARK:Mv,STAR:`${Mv}*?`,DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},UT={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};Ov.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:UT,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(r){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${r.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(r){return r===!0?BT:Iv}}});var bo=A(ht=>{"use strict";var{REGEX_BACKSLASH:VT,REGEX_REMOVE_BACKSLASH:HT,REGEX_SPECIAL_CHARS:zT,REGEX_SPECIAL_CHARS_GLOBAL:KT}=go();ht.isObject=r=>r!==null&&typeof r=="object"&&!Array.isArray(r);ht.hasRegexChars=r=>zT.test(r);ht.isRegexChar=r=>r.length===1&&ht.hasRegexChars(r);ht.escapeRegex=r=>r.replace(KT,"\\$1");ht.toPosixSlashes=r=>r.replace(VT,"/");ht.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let r=navigator.platform.toLowerCase();return r==="win32"||r==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":!1};ht.removeBackslashes=r=>r.replace(HT,e=>e==="\\"?"":e);ht.escapeLast=(r,e,t)=>{let n=r.lastIndexOf(e,t);return n===-1?r:r[n-1]==="\\"?ht.escapeLast(r,e,n-1):`${r.slice(0,n)}\\${r.slice(n)}`};ht.removePrefix=(r,e={})=>{let t=r;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};ht.wrapOutput=(r,e={},t={})=>{let n=t.contains?"":"^",i=t.contains?"":"$",s=`${n}(?:${r})${i}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s};ht.basename=(r,{windows:e}={})=>{let t=r.split(e?/[\\/]/:"/"),n=t[t.length-1];return n===""?t[t.length-2]:n}});var Uv=A((tB,Bv)=>{"use strict";var Dv=bo(),{CHAR_ASTERISK:lp,CHAR_AT:WT,CHAR_BACKWARD_SLASH:Yi,CHAR_COMMA:GT,CHAR_DOT:dp,CHAR_EXCLAMATION_MARK:up,CHAR_FORWARD_SLASH:qv,CHAR_LEFT_CURLY_BRACE:fp,CHAR_LEFT_PARENTHESES:hc,CHAR_LEFT_SQUARE_BRACKET:JT,CHAR_PLUS:YT,CHAR_QUESTION_MARK:Nv,CHAR_RIGHT_CURLY_BRACE:XT,CHAR_RIGHT_PARENTHESES:Lv,CHAR_RIGHT_SQUARE_BRACKET:QT}=go(),Fv=r=>r===qv||r===Yi,jv=r=>{r.isPrefix!==!0&&(r.depth=r.isGlobstar?1/0:1)},ZT=(r,e)=>{let t=e||{},n=r.length-1,i=t.parts===!0||t.tokens===!0||t.scanToEnd===!0,s=[],o=[],a=[],c=r,l=-1,u=0,d=0,f=!1,p=!1,m=!1,h=!1,y=!1,g=!1,b=!1,v=!1,S=!1,_=!1,E=0,k,$,M={value:"",depth:0,isGlob:!1},x=()=>l>=n,q=()=>c.charCodeAt(l+1),T=()=>(k=$,c.charCodeAt(++l));for(;l0&&(P=c.slice(0,u),c=c.slice(u),d-=u),V&&m===!0&&d>0?(V=c.slice(0,d),C=c.slice(d)):m===!0?(V="",C=c):V=c,V&&V!==""&&V!=="/"&&V!==c&&Fv(V.charCodeAt(V.length-1))&&(V=V.slice(0,-1)),t.unescape===!0&&(C&&(C=Dv.removeBackslashes(C)),V&&b===!0&&(V=Dv.removeBackslashes(V)));let Be={prefix:P,input:r,start:u,base:V,glob:C,isBrace:f,isBracket:p,isGlob:m,isExtglob:h,isGlobstar:y,negated:v,negatedExtglob:S};if(t.tokens===!0&&(Be.maxDepth=0,Fv($)||o.push(M),Be.tokens=o),t.parts===!0||t.tokens===!0){let ce;for(let ke=0;ke=u&&(a.push(Hn),ce=Ns)}let ct=ce!==void 0?ce+1:u,xt=r.slice(ct);a.push(xt),t.tokens&&ce&&ce+1{"use strict";var vo=go(),Et=bo(),{MAX_LENGTH:mc,POSIX_REGEX_SOURCE:eR,REGEX_NON_SPECIAL_CHARS:tR,REGEX_SPECIAL_CHARS_BACKREF:rR,REPLACEMENTS:Vv}=vo,nR=(r,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...r,e);r.sort();let t=`[${r.join("-")}]`;try{new RegExp(t)}catch{return r.map(i=>Et.escapeRegex(i)).join("..")}return t},Xi=(r,e)=>`Missing ${r}: "${e}" - use "\\\\${e}" to match literal characters`,Hv=r=>{let e=[],t=0,n=0,i=0,s="",o=!1;for(let a of r){if(o===!0){s+=a,o=!1;continue}if(a==="\\"){s+=a,o=!0;continue}if(a==='"'){i=i===1?0:1,s+=a;continue}if(i===0){if(a==="[")t++;else if(a==="]"&&t>0)t--;else if(t===0){if(a==="(")n++;else if(a===")"&&n>0)n--;else if(a==="|"&&n===0){e.push(s),s="";continue}}}s+=a}return e.push(s),e},iR=r=>{let e=!1;for(let t of r){if(e===!0){e=!1;continue}if(t==="\\"){e=!0;continue}if(/[?*+@!()[\]{}]/.test(t))return!1}return!0},hp=r=>{let e=r.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(iR(e))return e.replace(/\\(.)/g,"$1")},sR=r=>{let e=r.map(hp).filter(Boolean);for(let t=0;t{if(r[0]!=="+"&&r[0]!=="*"||r[1]!=="(")return;let t=0,n=0,i=0,s=!1;for(let o=1;o0){t--;continue}if(!(t>0)){if(a==="("){n++;continue}if(a===")"&&(n--,n===0))return e===!0&&o!==r.length-1?void 0:{type:r[0],body:r.slice(2,o),end:o}}}}},oR=r=>`${r.length===1?Et.escapeRegex(r[0]):`[${r.map(t=>Et.escapeRegex(t)).join("")}]`}*`,aR=r=>{let e=0,t=[];for(;eo.trim());if(i.length!==1)return;let s=hp(i[0]);if(!s||s.length!==1)return;t.push(s),e+=n.end+1}if(!(t.length<1))return t},cR=r=>{let e=0,t=r.trim(),n=pp(t);for(;n;)e++,t=n.body.trim(),n=pp(t);return e},lR=(r,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:vo.DEFAULT_MAX_EXTGLOB_RECURSION,n=Hv(r).map(a=>a.trim());if(n.length>1&&(n.some(a=>a==="")||n.some(a=>/^[*?]+$/.test(a))||sR(n)))return{risky:!0};let i=[],s=!1,o=!0;for(let a of n){let c=aR(a);if(c){s=!0,i.push(...c);continue}let l=hp(a);if(l&&l.length===1){i.push(l);continue}if(o=!1,cR(a)>t)return{risky:!0}}return s?o?{risky:!0,safeOutput:oR([...new Set(i)])}:{risky:!0}:{risky:!1}},mp=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a string");r=Vv[r]||r;let t={...e},n=typeof t.maxLength=="number"?Math.min(mc,t.maxLength):mc,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);let s={type:"bos",value:"",output:t.prepend||""},o=[s],a=t.capture?"":"?:",c=vo.globChars(t.windows),l=vo.extglobChars(c),{DOT_LITERAL:u,PLUS_LITERAL:d,SLASH_LITERAL:f,ONE_CHAR:p,DOTS_SLASH:m,NO_DOT:h,NO_DOT_SLASH:y,NO_DOTS_SLASH:g,QMARK:b,QMARK_NO_DOT:v,STAR:S,START_ANCHOR:_}=c,E=I=>`(${a}(?:(?!${_}${I.dot?m:u}).)*?)`,k=t.dot?"":h,$=t.dot?b:v,M=t.bash===!0?E(t):S;t.capture&&(M=`(${M})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let x={input:r,index:-1,start:0,dot:t.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:o};r=Et.removePrefix(r,x),i=r.length;let q=[],T=[],V=[],P=s,C,Be=()=>x.index===i-1,ce=x.peek=(I=1)=>r[x.index+I],ct=x.advance=()=>r[++x.index]||"",xt=()=>r.slice(x.index+1),ke=(I="",ve=0)=>{x.consumed+=I,x.index+=ve},Ai=I=>{x.output+=I.output!=null?I.output:I.value,ke(I.value)},Ns=()=>{let I=1;for(;ce()==="!"&&(ce(2)!=="("||ce(3)==="?");)ct(),x.start++,I++;return I%2===0?!1:(x.negated=!0,x.start++,!0)},Hn=I=>{x[I]++,V.push(I)},on=I=>{x[I]--,V.pop()},Z=I=>{if(P.type==="globstar"){let ve=x.braces>0&&(I.type==="comma"||I.type==="brace"),R=I.extglob===!0||q.length&&(I.type==="pipe"||I.type==="paren");I.type!=="slash"&&I.type!=="paren"&&!ve&&!R&&(x.output=x.output.slice(0,-P.output.length),P.type="star",P.value="*",P.output=M,x.output+=P.output)}if(q.length&&I.type!=="paren"&&(q[q.length-1].inner+=I.value),(I.value||I.output)&&Ai(I),P&&P.type==="text"&&I.type==="text"){P.output=(P.output||P.value)+I.value,P.value+=I.value;return}I.prev=P,o.push(I),P=I},ka=(I,ve)=>{let R={...l[ve],conditions:1,inner:""};R.prev=P,R.parens=x.parens,R.output=x.output,R.startIndex=x.index,R.tokensIndex=o.length;let ee=(t.capture?"(":"")+R.open;Hn("parens"),Z({type:I,value:ve,output:x.output?"":p}),Z({type:"paren",extglob:!0,value:ct(),output:ee}),q.push(R)},Qx=I=>{let ve=r.slice(I.startIndex,x.index+1),R=r.slice(I.startIndex+2,x.index),ee=lR(R,t);if((I.type==="plus"||I.type==="star")&&ee.risky){let ue=ee.safeOutput?(I.output?"":p)+(t.capture?`(${ee.safeOutput})`:ee.safeOutput):void 0,hr=o[I.tokensIndex];hr.type="text",hr.value=ve,hr.output=ue||Et.escapeRegex(ve);for(let zn=I.tokensIndex+1;zn1&&I.inner.includes("/")&&(ue=E(t)),(ue!==M||Be()||/^\)+$/.test(xt()))&&(he=I.close=`)$))${ue}`),I.inner.includes("*")&&(Pe=xt())&&/^\.[^\\/.]+$/.test(Pe)){let hr=mp(Pe,{...e,fastpaths:!1}).output;he=I.close=`)${hr})${ue})`}I.prev.type==="bos"&&(x.negatedExtglob=!0)}Z({type:"paren",extglob:!0,value:C,output:he}),on("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(r)){let I=!1,ve=r.replace(rR,(R,ee,he,Pe,ue,hr)=>Pe==="\\"?(I=!0,R):Pe==="?"?ee?ee+Pe+(ue?b.repeat(ue.length):""):hr===0?$+(ue?b.repeat(ue.length):""):b.repeat(he.length):Pe==="."?u.repeat(he.length):Pe==="*"?ee?ee+Pe+(ue?M:""):M:ee?R:`\\${R}`);return I===!0&&(t.unescape===!0?ve=ve.replace(/\\/g,""):ve=ve.replace(/\\+/g,R=>R.length%2===0?"\\\\":R?"\\":"")),ve===r&&t.contains===!0?(x.output=r,x):(x.output=Et.wrapOutput(ve,x,e),x)}for(;!Be();){if(C=ct(),C==="\0")continue;if(C==="\\"){let R=ce();if(R==="/"&&t.bash!==!0||R==="."||R===";")continue;if(!R){C+="\\",Z({type:"text",value:C});continue}let ee=/^\\+/.exec(xt()),he=0;if(ee&&ee[0].length>2&&(he=ee[0].length,x.index+=he,he%2!==0&&(C+="\\")),t.unescape===!0?C=ct():C+=ct(),x.brackets===0){Z({type:"text",value:C});continue}}if(x.brackets>0&&(C!=="]"||P.value==="["||P.value==="[^")){if(t.posix!==!1&&C===":"){let R=P.value.slice(1);if(R.includes("[")&&(P.posix=!0,R.includes(":"))){let ee=P.value.lastIndexOf("["),he=P.value.slice(0,ee),Pe=P.value.slice(ee+2),ue=eR[Pe];if(ue){P.value=he+ue,x.backtrack=!0,ct(),!s.output&&o.indexOf(P)===1&&(s.output=p);continue}}}(C==="["&&ce()!==":"||C==="-"&&ce()==="]")&&(C=`\\${C}`),C==="]"&&(P.value==="["||P.value==="[^")&&(C=`\\${C}`),t.posix===!0&&C==="!"&&P.value==="["&&(C="^"),P.value+=C,Ai({value:C});continue}if(x.quotes===1&&C!=='"'){C=Et.escapeRegex(C),P.value+=C,Ai({value:C});continue}if(C==='"'){x.quotes=x.quotes===1?0:1,t.keepQuotes===!0&&Z({type:"text",value:C});continue}if(C==="("){Hn("parens"),Z({type:"paren",value:C});continue}if(C===")"){if(x.parens===0&&t.strictBrackets===!0)throw new SyntaxError(Xi("opening","("));let R=q[q.length-1];if(R&&x.parens===R.parens+1){Qx(q.pop());continue}Z({type:"paren",value:C,output:x.parens?")":"\\)"}),on("parens");continue}if(C==="["){if(t.nobracket===!0||!xt().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(Xi("closing","]"));C=`\\${C}`}else Hn("brackets");Z({type:"bracket",value:C});continue}if(C==="]"){if(t.nobracket===!0||P&&P.type==="bracket"&&P.value.length===1){Z({type:"text",value:C,output:`\\${C}`});continue}if(x.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(Xi("opening","["));Z({type:"text",value:C,output:`\\${C}`});continue}on("brackets");let R=P.value.slice(1);if(P.posix!==!0&&R[0]==="^"&&!R.includes("/")&&(C=`/${C}`),P.value+=C,Ai({value:C}),t.literalBrackets===!1||Et.hasRegexChars(R))continue;let ee=Et.escapeRegex(P.value);if(x.output=x.output.slice(0,-P.value.length),t.literalBrackets===!0){x.output+=ee,P.value=ee;continue}P.value=`(${a}${ee}|${P.value})`,x.output+=P.value;continue}if(C==="{"&&t.nobrace!==!0){Hn("braces");let R={type:"brace",value:C,output:"(",outputIndex:x.output.length,tokensIndex:x.tokens.length};T.push(R),Z(R);continue}if(C==="}"){let R=T[T.length-1];if(t.nobrace===!0||!R){Z({type:"text",value:C,output:C});continue}let ee=")";if(R.dots===!0){let he=o.slice(),Pe=[];for(let ue=he.length-1;ue>=0&&(o.pop(),he[ue].type!=="brace");ue--)he[ue].type!=="dots"&&Pe.unshift(he[ue].value);ee=nR(Pe,t),x.backtrack=!0}if(R.comma!==!0&&R.dots!==!0){let he=x.output.slice(0,R.outputIndex),Pe=x.tokens.slice(R.tokensIndex);R.value=R.output="\\{",C=ee="\\}",x.output=he;for(let ue of Pe)x.output+=ue.output||ue.value}Z({type:"brace",value:C,output:ee}),on("braces"),T.pop();continue}if(C==="|"){q.length>0&&q[q.length-1].conditions++,Z({type:"text",value:C});continue}if(C===","){let R=C,ee=T[T.length-1];ee&&V[V.length-1]==="braces"&&(ee.comma=!0,R="|"),Z({type:"comma",value:C,output:R});continue}if(C==="/"){if(P.type==="dot"&&x.index===x.start+1){x.start=x.index+1,x.consumed="",x.output="",o.pop(),P=s;continue}Z({type:"slash",value:C,output:f});continue}if(C==="."){if(x.braces>0&&P.type==="dot"){P.value==="."&&(P.output=u);let R=T[T.length-1];P.type="dots",P.output+=C,P.value+=C,R.dots=!0;continue}if(x.braces+x.parens===0&&P.type!=="bos"&&P.type!=="slash"){Z({type:"text",value:C,output:u});continue}Z({type:"dot",value:C,output:u});continue}if(C==="?"){if(!(P&&P.value==="(")&&t.noextglob!==!0&&ce()==="("&&ce(2)!=="?"){ka("qmark",C);continue}if(P&&P.type==="paren"){let ee=ce(),he=C;(P.value==="("&&!/[!=<:]/.test(ee)||ee==="<"&&!/<([!=]|\w+>)/.test(xt()))&&(he=`\\${C}`),Z({type:"text",value:C,output:he});continue}if(t.dot!==!0&&(P.type==="slash"||P.type==="bos")){Z({type:"qmark",value:C,output:v});continue}Z({type:"qmark",value:C,output:b});continue}if(C==="!"){if(t.noextglob!==!0&&ce()==="("&&(ce(2)!=="?"||!/[!=<:]/.test(ce(3)))){ka("negate",C);continue}if(t.nonegate!==!0&&x.index===0){Ns();continue}}if(C==="+"){if(t.noextglob!==!0&&ce()==="("&&ce(2)!=="?"){ka("plus",C);continue}if(P&&P.value==="("||t.regex===!1){Z({type:"plus",value:C,output:d});continue}if(P&&(P.type==="bracket"||P.type==="paren"||P.type==="brace")||x.parens>0){Z({type:"plus",value:C});continue}Z({type:"plus",value:d});continue}if(C==="@"){if(t.noextglob!==!0&&ce()==="("&&ce(2)!=="?"){Z({type:"at",extglob:!0,value:C,output:""});continue}Z({type:"text",value:C});continue}if(C!=="*"){(C==="$"||C==="^")&&(C=`\\${C}`);let R=tR.exec(xt());R&&(C+=R[0],x.index+=R[0].length),Z({type:"text",value:C});continue}if(P&&(P.type==="globstar"||P.star===!0)){P.type="star",P.star=!0,P.value+=C,P.output=M,x.backtrack=!0,x.globstar=!0,ke(C);continue}let I=xt();if(t.noextglob!==!0&&/^\([^?]/.test(I)){ka("star",C);continue}if(P.type==="star"){if(t.noglobstar===!0){ke(C);continue}let R=P.prev,ee=R.prev,he=R.type==="slash"||R.type==="bos",Pe=ee&&(ee.type==="star"||ee.type==="globstar");if(t.bash===!0&&(!he||I[0]&&I[0]!=="/")){Z({type:"star",value:C,output:""});continue}let ue=x.braces>0&&(R.type==="comma"||R.type==="brace"),hr=q.length&&(R.type==="pipe"||R.type==="paren");if(!he&&R.type!=="paren"&&!ue&&!hr){Z({type:"star",value:C,output:""});continue}for(;I.slice(0,3)==="/**";){let ki=r[x.index+4];if(ki&&ki!=="/")break;I=I.slice(3),ke("/**",3)}let zn=Be()||x.parens>0&&I===")".repeat(x.parens)&&!q.some(ki=>ki.type==="negate");if(R.type==="bos"&&Be()){P.type="globstar",P.value+=C,P.output=E(t),x.output=P.output,x.globstar=!0,ke(C);continue}if(R.type==="slash"&&R.prev.type!=="bos"&&!Pe&&zn){x.output=x.output.slice(0,-(R.output+P.output).length),R.output=`(?:${R.output}`,P.type="globstar",P.output=E(t)+(t.strictSlashes?")":"|$)"),P.value+=C,x.globstar=!0,x.output+=R.output+P.output,ke(C);continue}if(R.type==="slash"&&R.prev.type!=="bos"&&I[0]==="/"){let ki=I[1]!==void 0?"|$":"";x.output=x.output.slice(0,-(R.output+P.output).length),R.output=`(?:${R.output}`,P.type="globstar",P.output=`${E(t)}${f}|${f}${ki})`,P.value+=C,x.output+=R.output+P.output,x.globstar=!0,ke(C+ct()),Z({type:"slash",value:"/",output:""});continue}if(R.type==="bos"&&I[0]==="/"){P.type="globstar",P.value+=C,P.output=`(?:^|${f}|${E(t)}${f})`,x.output=P.output,x.globstar=!0,ke(C+ct()),Z({type:"slash",value:"/",output:""});continue}x.output=x.output.slice(0,-P.output.length),P.type="globstar",P.output=E(t),P.value+=C,x.output+=P.output,x.globstar=!0,ke(C);continue}let ve={type:"star",value:C,output:M};if(t.bash===!0){ve.output=".*?",(P.type==="bos"||P.type==="slash")&&(ve.output=k+ve.output),Z(ve);continue}if(P&&(P.type==="bracket"||P.type==="paren")&&t.regex===!0){ve.output=C,Z(ve);continue}(x.index===x.start||P.type==="slash"||P.type==="dot")&&(P.type==="dot"?(x.output+=y,P.output+=y):t.dot===!0?(x.output+=g,P.output+=g):(x.output+=k,P.output+=k),ce()!=="*"&&(x.output+=p,P.output+=p)),Z(ve)}for(;x.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(Xi("closing","]"));x.output=Et.escapeLast(x.output,"["),on("brackets")}for(;x.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(Xi("closing",")"));x.output=Et.escapeLast(x.output,"("),on("parens")}for(;x.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(Xi("closing","}"));x.output=Et.escapeLast(x.output,"{"),on("braces")}if(t.strictSlashes!==!0&&(P.type==="star"||P.type==="bracket")&&Z({type:"maybe_slash",value:"",output:`${f}?`}),x.backtrack===!0){x.output="";for(let I of x.tokens)x.output+=I.output!=null?I.output:I.value,I.suffix&&(x.output+=I.suffix)}return x};mp.fastpaths=(r,e)=>{let t={...e},n=typeof t.maxLength=="number"?Math.min(mc,t.maxLength):mc,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);r=Vv[r]||r;let{DOT_LITERAL:s,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:c,NO_DOT:l,NO_DOTS:u,NO_DOTS_SLASH:d,STAR:f,START_ANCHOR:p}=vo.globChars(t.windows),m=t.dot?u:l,h=t.dot?d:l,y=t.capture?"":"?:",g={negated:!1,prefix:""},b=t.bash===!0?".*?":f;t.capture&&(b=`(${b})`);let v=k=>k.noglobstar===!0?b:`(${y}(?:(?!${p}${k.dot?c:s}).)*?)`,S=k=>{switch(k){case"*":return`${m}${a}${b}`;case".*":return`${s}${a}${b}`;case"*.*":return`${m}${b}${s}${a}${b}`;case"*/*":return`${m}${b}${o}${a}${h}${b}`;case"**":return m+v(t);case"**/*":return`(?:${m}${v(t)}${o})?${h}${a}${b}`;case"**/*.*":return`(?:${m}${v(t)}${o})?${h}${b}${s}${a}${b}`;case"**/.*":return`(?:${m}${v(t)}${o})?${s}${a}${b}`;default:{let $=/^(.*?)\.(\w+)$/.exec(k);if(!$)return;let M=S($[1]);return M?M+s+$[2]:void 0}}},_=Et.removePrefix(r,g),E=S(_);return E&&t.strictSlashes!==!0&&(E+=`${o}?`),E};zv.exports=mp});var Jv=A((nB,Gv)=>{"use strict";var dR=Uv(),yp=Kv(),Wv=bo(),uR=go(),fR=r=>r&&typeof r=="object"&&!Array.isArray(r),xe=(r,e,t=!1)=>{if(Array.isArray(r)){let u=r.map(f=>xe(f,e,t));return f=>{for(let p of u){let m=p(f);if(m)return m}return!1}}let n=fR(r)&&r.tokens&&r.input;if(r===""||typeof r!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let i=e||{},s=i.windows,o=n?xe.compileRe(r,e):xe.makeRe(r,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(i.ignore){let u={...e,ignore:null,onMatch:null,onResult:null};c=xe(i.ignore,u,t)}let l=(u,d=!1)=>{let{isMatch:f,match:p,output:m}=xe.test(u,o,e,{glob:r,posix:s}),h={glob:r,state:a,regex:o,posix:s,input:u,output:m,match:p,isMatch:f};return typeof i.onResult=="function"&&i.onResult(h),f===!1?(h.isMatch=!1,d?h:!1):c(u)?(typeof i.onIgnore=="function"&&i.onIgnore(h),h.isMatch=!1,d?h:!1):(typeof i.onMatch=="function"&&i.onMatch(h),d?h:!0)};return t&&(l.state=a),l};xe.test=(r,e,t,{glob:n,posix:i}={})=>{if(typeof r!="string")throw new TypeError("Expected input to be a string");if(r==="")return{isMatch:!1,output:""};let s=t||{},o=s.format||(i?Wv.toPosixSlashes:null),a=r===n,c=a&&o?o(r):r;return a===!1&&(c=o?o(r):r,a=c===n),(a===!1||s.capture===!0)&&(s.matchBase===!0||s.basename===!0?a=xe.matchBase(r,e,t,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};xe.matchBase=(r,e,t,n=t&&t.windows)=>(e instanceof RegExp?e:xe.makeRe(e,t)).test(Wv.basename(r,{windows:n}));xe.isMatch=(r,e,t)=>xe(e,t)(r);xe.parse=(r,e)=>Array.isArray(r)?r.map(t=>xe.parse(t,e)):yp(r,{...e,fastpaths:!1});xe.scan=(r,e)=>dR(r,e);xe.compileRe=(r,e,t=!1,n=!1)=>{if(t===!0)return r.output;let i=e||{},s=i.contains?"":"^",o=i.contains?"":"$",a=`${s}(?:${r.output})${o}`;r&&r.negated===!0&&(a=`^(?!${a}).*$`);let c=xe.toRegex(a,e);return n===!0&&(c.state=r),c};xe.makeRe=(r,e={},t=!1,n=!1)=>{if(!r||typeof r!="string")throw new TypeError("Expected a non-empty string");let i={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(r[0]==="."||r[0]==="*")&&(i.output=yp.fastpaths(r,e)),i.output||(i=yp(r,e)),xe.compileRe(i,e,t,n)};xe.toRegex=(r,e)=>{try{let t=e||{};return new RegExp(r,t.flags||(t.nocase?"i":""))}catch(t){if(e&&e.debug===!0)throw t;return/$^/}};xe.constants=uR;Gv.exports=xe});var gp=A((iB,Qv)=>{"use strict";var Yv=Jv(),pR=bo();function Xv(r,e,t=!1){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:pR.isWindows()}),Yv(r,e,t)}Object.assign(Xv,Yv);Qv.exports=Xv});function bp(r,e){return yc(e.split("/"),r.split("/"))}function yc(r,e){if(e.length===0)return r.length===0;let[t,...n]=e;return t==="**"?yc(r,n)||r.length>0&&yc(r.slice(1),e):r.length===0?!1:Qi([...r[0]],[...t])&&yc(r.slice(1),n)}function Qi(r,e){if(e.length===0)return r.length===0;let[t,...n]=e;if(t==="*")return Qi(r,n)||r.length>0&&Qi(r.slice(1),e);if(t==="?")return r.length>0&&Qi(r.slice(1),n);if(t==="["){let i=hR(n);if(i)return r.length>0&&i.matches(r[0])&&Qi(r.slice(1),i.after)}return r[0]===t&&Qi(r.slice(1),n)}function hR(r){let e=r[0]==="!",t=[],n=e?1:0,i=!0;for(;n{let c=wo(a);return t.some(([l,u])=>l<=c&&c<=u)!==e},after:r.slice(n+1)};n+2{});var mw={};ay(mw,{MdbasePathError:()=>So,applyReadDefaults:()=>qR,buildInitialFrontmatter:()=>Rp,buildTypeTemplate:()=>Tp,buildUniqueNotePath:()=>Op,coerceFieldInput:()=>Sc,createNoteFromType:()=>HR,createTypeDefinition:()=>BR,ensureCollectionInitialized:()=>$o,fieldsFromV03Schema:()=>gn,formatMarkdown:()=>mt,getPromptFields:()=>Ip,getTopLevelFieldFromIssuePath:()=>Dp,getTypesForFile:()=>Ke,isExcluded:()=>yt,loadContractDefinitions:()=>kp,loadMdbaseConfig:()=>ai,loadTypeDefinitions:()=>Ap,normalizeSafeRelativePath:()=>yn,parseFrontmatter:()=>Me,readCollectionRecords:()=>Ep,resolveFilenameForType:()=>fw,resolveFolderForType:()=>uw,schemaFromV03Fields:()=>es,slugify:()=>$p,v03TypeDefFromFrontmatter:()=>wc,validateCollection:()=>Mp,validateFile:()=>_c,validateRecordAgainstType:()=>ts});function yR(){return _o||(_o=new tw.Ajv2020({allErrors:!0,strict:!1,allowUnionTypes:!0}),(0,rw.default)(_o),_o)}function W(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Oe(r){return JSON.parse(JSON.stringify(r))}function gR(r){if(r===!0)return!0;if(r===!1)return!1;if(r==="warn")return"warn"}function vp(r){return Array.isArray(r)?`[${r.map(e=>vp(e)).join(",")}]`:W(r)?`{${Object.keys(r).sort().map(t=>`${JSON.stringify(t)}:${vp(r[t])}`).join(",")}}`:JSON.stringify(r)}function bR(r){let e=r.indexOf("."),t=r.indexOf("[");return e===-1&&t===-1?r:e===-1?r.slice(0,t):t===-1?r.slice(0,e):r.slice(0,Math.min(e,t))}function vR(r){let e=new Map,t=new Set,n=i=>{let s=e.get(i);if(s)return s;let o=r.get(i);if(!o)return null;if(t.has(i)){let l={...o,fields:Oe(o.fields)};return e.set(i,l),l}t.add(i);let a=o.extends?n(o.extends):null;t.delete(i);let c={...o,fields:a?{...Oe(a.fields),...Oe(o.fields)}:Oe(o.fields),display_name_key:o.display_name_key??a?.display_name_key,path_pattern:o.path_pattern??a?.path_pattern,filename_pattern:o.filename_pattern??a?.filename_pattern,strict:o.strict!==void 0?o.strict:a?.strict,match:o.match??a?.match};return e.set(i,c),c};for(let i of r.keys())n(i);return e}function nw(r){let e=(0,oe.normalizePath)(r),t=e.lastIndexOf("/");return t>=0?e.slice(0,t):""}function iw(r){let e=r.trim();e.startsWith("[[")&&e.endsWith("]]")&&(e=e.slice(2,-2));let t=e.indexOf("|");t>=0&&(e=e.slice(0,t));let n=e.indexOf("#");return n>=0&&(e=e.slice(0,n)),e.trim()}function sw(r){return/^[a-z][a-z0-9+.-]*:\/\//i.test(r)}function ow(r,e,t){let n=iw(t);if(!n||sw(n))return null;let i=new Set,s=(0,oe.normalizePath)(n);i.add(s),s.endsWith(".md")||i.add(`${s}.md`);let o=nw(e);if(o){let c=(0,oe.normalizePath)(`${o}/${n}`);i.add(c),c.endsWith(".md")||i.add(`${c}.md`)}for(let c of i){let l=r.getAbstractFileByPath(c);if(l instanceof oe.TFile)return l}let a=n.replace(/\.md$/i,"");return r.getMarkdownFiles().find(c=>c.basename===a)??null}function wR(r,e,t){return sw(iw(t))||ow(r,e,t)!==null}function Me(r){let e=(0,oe.getFrontMatterInfo)(r);if(!e.exists)return{hasFrontmatter:!1,frontmatter:{},body:r};try{let t=e.frontmatter,n=(0,oe.parseYaml)(t);return n==null&&t.trim()!==""?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e.contentStart),error:"Frontmatter must be a YAML object"}:n!=null&&!W(n)?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e.contentStart),error:"Frontmatter must be a YAML object"}:{hasFrontmatter:!0,frontmatter:n??{},body:r.slice(e.contentStart)}}catch(t){return{hasFrontmatter:!0,frontmatter:{},body:r.slice(e.contentStart),error:t instanceof Error?t.message:String(t)}}}function mt(r,e=""){if(Object.keys(r).length===0)return e;let t=(0,oe.stringifyYaml)(r).trimEnd(),n=e.replace(/^\n+/,"");return`--- + deps: ${t}}`};var X1={keyword:"dependencies",type:"object",schemaType:"object",error:br.error,code(r){let[e,t]=Q1(r);bb(r,e),vb(r,t)}};function Q1({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 bb(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,ho.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,ho.checkReportMissingProp)(r,l)}):(t.if((0,pf._)`${c} && (${(0,ho.checkMissingProp)(r,a,s)})`),(0,ho.reportMissingProp)(r,s),t.else())}}br.validatePropertyDeps=bb;function vb(r,e=r.schema){let{gen:t,data:n,keyword:i,it:s}=r,o=t.name("valid");for(let a in e)(0,Y1.alwaysValidSchema)(s,e[a])||(t.if((0,ho.propertyInData)(t,n,a,s.opts.ownProperties),()=>{let c=r.subschema({keyword:i,schemaProp:a},o);r.mergeValidEvaluated(c,o)},()=>t.var(o,!0)),r.ok(o))}br.validateSchemaDeps=vb;br.default=X1});var _b=A(hf=>{"use strict";Object.defineProperty(hf,"__esModule",{value:!0});var wb=U(),Z1=Q(),eM={message:"property name must be valid",params:({params:r})=>(0,wb._)`{propertyName: ${r.propertyName}}`},tM={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:eM,code(r){let{gen:e,schema:t,data:n,it:i}=r;if((0,Z1.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,wb.not)(s),()=>{r.error(!0),i.allErrors||e.break()})}),r.ok(s)}};hf.default=tM});var yf=A(mf=>{"use strict";Object.defineProperty(mf,"__esModule",{value:!0});var ac=Nt(),Qt=U(),rM=Dt(),cc=Q(),nM={message:"must NOT have additional properties",params:({params:r})=>(0,Qt._)`{additionalProperty: ${r.additionalProperty}}`},iM={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:nM,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,cc.alwaysValidSchema)(o,t))return;let l=(0,ac.allSchemaProperties)(n.properties),u=(0,ac.allSchemaProperties)(n.patternProperties);d(),r.ok((0,Qt._)`${s} === ${rM.default.errors}`);function d(){e.forIn("key",i,y=>{!l.length&&!u.length?h(y):e.if(f(y),()=>h(y))})}function f(y){let g;if(l.length>8){let b=(0,cc.schemaRefOrVal)(o,n.properties,"properties");g=(0,ac.isOwnProperty)(e,b,y)}else l.length?g=(0,Qt.or)(...l.map(b=>(0,Qt._)`${y} === ${b}`)):g=Qt.nil;return u.length&&(g=(0,Qt.or)(g,...u.map(b=>(0,Qt._)`${(0,ac.usePattern)(r,b)}.test(${y})`))),(0,Qt.not)(g)}function p(y){e.code((0,Qt._)`delete ${i}[${y}]`)}function h(y){if(c.removeAdditional==="all"||c.removeAdditional&&t===!1){p(y);return}if(t===!1){r.setParams({additionalProperty:y}),r.error(),a||e.break();return}if(typeof t=="object"&&!(0,cc.alwaysValidSchema)(o,t)){let g=e.name("valid");c.removeAdditional==="failing"?(m(y,g,!1),e.if((0,Qt.not)(g),()=>{r.reset(),p(y)})):(m(y,g),a||e.if((0,Qt.not)(g),()=>e.break()))}}function m(y,g,b){let v={keyword:"additionalProperties",dataProp:y,dataPropType:cc.Type.Str};b===!1&&Object.assign(v,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(v,g)}}};mf.default=iM});var $b=A(bf=>{"use strict";Object.defineProperty(bf,"__esModule",{value:!0});var sM=Ni(),Sb=Nt(),gf=Q(),xb=yf(),oM={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&&xb.default.code(new sM.KeywordCxt(s,xb.default,"additionalProperties"));let o=(0,Sb.allSchemaProperties)(t);for(let d of o)s.definedProperties.add(d);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=gf.mergeEvaluated.props(e,(0,gf.toHash)(o),s.props));let a=o.filter(d=>!(0,gf.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,Sb.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)}}};bf.default=oM});var Pb=A(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0});var Eb=Nt(),lc=U(),Ab=Q(),kb=Q(),aM={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,Eb.allSchemaProperties)(t),c=a.filter(m=>(0,Ab.alwaysValidSchema)(s,t[m]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=o.strictSchema&&!o.allowMatchingProperties&&i.properties,u=e.name("valid");s.props!==!0&&!(s.props instanceof lc.Name)&&(s.props=(0,kb.evaluatedPropsToName)(e,s.props));let{props:d}=s;f();function f(){for(let m of a)l&&p(m),s.allErrors?h(m):(e.var(u,!0),h(m),e.if(u))}function p(m){for(let y in l)new RegExp(m).test(y)&&(0,Ab.checkStrictMode)(s,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function h(m){e.forIn("key",n,y=>{e.if((0,lc._)`${(0,Eb.usePattern)(r,m)}.test(${y})`,()=>{let g=c.includes(m);g||r.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:kb.Type.Str},u),s.opts.unevaluated&&d!==!0?e.assign((0,lc._)`${d}[${y}]`,!0):!g&&!s.allErrors&&e.if((0,lc.not)(u),()=>e.break())})})}}};vf.default=aM});var Mb=A(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0});var cM=Q(),lM={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,cM.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"}};wf.default=lM});var Cb=A(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var dM=Nt(),uM={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:dM.validateUnion,error:{message:"must match a schema in anyOf"}};_f.default=uM});var Tb=A(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0});var dc=U(),fM=Q(),pM={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,dc._)`{passingSchemas: ${r.passing}}`},hM={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:pM,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,fM.alwaysValidSchema)(i,u)?e.var(c,!0):f=r.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,dc._)`${c} && ${o}`).assign(o,!1).assign(a,(0,dc._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(a,d),f&&r.mergeEvaluated(f,dc.Name)})})}}};Sf.default=hM});var Rb=A(xf=>{"use strict";Object.defineProperty(xf,"__esModule",{value:!0});var mM=Q(),yM={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,mM.alwaysValidSchema)(n,s))return;let a=r.subschema({keyword:"allOf",schemaProp:o},i);r.ok(i),r.mergeEvaluated(a)})}};xf.default=yM});var Db=A($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0});var uc=U(),Ob=Q(),gM={message:({params:r})=>(0,uc.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,uc._)`{failingKeyword: ${r.ifClause}}`},bM={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:gM,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,Ob.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=Ib(n,"then"),s=Ib(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,uc.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,uc._)`${u}`):r.setParams({ifClause:u})}}}};function Ib(r,e){let t=r.schema[e];return t!==void 0&&!(0,Ob.alwaysValidSchema)(r,t)}$f.default=bM});var Nb=A(Ef=>{"use strict";Object.defineProperty(Ef,"__esModule",{value:!0});var vM=Q(),wM={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,vM.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};Ef.default=wM});var kf=A(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});var _M=cf(),SM=hb(),xM=lf(),$M=yb(),EM=gb(),AM=oc(),kM=_b(),PM=yf(),MM=$b(),CM=Pb(),TM=Mb(),RM=Cb(),IM=Tb(),OM=Rb(),DM=Db(),NM=Nb();function LM(r=!1){let e=[TM.default,RM.default,IM.default,OM.default,DM.default,NM.default,kM.default,PM.default,AM.default,MM.default,CM.default];return r?e.push(SM.default,$M.default):e.push(_M.default,xM.default),e.push(EM.default),e}Af.default=LM});var Mf=A(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.dynamicAnchor=void 0;var Pf=U(),FM=Dt(),Lb=Zs(),jM=ec(),qM={keyword:"$dynamicAnchor",schemaType:"string",code:r=>Fb(r,r.schema)};function Fb(r,e){let{gen:t,it:n}=r;n.schemaEnv.root.dynamicAnchors[e]=!0;let i=(0,Pf._)`${FM.default.dynamicAnchors}${(0,Pf.getProperty)(e)}`,s=n.errSchemaPath==="#"?n.validateName:BM(r);t.if((0,Pf._)`!${i}`,()=>t.assign(i,s))}mo.dynamicAnchor=Fb;function BM(r){let{schemaEnv:e,schema:t,self:n}=r.it,{root:i,baseId:s,localRefs:o,meta:a}=e.root,{schemaId:c}=n.opts,l=new Lb.SchemaEnv({schema:t,schemaId:c,root:i,baseId:s,localRefs:o,meta:a});return Lb.compileSchema.call(n,l),(0,jM.getValidate)(r,l)}mo.default=qM});var Cf=A(yo=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});yo.dynamicRef=void 0;var jb=U(),UM=Dt(),qb=ec(),VM={keyword:"$dynamicRef",schemaType:"string",code:r=>Bb(r,r.schema)};function Bb(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,jb._)`${UM.default.dynamicAnchors}${(0,jb.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,qb.callRef)(r,c),t.let(l,!0)}):()=>(0,qb.callRef)(r,c)}}yo.dynamicRef=Bb;yo.default=VM});var Ub=A(Tf=>{"use strict";Object.defineProperty(Tf,"__esModule",{value:!0});var HM=Mf(),zM=Q(),KM={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,HM.dynamicAnchor)(r,""):(0,zM.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};Tf.default=KM});var Vb=A(Rf=>{"use strict";Object.defineProperty(Rf,"__esModule",{value:!0});var WM=Cf(),GM={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,WM.dynamicRef)(r,r.schema)};Rf.default=GM});var Hb=A(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var JM=Mf(),YM=Cf(),XM=Ub(),QM=Vb(),ZM=[JM.default,YM.default,XM.default,QM.default];If.default=ZM});var Kb=A(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var zb=oc(),eC={keyword:"dependentRequired",type:"object",schemaType:"object",error:zb.error,code:r=>(0,zb.validatePropertyDeps)(r)};Of.default=eC});var Wb=A(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var tC=oc(),rC={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,tC.validateSchemaDeps)(r)};Df.default=rC});var Gb=A(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var nC=Q(),iC={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,nC.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};Nf.default=iC});var Jb=A(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var sC=Kb(),oC=Wb(),aC=Gb(),cC=[sC.default,oC.default,aC.default];Lf.default=cC});var Xb=A(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var hn=U(),Yb=Q(),lC=Dt(),dC={message:"must NOT have unevaluated properties",params:({params:r})=>(0,hn._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},uC={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:dC,code(r){let{gen:e,schema:t,data:n,errsCount:i,it:s}=r;if(!i)throw new Error("ajv implementation error");let{allErrors:o,props:a}=s;a instanceof hn.Name?e.if((0,hn._)`${a} !== true`,()=>e.forIn("key",n,d=>e.if(l(a,d),()=>c(d)))):a!==!0&&e.forIn("key",n,d=>a===void 0?c(d):e.if(u(a,d),()=>c(d))),s.props=!0,r.ok((0,hn._)`${i} === ${lC.default.errors}`);function c(d){if(t===!1){r.setParams({unevaluatedProperty:d}),r.error(),o||e.break();return}if(!(0,Yb.alwaysValidSchema)(s,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:d,dataPropType:Yb.Type.Str},f),o||e.if((0,hn.not)(f),()=>e.break())}}function l(d,f){return(0,hn._)`!${d} || !${d}[${f}]`}function u(d,f){let p=[];for(let h in d)d[h]===!0&&p.push((0,hn._)`${f} !== ${h}`);return(0,hn.and)(...p)}}};Ff.default=uC});var Zb=A(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var oi=U(),Qb=Q(),fC={message:({params:{len:r}})=>(0,oi.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,oi._)`{limit: ${r}}`},pC={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:fC,code(r){let{gen:e,schema:t,data:n,it:i}=r,s=i.items||0;if(s===!0)return;let o=e.const("len",(0,oi._)`${n}.length`);if(t===!1)r.setParams({len:s}),r.fail((0,oi._)`${o} > ${s}`);else if(typeof t=="object"&&!(0,Qb.alwaysValidSchema)(i,t)){let c=e.var("valid",(0,oi._)`${o} <= ${s}`);e.if((0,oi.not)(c),()=>a(c,s)),r.ok(c)}i.items=!0;function a(c,l){e.forRange("i",l,o,u=>{r.subschema({keyword:"unevaluatedItems",dataProp:u,dataPropType:Qb.Type.Num},c),i.allErrors||e.if((0,oi.not)(c),()=>e.break())})}}};jf.default=pC});var ev=A(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var hC=Xb(),mC=Zb(),yC=[hC.default,mC.default];qf.default=yC});var tv=A(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var xe=U(),gC={message:({schemaCode:r})=>(0,xe.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,xe._)`{format: ${r}}`},bC={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:gC,code(r,e){let{gen:t,data:n,$data:i,schema:s,schemaCode:o,it:a}=r,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;i?f():p();function f(){let h=t.scopeValue("formats",{ref:d.formats,code:c.code.formats}),m=t.const("fDef",(0,xe._)`${h}[${o}]`),y=t.let("fType"),g=t.let("format");t.if((0,xe._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>t.assign(y,(0,xe._)`${m}.type || "string"`).assign(g,(0,xe._)`${m}.validate`),()=>t.assign(y,(0,xe._)`"string"`).assign(g,m)),r.fail$data((0,xe.or)(b(),v()));function b(){return c.strictSchema===!1?xe.nil:(0,xe._)`${o} && !${g}`}function v(){let S=u.$async?(0,xe._)`(${m}.async ? await ${g}(${n}) : ${g}(${n}))`:(0,xe._)`${g}(${n})`,_=(0,xe._)`(typeof ${g} == "function" ? ${S} : ${g}.test(${n}))`;return(0,xe._)`${g} && ${g} !== true && ${y} === ${e} && !${_}`}}function p(){let h=d.formats[s];if(!h){b();return}if(h===!0)return;let[m,y,g]=v(h);m===e&&r.pass(S());function b(){if(c.strictSchema===!1){d.logger.warn(_());return}throw new Error(_());function _(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function v(_){let E=_ instanceof RegExp?(0,xe.regexpCode)(_):c.code.formats?(0,xe._)`${c.code.formats}${(0,xe.getProperty)(s)}`:void 0,k=t.scopeValue("formats",{key:s,ref:_,code:E});return typeof _=="object"&&!(_ instanceof RegExp)?[_.type||"string",_.validate,(0,xe._)`${k}.validate`]:["string",_,k]}function S(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!u.$async)throw new Error("async format in sync schema");return(0,xe._)`await ${g}(${n})`}return typeof y=="function"?(0,xe._)`${g}(${n})`:(0,xe._)`${g}.test(${n})`}}}};Bf.default=bC});var Vf=A(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var vC=tv(),wC=[vC.default];Uf.default=wC});var Hf=A(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.contentVocabulary=Ui.metadataVocabulary=void 0;Ui.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Ui.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var nv=A(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var _C=Vu(),SC=of(),xC=kf(),$C=Hb(),EC=Jb(),AC=ev(),kC=Vf(),rv=Hf(),PC=[$C.default,_C.default,SC.default,(0,xC.default)(!0),kC.default,rv.metadataVocabulary,rv.contentVocabulary,EC.default,AC.default];zf.default=PC});var sv=A(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});fc.DiscrError=void 0;var iv;(function(r){r.Tag="tag",r.Mapping="mapping"})(iv||(fc.DiscrError=iv={}))});var Gf=A(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0});var Vi=U(),Kf=sv(),ov=Zs(),MC=Li(),CC=Q(),TC={message:({params:{discrError:r,tagName:e}})=>r===Kf.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,Vi._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},RC={keyword:"discriminator",type:"object",schemaType:"object",error:TC,code(r){let{gen:e,data:t,schema:n,parentSchema:i,it:s}=r,{oneOf:o}=i;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,Vi._)`${t}${(0,Vi.getProperty)(a)}`);e.if((0,Vi._)`typeof ${l} == "string"`,()=>u(),()=>r.error(!1,{discrError:Kf.DiscrError.Tag,tag:l,tagName:a})),r.ok(c);function u(){let p=f();e.if(!1);for(let h in p)e.elseIf((0,Vi._)`${l} === ${h}`),e.assign(c,d(p[h]));e.else(),r.error(!1,{discrError:Kf.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function d(p){let h=e.name("valid"),m=r.subschema({keyword:"oneOf",schemaProp:p},h);return r.mergeEvaluated(m,Vi.Name),h}function f(){var p;let h={},m=g(i),y=!0;for(let S=0;S{IC.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 cv=A((Uq,OC)=>{OC.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 lv=A((Vq,DC)=>{DC.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 dv=A((Hq,NC)=>{NC.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 uv=A((zq,LC)=>{LC.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 fv=A((Kq,FC)=>{FC.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 pv=A((Wq,jC)=>{jC.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 hv=A((Gq,qC)=>{qC.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 mv=A(Jf=>{"use strict";Object.defineProperty(Jf,"__esModule",{value:!0});var BC=av(),UC=cv(),VC=lv(),HC=dv(),zC=uv(),KC=fv(),WC=pv(),GC=hv(),JC=["/properties"];function YC(r){return[BC,UC,VC,HC,zC,e(this,KC),WC,e(this,GC)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,n){return r?t.$dataMetaSchema(n,JC):n}}Jf.default=YC});var Qf=A((ye,Xf)=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.MissingRefError=ye.ValidationError=ye.CodeGen=ye.Name=ye.nil=ye.stringify=ye.str=ye._=ye.KeywordCxt=ye.Ajv2020=void 0;var XC=qu(),QC=nv(),ZC=Gf(),eT=mv(),Yf="https://json-schema.org/draft/2020-12/schema",Hi=class extends XC.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),QC.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(ZC.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(eT.default.call(this,e),this.refs["http://json-schema.org/schema"]=Yf)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Yf)?Yf:void 0)}};ye.Ajv2020=Hi;Xf.exports=ye=Hi;Xf.exports.Ajv2020=Hi;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=Hi;var tT=Ni();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return tT.KeywordCxt}});var zi=U();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return zi._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return zi.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return zi.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return zi.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return zi.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return zi.CodeGen}});var rT=Qs();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return rT.default}});var nT=Li();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return nT.default}})});var xv=A(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.formatNames=wr.fastFormats=wr.fullFormats=void 0;function vr(r,e){return{validate:r,compare:e}}wr.fullFormats={date:vr(vv,rp),time:vr(ep(!0),np),"date-time":vr(yv(!0),_v),"iso-time":vr(ep(),wv),"iso-date-time":vr(yv(),Sv),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:lT,"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:yT,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:dT,int32:{type:"number",validate:pT},int64:{type:"number",validate:hT},float:{type:"number",validate:bv},double:{type:"number",validate:bv},password:!0,binary:!0};wr.fastFormats={...wr.fullFormats,date:vr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,rp),time:vr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,np),"date-time":vr(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,_v),"iso-time":vr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,wv),"iso-date-time":vr(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Sv),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};wr.formatNames=Object.keys(wr.fullFormats);function iT(r){return r%4===0&&(r%100!==0||r%400===0)}var sT=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,oT=[0,31,28,31,30,31,30,31,31,30,31,30,31];function vv(r){let e=sT.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&&iT(t)?29:oT[n])}function rp(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 np(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 wv(r,e){if(!(r&&e))return;let t=Zf.exec(r),n=Zf.exec(e);if(t&&n)return r=t[1]+t[2]+t[3],e=n[1]+n[2]+n[3],r>e?1:r=uT}function hT(r){return Number.isInteger(r)}function bv(){return!0}var mT=/[^\\]\\Z/;function yT(r){if(mT.test(r))return!1;try{return new RegExp(r),!0}catch{return!1}}});var Ev=A(ip=>{"use strict";Object.defineProperty(ip,"__esModule",{value:!0});var gT=Vu(),bT=of(),vT=kf(),wT=Vf(),$v=Hf(),_T=[gT.default,bT.default,(0,vT.default)(),wT.default,$v.metadataVocabulary,$v.contentVocabulary];ip.default=_T});var Av=A((Qq,ST)=>{ST.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 Pv=A((ge,sp)=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.MissingRefError=ge.ValidationError=ge.CodeGen=ge.Name=ge.nil=ge.stringify=ge.str=ge._=ge.KeywordCxt=ge.Ajv=void 0;var xT=qu(),$T=Ev(),ET=Gf(),kv=Av(),AT=["/properties"],pc="http://json-schema.org/draft-07/schema",Ki=class extends xT.default{_addVocabularies(){super._addVocabularies(),$T.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(ET.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(kv,AT):kv;this.addMetaSchema(e,pc,!1),this.refs["http://json-schema.org/schema"]=pc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(pc)?pc:void 0)}};ge.Ajv=Ki;sp.exports=ge=Ki;sp.exports.Ajv=Ki;Object.defineProperty(ge,"__esModule",{value:!0});ge.default=Ki;var kT=Ni();Object.defineProperty(ge,"KeywordCxt",{enumerable:!0,get:function(){return kT.KeywordCxt}});var Wi=U();Object.defineProperty(ge,"_",{enumerable:!0,get:function(){return Wi._}});Object.defineProperty(ge,"str",{enumerable:!0,get:function(){return Wi.str}});Object.defineProperty(ge,"stringify",{enumerable:!0,get:function(){return Wi.stringify}});Object.defineProperty(ge,"nil",{enumerable:!0,get:function(){return Wi.nil}});Object.defineProperty(ge,"Name",{enumerable:!0,get:function(){return Wi.Name}});Object.defineProperty(ge,"CodeGen",{enumerable:!0,get:function(){return Wi.CodeGen}});var PT=Qs();Object.defineProperty(ge,"ValidationError",{enumerable:!0,get:function(){return PT.default}});var MT=Li();Object.defineProperty(ge,"MissingRefError",{enumerable:!0,get:function(){return MT.default}})});var Mv=A(Gi=>{"use strict";Object.defineProperty(Gi,"__esModule",{value:!0});Gi.formatLimitDefinition=void 0;var CT=Pv(),Zt=U(),mn=Zt.operators,hc={formatMaximum:{okStr:"<=",ok:mn.LTE,fail:mn.GT},formatMinimum:{okStr:">=",ok:mn.GTE,fail:mn.LT},formatExclusiveMaximum:{okStr:"<",ok:mn.LT,fail:mn.GTE},formatExclusiveMinimum:{okStr:">",ok:mn.GT,fail:mn.LTE}},TT={message:({keyword:r,schemaCode:e})=>(0,Zt.str)`should be ${hc[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Zt._)`{comparison: ${hc[r].okStr}, limit: ${e}}`};Gi.formatLimitDefinition={keyword:Object.keys(hc),type:"string",schemaType:"string",$data:!0,error:TT,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 CT.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,Zt._)`${f}[${c.schemaCode}]`);r.fail$data((0,Zt.or)((0,Zt._)`typeof ${p} != "object"`,(0,Zt._)`${p} instanceof RegExp`,(0,Zt._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let f=c.schema,p=a.formats[f];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${i}": format "${f}" does not define "compare" function`);let h=e.scopeValue("formats",{key:f,ref:p,code:o.code.formats?(0,Zt._)`${o.code.formats}${(0,Zt.getProperty)(f)}`:void 0});r.fail$data(d(h))}function d(f){return(0,Zt._)`${f}.compare(${t}, ${n}) ${hc[i].fail} 0`}},dependencies:["format"]};var RT=r=>(r.addKeyword(Gi.formatLimitDefinition),r);Gi.default=RT});var cp=A((go,Rv)=>{"use strict";Object.defineProperty(go,"__esModule",{value:!0});var Ji=xv(),IT=Mv(),op=U(),Cv=new op.Name("fullFormats"),OT=new op.Name("fastFormats"),ap=(r,e={keywords:!0})=>{if(Array.isArray(e))return Tv(r,e,Ji.fullFormats,Cv),r;let[t,n]=e.mode==="fast"?[Ji.fastFormats,OT]:[Ji.fullFormats,Cv],i=e.formats||Ji.formatNames;return Tv(r,i,t,n),e.keywords&&(0,IT.default)(r),r};ap.get=(r,e="full")=>{let n=(e==="fast"?Ji.fastFormats:Ji.fullFormats)[r];if(!n)throw new Error(`Unknown format "${r}"`);return n};function Tv(r,e,t,n){var i,s;(i=(s=r.opts.code).formats)!==null&&i!==void 0||(s.formats=(0,op._)`require("ajv-formats/dist/formats").${n}`);for(let o of e)r.addFormat(o,t[o])}Rv.exports=go=ap;Object.defineProperty(go,"__esModule",{value:!0});go.default=ap});var bo=A((eB,Lv)=>{"use strict";var Iv="[^\\\\/]",DT="(?=.)",Ov="[^/]",lp="(?:\\/|$)",Dv="(?:^|\\/)",dp=`\\.{1,2}${lp}`,NT="(?!\\.)",LT=`(?!${Dv}${dp})`,FT=`(?!\\.{0,1}${lp})`,jT=`(?!${dp})`,qT="[^.\\/]",BT=`${Ov}*?`,UT="/",Nv={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:DT,QMARK:Ov,END_ANCHOR:lp,DOTS_SLASH:dp,NO_DOT:NT,NO_DOTS:LT,NO_DOT_SLASH:FT,NO_DOTS_SLASH:jT,QMARK_NO_DOT:qT,STAR:BT,START_ANCHOR:Dv,SEP:UT},VT={...Nv,SLASH_LITERAL:"[\\\\/]",QMARK:Iv,STAR:`${Iv}*?`,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:"\\"},HT={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};Lv.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:HT,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?VT:Nv}}});var vo=A(ht=>{"use strict";var{REGEX_BACKSLASH:zT,REGEX_REMOVE_BACKSLASH:KT,REGEX_SPECIAL_CHARS:WT,REGEX_SPECIAL_CHARS_GLOBAL:GT}=bo();ht.isObject=r=>r!==null&&typeof r=="object"&&!Array.isArray(r);ht.hasRegexChars=r=>WT.test(r);ht.isRegexChar=r=>r.length===1&&ht.hasRegexChars(r);ht.escapeRegex=r=>r.replace(GT,"\\$1");ht.toPosixSlashes=r=>r.replace(zT,"/");ht.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let r=navigator.platform.toLowerCase();return r==="win32"||r==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":!1};ht.removeBackslashes=r=>r.replace(KT,e=>e==="\\"?"":e);ht.escapeLast=(r,e,t)=>{let n=r.lastIndexOf(e,t);return n===-1?r:r[n-1]==="\\"?ht.escapeLast(r,e,n-1):`${r.slice(0,n)}\\${r.slice(n)}`};ht.removePrefix=(r,e={})=>{let t=r;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};ht.wrapOutput=(r,e={},t={})=>{let n=t.contains?"":"^",i=t.contains?"":"$",s=`${n}(?:${r})${i}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s};ht.basename=(r,{windows:e}={})=>{let t=r.split(e?/[\\/]/:"/"),n=t[t.length-1];return n===""?t[t.length-2]:n}});var zv=A((rB,Hv)=>{"use strict";var Fv=vo(),{CHAR_ASTERISK:up,CHAR_AT:JT,CHAR_BACKWARD_SLASH:Yi,CHAR_COMMA:YT,CHAR_DOT:fp,CHAR_EXCLAMATION_MARK:pp,CHAR_FORWARD_SLASH:Vv,CHAR_LEFT_CURLY_BRACE:hp,CHAR_LEFT_PARENTHESES:mc,CHAR_LEFT_SQUARE_BRACKET:XT,CHAR_PLUS:QT,CHAR_QUESTION_MARK:jv,CHAR_RIGHT_CURLY_BRACE:ZT,CHAR_RIGHT_PARENTHESES:qv,CHAR_RIGHT_SQUARE_BRACKET:eR}=bo(),Bv=r=>r===Vv||r===Yi,Uv=r=>{r.isPrefix!==!0&&(r.depth=r.isGlobstar?1/0:1)},tR=(r,e)=>{let t=e||{},n=r.length-1,i=t.parts===!0||t.tokens===!0||t.scanToEnd===!0,s=[],o=[],a=[],c=r,l=-1,u=0,d=0,f=!1,p=!1,h=!1,m=!1,y=!1,g=!1,b=!1,v=!1,S=!1,_=!1,E=0,k,x,T={value:"",depth:0,isGlob:!1},$=()=>l>=n,q=()=>c.charCodeAt(l+1),C=()=>(k=x,c.charCodeAt(++l));for(;l0&&(P=c.slice(0,u),c=c.slice(u),d-=u),V&&h===!0&&d>0?(V=c.slice(0,d),M=c.slice(d)):h===!0?(V="",M=c):V=c,V&&V!==""&&V!=="/"&&V!==c&&Bv(V.charCodeAt(V.length-1))&&(V=V.slice(0,-1)),t.unescape===!0&&(M&&(M=Fv.removeBackslashes(M)),V&&b===!0&&(V=Fv.removeBackslashes(V)));let Be={prefix:P,input:r,start:u,base:V,glob:M,isBrace:f,isBracket:p,isGlob:h,isExtglob:m,isGlobstar:y,negated:v,negatedExtglob:S};if(t.tokens===!0&&(Be.maxDepth=0,Bv(x)||o.push(T),Be.tokens=o),t.parts===!0||t.tokens===!0){let ce;for(let ke=0;ke=u&&(a.push(Hn),ce=Ls)}let ct=ce!==void 0?ce+1:u,$t=r.slice(ct);a.push($t),t.tokens&&ce&&ce+1{"use strict";var wo=bo(),Et=vo(),{MAX_LENGTH:yc,POSIX_REGEX_SOURCE:rR,REGEX_NON_SPECIAL_CHARS:nR,REGEX_SPECIAL_CHARS_BACKREF:iR,REPLACEMENTS:Kv}=wo,sR=(r,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...r,e);r.sort();let t=`[${r.join("-")}]`;try{new RegExp(t)}catch{return r.map(i=>Et.escapeRegex(i)).join("..")}return t},Xi=(r,e)=>`Missing ${r}: "${e}" - use "\\\\${e}" to match literal characters`,Wv=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},oR=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},yp=r=>{let e=r.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(oR(e))return e.replace(/\\(.)/g,"$1")},aR=r=>{let e=r.map(yp).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}}}}},cR=r=>`${r.length===1?Et.escapeRegex(r[0]):`[${r.map(t=>Et.escapeRegex(t)).join("")}]`}*`,lR=r=>{let e=0,t=[];for(;eo.trim());if(i.length!==1)return;let s=yp(i[0]);if(!s||s.length!==1)return;t.push(s),e+=n.end+1}if(!(t.length<1))return t},dR=r=>{let e=0,t=r.trim(),n=mp(t);for(;n;)e++,t=n.body.trim(),n=mp(t);return e},uR=(r,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:wo.DEFAULT_MAX_EXTGLOB_RECURSION,n=Wv(r).map(a=>a.trim());if(n.length>1&&(n.some(a=>a==="")||n.some(a=>/^[*?]+$/.test(a))||aR(n)))return{risky:!0};let i=[],s=!1,o=!0;for(let a of n){let c=lR(a);if(c){s=!0,i.push(...c);continue}let l=yp(a);if(l&&l.length===1){i.push(l);continue}if(o=!1,dR(a)>t)return{risky:!0}}return s?o?{risky:!0,safeOutput:cR([...new Set(i)])}:{risky:!0}:{risky:!1}},gp=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a string");r=Kv[r]||r;let t={...e},n=typeof t.maxLength=="number"?Math.min(yc,t.maxLength):yc,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=wo.globChars(t.windows),l=wo.extglobChars(c),{DOT_LITERAL:u,PLUS_LITERAL:d,SLASH_LITERAL:f,ONE_CHAR:p,DOTS_SLASH:h,NO_DOT:m,NO_DOT_SLASH:y,NO_DOTS_SLASH:g,QMARK:b,QMARK_NO_DOT:v,STAR:S,START_ANCHOR:_}=c,E=I=>`(${a}(?:(?!${_}${I.dot?h:u}).)*?)`,k=t.dot?"":m,x=t.dot?b:v,T=t.bash===!0?E(t):S;t.capture&&(T=`(${T})`),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=Et.removePrefix(r,$),i=r.length;let q=[],C=[],V=[],P=s,M,Be=()=>$.index===i-1,ce=$.peek=(I=1)=>r[$.index+I],ct=$.advance=()=>r[++$.index]||"",$t=()=>r.slice($.index+1),ke=(I="",ve=0)=>{$.consumed+=I,$.index+=ve},Ai=I=>{$.output+=I.output!=null?I.output:I.value,ke(I.value)},Ls=()=>{let I=1;for(;ce()==="!"&&(ce(2)!=="("||ce(3)==="?");)ct(),$.start++,I++;return I%2===0?!1:($.negated=!0,$.start++,!0)},Hn=I=>{$[I]++,V.push(I)},on=I=>{$[I]--,V.pop()},Z=I=>{if(P.type==="globstar"){let ve=$.braces>0&&(I.type==="comma"||I.type==="brace"),R=I.extglob===!0||q.length&&(I.type==="pipe"||I.type==="paren");I.type!=="slash"&&I.type!=="paren"&&!ve&&!R&&($.output=$.output.slice(0,-P.output.length),P.type="star",P.value="*",P.output=T,$.output+=P.output)}if(q.length&&I.type!=="paren"&&(q[q.length-1].inner+=I.value),(I.value||I.output)&&Ai(I),P&&P.type==="text"&&I.type==="text"){P.output=(P.output||P.value)+I.value,P.value+=I.value;return}I.prev=P,o.push(I),P=I},Pa=(I,ve)=>{let R={...l[ve],conditions:1,inner:""};R.prev=P,R.parens=$.parens,R.output=$.output,R.startIndex=$.index,R.tokensIndex=o.length;let ee=(t.capture?"(":"")+R.open;Hn("parens"),Z({type:I,value:ve,output:$.output?"":p}),Z({type:"paren",extglob:!0,value:ct(),output:ee}),q.push(R)},eE=I=>{let ve=r.slice(I.startIndex,$.index+1),R=r.slice(I.startIndex+2,$.index),ee=uR(R,t);if((I.type==="plus"||I.type==="star")&&ee.risky){let ue=ee.safeOutput?(I.output?"":p)+(t.capture?`(${ee.safeOutput})`:ee.safeOutput):void 0,hr=o[I.tokensIndex];hr.type="text",hr.value=ve,hr.output=ue||Et.escapeRegex(ve);for(let zn=I.tokensIndex+1;zn1&&I.inner.includes("/")&&(ue=E(t)),(ue!==T||Be()||/^\)+$/.test($t()))&&(he=I.close=`)$))${ue}`),I.inner.includes("*")&&(Pe=$t())&&/^\.[^\\/.]+$/.test(Pe)){let hr=gp(Pe,{...e,fastpaths:!1}).output;he=I.close=`)${hr})${ue})`}I.prev.type==="bos"&&($.negatedExtglob=!0)}Z({type:"paren",extglob:!0,value:M,output:he}),on("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(r)){let I=!1,ve=r.replace(iR,(R,ee,he,Pe,ue,hr)=>Pe==="\\"?(I=!0,R):Pe==="?"?ee?ee+Pe+(ue?b.repeat(ue.length):""):hr===0?x+(ue?b.repeat(ue.length):""):b.repeat(he.length):Pe==="."?u.repeat(he.length):Pe==="*"?ee?ee+Pe+(ue?T:""):T:ee?R:`\\${R}`);return I===!0&&(t.unescape===!0?ve=ve.replace(/\\/g,""):ve=ve.replace(/\\+/g,R=>R.length%2===0?"\\\\":R?"\\":"")),ve===r&&t.contains===!0?($.output=r,$):($.output=Et.wrapOutput(ve,$,e),$)}for(;!Be();){if(M=ct(),M==="\0")continue;if(M==="\\"){let R=ce();if(R==="/"&&t.bash!==!0||R==="."||R===";")continue;if(!R){M+="\\",Z({type:"text",value:M});continue}let ee=/^\\+/.exec($t()),he=0;if(ee&&ee[0].length>2&&(he=ee[0].length,$.index+=he,he%2!==0&&(M+="\\")),t.unescape===!0?M=ct():M+=ct(),$.brackets===0){Z({type:"text",value:M});continue}}if($.brackets>0&&(M!=="]"||P.value==="["||P.value==="[^")){if(t.posix!==!1&&M===":"){let R=P.value.slice(1);if(R.includes("[")&&(P.posix=!0,R.includes(":"))){let ee=P.value.lastIndexOf("["),he=P.value.slice(0,ee),Pe=P.value.slice(ee+2),ue=rR[Pe];if(ue){P.value=he+ue,$.backtrack=!0,ct(),!s.output&&o.indexOf(P)===1&&(s.output=p);continue}}}(M==="["&&ce()!==":"||M==="-"&&ce()==="]")&&(M=`\\${M}`),M==="]"&&(P.value==="["||P.value==="[^")&&(M=`\\${M}`),t.posix===!0&&M==="!"&&P.value==="["&&(M="^"),P.value+=M,Ai({value:M});continue}if($.quotes===1&&M!=='"'){M=Et.escapeRegex(M),P.value+=M,Ai({value:M});continue}if(M==='"'){$.quotes=$.quotes===1?0:1,t.keepQuotes===!0&&Z({type:"text",value:M});continue}if(M==="("){Hn("parens"),Z({type:"paren",value:M});continue}if(M===")"){if($.parens===0&&t.strictBrackets===!0)throw new SyntaxError(Xi("opening","("));let R=q[q.length-1];if(R&&$.parens===R.parens+1){eE(q.pop());continue}Z({type:"paren",value:M,output:$.parens?")":"\\)"}),on("parens");continue}if(M==="["){if(t.nobracket===!0||!$t().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(Xi("closing","]"));M=`\\${M}`}else Hn("brackets");Z({type:"bracket",value:M});continue}if(M==="]"){if(t.nobracket===!0||P&&P.type==="bracket"&&P.value.length===1){Z({type:"text",value:M,output:`\\${M}`});continue}if($.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(Xi("opening","["));Z({type:"text",value:M,output:`\\${M}`});continue}on("brackets");let R=P.value.slice(1);if(P.posix!==!0&&R[0]==="^"&&!R.includes("/")&&(M=`/${M}`),P.value+=M,Ai({value:M}),t.literalBrackets===!1||Et.hasRegexChars(R))continue;let ee=Et.escapeRegex(P.value);if($.output=$.output.slice(0,-P.value.length),t.literalBrackets===!0){$.output+=ee,P.value=ee;continue}P.value=`(${a}${ee}|${P.value})`,$.output+=P.value;continue}if(M==="{"&&t.nobrace!==!0){Hn("braces");let R={type:"brace",value:M,output:"(",outputIndex:$.output.length,tokensIndex:$.tokens.length};C.push(R),Z(R);continue}if(M==="}"){let R=C[C.length-1];if(t.nobrace===!0||!R){Z({type:"text",value:M,output:M});continue}let ee=")";if(R.dots===!0){let he=o.slice(),Pe=[];for(let ue=he.length-1;ue>=0&&(o.pop(),he[ue].type!=="brace");ue--)he[ue].type!=="dots"&&Pe.unshift(he[ue].value);ee=sR(Pe,t),$.backtrack=!0}if(R.comma!==!0&&R.dots!==!0){let he=$.output.slice(0,R.outputIndex),Pe=$.tokens.slice(R.tokensIndex);R.value=R.output="\\{",M=ee="\\}",$.output=he;for(let ue of Pe)$.output+=ue.output||ue.value}Z({type:"brace",value:M,output:ee}),on("braces"),C.pop();continue}if(M==="|"){q.length>0&&q[q.length-1].conditions++,Z({type:"text",value:M});continue}if(M===","){let R=M,ee=C[C.length-1];ee&&V[V.length-1]==="braces"&&(ee.comma=!0,R="|"),Z({type:"comma",value:M,output:R});continue}if(M==="/"){if(P.type==="dot"&&$.index===$.start+1){$.start=$.index+1,$.consumed="",$.output="",o.pop(),P=s;continue}Z({type:"slash",value:M,output:f});continue}if(M==="."){if($.braces>0&&P.type==="dot"){P.value==="."&&(P.output=u);let R=C[C.length-1];P.type="dots",P.output+=M,P.value+=M,R.dots=!0;continue}if($.braces+$.parens===0&&P.type!=="bos"&&P.type!=="slash"){Z({type:"text",value:M,output:u});continue}Z({type:"dot",value:M,output:u});continue}if(M==="?"){if(!(P&&P.value==="(")&&t.noextglob!==!0&&ce()==="("&&ce(2)!=="?"){Pa("qmark",M);continue}if(P&&P.type==="paren"){let ee=ce(),he=M;(P.value==="("&&!/[!=<:]/.test(ee)||ee==="<"&&!/<([!=]|\w+>)/.test($t()))&&(he=`\\${M}`),Z({type:"text",value:M,output:he});continue}if(t.dot!==!0&&(P.type==="slash"||P.type==="bos")){Z({type:"qmark",value:M,output:v});continue}Z({type:"qmark",value:M,output:b});continue}if(M==="!"){if(t.noextglob!==!0&&ce()==="("&&(ce(2)!=="?"||!/[!=<:]/.test(ce(3)))){Pa("negate",M);continue}if(t.nonegate!==!0&&$.index===0){Ls();continue}}if(M==="+"){if(t.noextglob!==!0&&ce()==="("&&ce(2)!=="?"){Pa("plus",M);continue}if(P&&P.value==="("||t.regex===!1){Z({type:"plus",value:M,output:d});continue}if(P&&(P.type==="bracket"||P.type==="paren"||P.type==="brace")||$.parens>0){Z({type:"plus",value:M});continue}Z({type:"plus",value:d});continue}if(M==="@"){if(t.noextglob!==!0&&ce()==="("&&ce(2)!=="?"){Z({type:"at",extglob:!0,value:M,output:""});continue}Z({type:"text",value:M});continue}if(M!=="*"){(M==="$"||M==="^")&&(M=`\\${M}`);let R=nR.exec($t());R&&(M+=R[0],$.index+=R[0].length),Z({type:"text",value:M});continue}if(P&&(P.type==="globstar"||P.star===!0)){P.type="star",P.star=!0,P.value+=M,P.output=T,$.backtrack=!0,$.globstar=!0,ke(M);continue}let I=$t();if(t.noextglob!==!0&&/^\([^?]/.test(I)){Pa("star",M);continue}if(P.type==="star"){if(t.noglobstar===!0){ke(M);continue}let R=P.prev,ee=R.prev,he=R.type==="slash"||R.type==="bos",Pe=ee&&(ee.type==="star"||ee.type==="globstar");if(t.bash===!0&&(!he||I[0]&&I[0]!=="/")){Z({type:"star",value:M,output:""});continue}let ue=$.braces>0&&(R.type==="comma"||R.type==="brace"),hr=q.length&&(R.type==="pipe"||R.type==="paren");if(!he&&R.type!=="paren"&&!ue&&!hr){Z({type:"star",value:M,output:""});continue}for(;I.slice(0,3)==="/**";){let ki=r[$.index+4];if(ki&&ki!=="/")break;I=I.slice(3),ke("/**",3)}let zn=Be()||$.parens>0&&I===")".repeat($.parens)&&!q.some(ki=>ki.type==="negate");if(R.type==="bos"&&Be()){P.type="globstar",P.value+=M,P.output=E(t),$.output=P.output,$.globstar=!0,ke(M);continue}if(R.type==="slash"&&R.prev.type!=="bos"&&!Pe&&zn){$.output=$.output.slice(0,-(R.output+P.output).length),R.output=`(?:${R.output}`,P.type="globstar",P.output=E(t)+(t.strictSlashes?")":"|$)"),P.value+=M,$.globstar=!0,$.output+=R.output+P.output,ke(M);continue}if(R.type==="slash"&&R.prev.type!=="bos"&&I[0]==="/"){let ki=I[1]!==void 0?"|$":"";$.output=$.output.slice(0,-(R.output+P.output).length),R.output=`(?:${R.output}`,P.type="globstar",P.output=`${E(t)}${f}|${f}${ki})`,P.value+=M,$.output+=R.output+P.output,$.globstar=!0,ke(M+ct()),Z({type:"slash",value:"/",output:""});continue}if(R.type==="bos"&&I[0]==="/"){P.type="globstar",P.value+=M,P.output=`(?:^|${f}|${E(t)}${f})`,$.output=P.output,$.globstar=!0,ke(M+ct()),Z({type:"slash",value:"/",output:""});continue}$.output=$.output.slice(0,-P.output.length),P.type="globstar",P.output=E(t),P.value+=M,$.output+=P.output,$.globstar=!0,ke(M);continue}let ve={type:"star",value:M,output:T};if(t.bash===!0){ve.output=".*?",(P.type==="bos"||P.type==="slash")&&(ve.output=k+ve.output),Z(ve);continue}if(P&&(P.type==="bracket"||P.type==="paren")&&t.regex===!0){ve.output=M,Z(ve);continue}($.index===$.start||P.type==="slash"||P.type==="dot")&&(P.type==="dot"?($.output+=y,P.output+=y):t.dot===!0?($.output+=g,P.output+=g):($.output+=k,P.output+=k),ce()!=="*"&&($.output+=p,P.output+=p)),Z(ve)}for(;$.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(Xi("closing","]"));$.output=Et.escapeLast($.output,"["),on("brackets")}for(;$.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(Xi("closing",")"));$.output=Et.escapeLast($.output,"("),on("parens")}for(;$.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(Xi("closing","}"));$.output=Et.escapeLast($.output,"{"),on("braces")}if(t.strictSlashes!==!0&&(P.type==="star"||P.type==="bracket")&&Z({type:"maybe_slash",value:"",output:`${f}?`}),$.backtrack===!0){$.output="";for(let I of $.tokens)$.output+=I.output!=null?I.output:I.value,I.suffix&&($.output+=I.suffix)}return $};gp.fastpaths=(r,e)=>{let t={...e},n=typeof t.maxLength=="number"?Math.min(yc,t.maxLength):yc,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);r=Kv[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}=wo.globChars(t.windows),h=t.dot?u:l,m=t.dot?d:l,y=t.capture?"":"?:",g={negated:!1,prefix:""},b=t.bash===!0?".*?":f;t.capture&&(b=`(${b})`);let v=k=>k.noglobstar===!0?b:`(${y}(?:(?!${p}${k.dot?c:s}).)*?)`,S=k=>{switch(k){case"*":return`${h}${a}${b}`;case".*":return`${s}${a}${b}`;case"*.*":return`${h}${b}${s}${a}${b}`;case"*/*":return`${h}${b}${o}${a}${m}${b}`;case"**":return h+v(t);case"**/*":return`(?:${h}${v(t)}${o})?${m}${a}${b}`;case"**/*.*":return`(?:${h}${v(t)}${o})?${m}${b}${s}${a}${b}`;case"**/.*":return`(?:${h}${v(t)}${o})?${s}${a}${b}`;default:{let x=/^(.*?)\.(\w+)$/.exec(k);if(!x)return;let T=S(x[1]);return T?T+s+x[2]:void 0}}},_=Et.removePrefix(r,g),E=S(_);return E&&t.strictSlashes!==!0&&(E+=`${o}?`),E};Gv.exports=gp});var Qv=A((iB,Xv)=>{"use strict";var fR=zv(),bp=Jv(),Yv=vo(),pR=bo(),hR=r=>r&&typeof r=="object"&&!Array.isArray(r),$e=(r,e,t=!1)=>{if(Array.isArray(r)){let u=r.map(f=>$e(f,e,t));return f=>{for(let p of u){let h=p(f);if(h)return h}return!1}}let n=hR(r)&&r.tokens&&r.input;if(r===""||typeof r!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let i=e||{},s=i.windows,o=n?$e.compileRe(r,e):$e.makeRe(r,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(i.ignore){let u={...e,ignore:null,onMatch:null,onResult:null};c=$e(i.ignore,u,t)}let l=(u,d=!1)=>{let{isMatch:f,match:p,output:h}=$e.test(u,o,e,{glob:r,posix:s}),m={glob:r,state:a,regex:o,posix:s,input:u,output:h,match:p,isMatch:f};return typeof i.onResult=="function"&&i.onResult(m),f===!1?(m.isMatch=!1,d?m:!1):c(u)?(typeof i.onIgnore=="function"&&i.onIgnore(m),m.isMatch=!1,d?m:!1):(typeof i.onMatch=="function"&&i.onMatch(m),d?m:!0)};return t&&(l.state=a),l};$e.test=(r,e,t,{glob:n,posix:i}={})=>{if(typeof r!="string")throw new TypeError("Expected input to be a string");if(r==="")return{isMatch:!1,output:""};let s=t||{},o=s.format||(i?Yv.toPosixSlashes:null),a=r===n,c=a&&o?o(r):r;return a===!1&&(c=o?o(r):r,a=c===n),(a===!1||s.capture===!0)&&(s.matchBase===!0||s.basename===!0?a=$e.matchBase(r,e,t,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};$e.matchBase=(r,e,t,n=t&&t.windows)=>(e instanceof RegExp?e:$e.makeRe(e,t)).test(Yv.basename(r,{windows:n}));$e.isMatch=(r,e,t)=>$e(e,t)(r);$e.parse=(r,e)=>Array.isArray(r)?r.map(t=>$e.parse(t,e)):bp(r,{...e,fastpaths:!1});$e.scan=(r,e)=>fR(r,e);$e.compileRe=(r,e,t=!1,n=!1)=>{if(t===!0)return r.output;let i=e||{},s=i.contains?"":"^",o=i.contains?"":"$",a=`${s}(?:${r.output})${o}`;r&&r.negated===!0&&(a=`^(?!${a}).*$`);let c=$e.toRegex(a,e);return n===!0&&(c.state=r),c};$e.makeRe=(r,e={},t=!1,n=!1)=>{if(!r||typeof r!="string")throw new TypeError("Expected a non-empty string");let i={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(r[0]==="."||r[0]==="*")&&(i.output=bp.fastpaths(r,e)),i.output||(i=bp(r,e)),$e.compileRe(i,e,t,n)};$e.toRegex=(r,e)=>{try{let t=e||{};return new RegExp(r,t.flags||(t.nocase?"i":""))}catch(t){if(e&&e.debug===!0)throw t;return/$^/}};$e.constants=pR;Xv.exports=$e});var vp=A((sB,tw)=>{"use strict";var Zv=Qv(),mR=vo();function ew(r,e,t=!1){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:mR.isWindows()}),Zv(r,e,t)}Object.assign(ew,Zv);tw.exports=ew});function wp(r,e){return gc(e.split("/"),r.split("/"))}function gc(r,e){if(e.length===0)return r.length===0;let[t,...n]=e;return t==="**"?gc(r,n)||r.length>0&&gc(r.slice(1),e):r.length===0?!1:Qi([...r[0]],[...t])&&gc(r.slice(1),n)}function Qi(r,e){if(e.length===0)return r.length===0;let[t,...n]=e;if(t==="*")return Qi(r,n)||r.length>0&&Qi(r.slice(1),e);if(t==="?")return r.length>0&&Qi(r.slice(1),n);if(t==="["){let i=yR(n);if(i)return r.length>0&&i.matches(r[0])&&Qi(r.slice(1),i.after)}return r[0]===t&&Qi(r.slice(1),n)}function yR(r){let e=r[0]==="!",t=[],n=e?1:0,i=!0;for(;n{let c=_o(a);return t.some(([l,u])=>l<=c&&c<=u)!==e},after:r.slice(n+1)};n+2{});var bw={};dy(bw,{MdbasePathError:()=>xo,applyReadDefaults:()=>UR,buildInitialFrontmatter:()=>Op,buildTypeTemplate:()=>Ip,buildUniqueNotePath:()=>Np,coerceFieldInput:()=>xc,createNoteFromType:()=>KR,createTypeDefinition:()=>VR,ensureCollectionInitialized:()=>$o,fieldsFromV03Schema:()=>gn,formatMarkdown:()=>mt,getPromptFields:()=>Dp,getTopLevelFieldFromIssuePath:()=>Lp,getTypesForFile:()=>Ke,isExcluded:()=>yt,loadContractDefinitions:()=>Mp,loadMdbaseConfig:()=>ai,loadTypeDefinitions:()=>Pp,normalizeSafeRelativePath:()=>yn,parseFrontmatter:()=>Ce,readCollectionRecords:()=>kp,resolveFilenameForType:()=>mw,resolveFolderForType:()=>hw,schemaFromV03Fields:()=>es,slugify:()=>Ep,v03TypeDefFromFrontmatter:()=>_c,validateCollection:()=>Rp,validateFile:()=>Sc,validateRecordAgainstType:()=>ts});function bR(){return So||(So=new iw.Ajv2020({allErrors:!0,strict:!1,allowUnionTypes:!0}),(0,sw.default)(So),So)}function K(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function De(r){return JSON.parse(JSON.stringify(r))}function vR(r){if(r===!0)return!0;if(r===!1)return!1;if(r==="warn")return"warn"}function _p(r){return Array.isArray(r)?`[${r.map(e=>_p(e)).join(",")}]`:K(r)?`{${Object.keys(r).sort().map(t=>`${JSON.stringify(t)}:${_p(r[t])}`).join(",")}}`:JSON.stringify(r)}function wR(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 _R(r){let e=new Map,t=new Set,n=i=>{let s=e.get(i);if(s)return s;let o=r.get(i);if(!o)return null;if(t.has(i)){let l={...o,fields:De(o.fields)};return e.set(i,l),l}t.add(i);let a=o.extends?n(o.extends):null;t.delete(i);let c={...o,fields:a?{...De(a.fields),...De(o.fields)}:De(o.fields),display_name_key:o.display_name_key??a?.display_name_key,path_pattern:o.path_pattern??a?.path_pattern,filename_pattern:o.filename_pattern??a?.filename_pattern,strict:o.strict!==void 0?o.strict:a?.strict,match:o.match??a?.match};return e.set(i,c),c};for(let i of r.keys())n(i);return e}function ow(r){let e=(0,oe.normalizePath)(r),t=e.lastIndexOf("/");return t>=0?e.slice(0,t):""}function aw(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 cw(r){return/^[a-z][a-z0-9+.-]*:\/\//i.test(r)}function lw(r,e,t){let n=aw(t);if(!n||cw(n))return null;let i=new Set,s=(0,oe.normalizePath)(n);i.add(s),s.endsWith(".md")||i.add(`${s}.md`);let o=ow(e);if(o){let c=(0,oe.normalizePath)(`${o}/${n}`);i.add(c),c.endsWith(".md")||i.add(`${c}.md`)}for(let c of i){let l=r.getAbstractFileByPath(c);if(l instanceof oe.TFile)return l}let a=n.replace(/\.md$/i,"");return r.getMarkdownFiles().find(c=>c.basename===a)??null}function SR(r,e,t){return cw(aw(t))||lw(r,e,t)!==null}function Ce(r){let e=(0,oe.getFrontMatterInfo)(r);if(!e.exists)return{hasFrontmatter:!1,frontmatter:{},body:r};try{let t=e.frontmatter,n=(0,oe.parseYaml)(t);return n==null&&t.trim()!==""?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e.contentStart),error:"Frontmatter must be a YAML object"}:n!=null&&!K(n)?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e.contentStart),error:"Frontmatter must be a YAML object"}:{hasFrontmatter:!0,frontmatter:n??{},body:r.slice(e.contentStart)}}catch(t){return{hasFrontmatter:!0,frontmatter:{},body:r.slice(e.contentStart),error:t instanceof Error?t.message:String(t)}}}function mt(r,e=""){if(Object.keys(r).length===0)return e;let t=(0,oe.stringifyYaml)(r).trimEnd(),n=e.replace(/^\n+/,"");return`--- ${t} --- -${n}`}async function ai(r){let e=r.getAbstractFileByPath("mdbase.yaml");if(!(e instanceof oe.TFile))return null;try{let t=await r.cachedRead(e),n=(0,oe.parseYaml)(t);if(!W(n))return null;let i=W(n.settings)?n.settings:{},s=W(n.runtime)?n.runtime:void 0;return{spec_version:typeof n.spec_version=="string"?n.spec_version:qr.spec_version,name:typeof n.name=="string"?n.name:qr.name,description:typeof n.description=="string"?n.description:qr.description,runtime:s?{profile_version:typeof s.profile_version=="string"?s.profile_version:void 0,enabled:typeof s.enabled=="boolean"?s.enabled:void 0,policy:typeof s.policy=="string"?s.policy:void 0}:void 0,settings:{types_folder:typeof i.types_folder=="string"?i.types_folder:qr.settings.types_folder,contracts_folder:typeof i.contracts_folder=="string"?i.contracts_folder:qr.settings.contracts_folder,explicit_type_keys:Array.isArray(i.explicit_type_keys)?i.explicit_type_keys.filter(o=>typeof o=="string"):[...qr.settings.explicit_type_keys],...typeof i.default_strict=="boolean"?{default_strict:i.default_strict}:{},...typeof i.include_subfolders=="boolean"?{include_subfolders:i.include_subfolders}:{},exclude:Array.isArray(i.exclude)?i.exclude.filter(o=>typeof o=="string"):Cp(n.spec_version)?[]:[...mR]}}}catch{return null}}async function $o(r,e={}){let t=[];if(!(r.getAbstractFileByPath("mdbase.yaml")instanceof oe.TFile)){let l=(0,oe.stringifyYaml)(qr).trimEnd()+` -`;await r.create("mdbase.yaml",l),t.push("mdbase.yaml")}let i=await ai(r)??qr,s=i.settings.types_folder;await r.adapter.exists(s)||(await r.createFolder(s),t.push(s));let a=(0,oe.normalizePath)(`${s}/note.md`);if(!await r.adapter.exists(a)&&e.seedNoteType!==!1){let l=Tp("note",void 0,i.spec_version);await r.create(a,l),t.push(a)}return{created:t}}function aw(r,e){let t=W(r)?r:{},n=Array.isArray(t.type)?t.type.find(s=>s!=="null"):t.type,i={required:e};return Array.isArray(t.enum)?(i.type="enum",i.values=Oe(t.enum)):n==="array"?(i.type="list",i.items=aw(t.items,!1)):n==="object"?(i.type="object",i.fields=gn(t)):n==="string"&&t.format==="date"?i.type="date":n==="string"&&t.format==="date-time"?i.type="datetime":n==="string"&&t.format==="time"?i.type="time":typeof n=="string"?i.type=n:i.type="any",t.default!==void 0&&(i.default=Oe(t.default)),typeof t.description=="string"&&(i.description=t.description),typeof t.minimum=="number"&&(i.min=t.minimum),typeof t.maximum=="number"&&(i.max=t.maximum),typeof t.minLength=="number"&&(i.min_length=t.minLength),typeof t.maxLength=="number"&&(i.max_length=t.maxLength),typeof t.pattern=="string"&&(i.pattern=t.pattern),typeof t.minItems=="number"&&(i.min_length=t.minItems),typeof t.maxItems=="number"&&(i.max_length=t.maxItems),i}function gn(r){let e=W(r.properties)?r.properties:{},t=new Set(Array.isArray(r.required)?r.required.filter(n=>typeof n=="string"):[]);return Object.fromEntries(Object.entries(e).map(([n,i])=>[n,aw(i,t.has(n))]))}function cw(r,e){let t={...Oe(e)},n=r.type??"string",i=()=>{delete t.properties,delete t.required,delete t.additionalProperties},s=()=>{delete t.items};if(n==="enum")delete t.type,t.enum=Oe(r.values??[]),delete t.format,i(),s();else if(n==="list")t.type="array",delete t.enum,delete t.format,i(),t.items=cw(r.items??{type:"any"},W(t.items)?t.items:{});else if(n==="object"){t.type="object",delete t.enum,delete t.format,s();let c=es(r.fields??{},W(t)?t:{},!1);t.properties=c.properties,c.required?t.required=c.required:delete t.required}else n==="link"?(t.type="string",delete t.enum,delete t.format,i(),s()):["date","datetime","time"].includes(n)?(t.type="string",t.format=n==="datetime"?"date-time":n,delete t.enum,i(),s()):["string","integer","number","boolean"].includes(n)?(t.type=n,delete t.format,delete t.enum,i(),s()):(delete t.type,delete t.enum,delete t.format,i(),s());r.default!==void 0?t.default=Oe(r.default):delete t.default,typeof r.description=="string"&&r.description.trim()?t.description=r.description:delete t.description;let o=n==="integer"||n==="number";o&&typeof r.min=="number"?t.minimum=r.min:delete t.minimum,o&&typeof r.max=="number"?t.maximum=r.max:delete t.maximum;let a=["string","link","date","datetime","time"].includes(n);return n==="list"&&typeof r.min_length=="number"?t.minItems=r.min_length:delete t.minItems,n==="list"&&typeof r.max_length=="number"?t.maxItems=r.max_length:delete t.maxItems,a&&typeof r.min_length=="number"?t.minLength=r.min_length:delete t.minLength,a&&typeof r.max_length=="number"?t.maxLength=r.max_length:delete t.maxLength,a&&typeof r.pattern=="string"?t.pattern=r.pattern:delete t.pattern,t}function es(r,e={},t=!1){let n=W(e.properties)?e.properties:{},i=Object.create(null),s=[];for(let[a,c]of Object.entries(r))i[a]=cw(c,W(n[a])?n[a]:{}),c.required===!0&&s.push(a);let o={...Oe(e),type:"object",properties:i,additionalProperties:!t};return s.length>0?o.required=s:delete o.required,o}function lw(r,e){if(!e)return r;if(!e.startsWith("/"))return;let t=r;for(let n of e.slice(1).split("/")){let i=n.replace(/~1/g,"/").replace(/~0/g,"~");if(Array.isArray(t)){let s=Number(i);if(!Number.isInteger(s)||s<0||s>=t.length)return;t=t[s]}else if(W(t)&&i in t)t=t[i];else return}return t}async function dw(r,e,t){let[n,i=""]=t.split("#",2);if(!n||/^[a-z][a-z0-9+.-]*:/i.test(n)||n.startsWith("/"))return null;let s=nw(e),o=[];for(let l of`${s}/${n}`.replace(/\\/g,"/").split("/"))if(!(!l||l==="."))if(l===".."){if(o.length===0)return null;o.pop()}else o.push(l);let a=(0,oe.normalizePath)(o.join("/")),c=r.getAbstractFileByPath(a);if(!(c instanceof oe.TFile))return null;try{let l=JSON.parse(await r.cachedRead(c)),u=lw(l,i);return W(u)?u:null}catch{return null}}function wc(r,e,t){let n=W(r.collection)?Oe(r.collection):void 0,i=gn(t);for(let s of n?.unique??[])typeof s.field=="string"&&i[s.field]&&(i[s.field].unique=!0,i[s.field].unique_scope=s.scope);for(let[s,o]of Object.entries(n?.links??{}))i[s]&&(i[s].target=o.target_type,i[s].validate_exists=o.validate_exists);return{name:String(r.name),version:typeof r.version=="number"?r.version:void 0,description:typeof r.description=="string"?r.description:void 0,display_name_key:n?.display?.name_field,path_pattern:n?.path?.pattern,strict:t.additionalProperties===!1,match:W(r.match)?r.match:void 0,fields:i,filePath:e,specProfile:"v0.3",schema:Oe(t),collection:n,originalFrontmatter:Oe(r)}}async function Ep(r,e){let t=[];for(let n of r.getMarkdownFiles()){if(yt(n.path,e))continue;let i=Me(await r.cachedRead(n));i.error||t.push({path:n.path,frontmatter:i.frontmatter})}return t}function ts(r,e,t){let n=[];return hw(r,e,t,n),n}async function Ap(r,e){let t=new Map,n=`${(0,oe.normalizePath)(e.settings.types_folder)}/`;for(let i of r.getMarkdownFiles()){if(!i.path.startsWith(n))continue;let s=await r.cachedRead(i),o=Me(s);if(!o.hasFrontmatter||o.error)continue;let a=o.frontmatter;if(e.spec_version.startsWith("0.3.")){if(a.kind!=="mdbase.type"||typeof a.name!="string"||!W(a.schema))continue;let u=a.schema,d=W(u.value)?u.value:null;if(!d&&typeof u.ref=="string"&&(d=await dw(r,i.path,u.ref)),!d)continue;t.set(a.name,wc(a,i.path,d));continue}if(!W(a.fields))continue;let c=typeof a.name=="string"&&a.name.trim().length>0?a.name.trim():i.basename,l={};for(let[u,d]of Object.entries(a.fields))W(d)&&(l[u]=d);t.set(c,{name:c,extends:typeof a.extends=="string"?a.extends:void 0,display_name_key:typeof a.display_name_key=="string"?a.display_name_key:void 0,path_pattern:typeof a.path_pattern=="string"?a.path_pattern:void 0,filename_pattern:typeof a.filename_pattern=="string"?a.filename_pattern:void 0,strict:gR(a.strict),match:W(a.match)?a.match:void 0,fields:l,filePath:i.path,specProfile:"v0.2",originalFrontmatter:Oe(a)})}return vR(t)}async function kp(r,e){let t=new Map,n=`${(0,oe.normalizePath)(e.settings.contracts_folder||"_contracts")}/`;for(let i of r.getMarkdownFiles()){if(!i.path.startsWith(n))continue;let s=Me(await r.cachedRead(i));if(!s.hasFrontmatter||s.error)continue;let o=s.frontmatter;if(o.kind!=="mdbase.contract"||o.contract_type!=="record"||typeof o.id!="string"||typeof o.version!="string")continue;let a=W(o.record_schema)?o.record_schema:{},c=W(o.binding_schema)?o.binding_schema:void 0,l=await ew(r,i.path,a);if(!l)continue;let u=c?await ew(r,i.path,c):null,d=`${o.id}@${o.version}`;t.set(d,{contract_type:"record",id:o.id,version:o.version,digest:typeof o.digest=="string"?o.digest:"",schema:l,...u?{binding_schema:u}:{},implementations:[]})}return t}async function ew(r,e,t){return W(t.value)?Oe(t.value):typeof t.ref!="string"?null:dw(r,e,t.ref)}function _R(r,e){for(let t of e){let n=r[t];if(Array.isArray(n))return n.filter(s=>typeof s=="string")}for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim().length>0)return[n.trim()]}return null}function Pp(r,e){return r.replace(/\{([^}]+)\}/g,(t,n)=>{let i=e[n];return i==null?"":Array.isArray(i)?i.filter(s=>["string","number","boolean"].includes(typeof s)).map(String).join("-"):typeof i=="string"?i:typeof i=="number"||typeof i=="boolean"?String(i):""})}function yn(r){let e=r.replace(/\\/g,"/");if(!e||e.startsWith("/")||/^[A-Za-z]:\//.test(e)||e.includes("\0"))throw new So("invalid_path",`Invalid collection-relative path: ${r}`);let t=e.split("/");if(t.includes(".."))throw new So("path_traversal",`Path escapes the collection root: ${r}`);return(0,oe.normalizePath)(t.filter(n=>n&&n!==".").join("/"))}function SR(r){let e=r.search(/[*?]|\[/),n=(e===-1?r:r.slice(0,e)).replace(/\/+$/,"");if(n.endsWith(".md")){let i=n.lastIndexOf("/");return i>=0?n.slice(0,i):""}return n}function uw(r,e){if(r.path_pattern){let t=(0,oe.normalizePath)(Pp(r.path_pattern,e));if(t.endsWith(".md")){let n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}return t.replace(/\/+$/,"")}return r.match?.path_glob?SR(r.match.path_glob):""}function fw(r,e){let t=r.display_name_key??"title",n=e[t],i=`${r.name}-${new Date().toISOString().slice(0,10)}`,s=typeof n=="string"&&n.trim().length>0?n:i;if(r.filename_pattern&&r.filename_pattern.trim().length>0){let o=(0,oe.normalizePath)(Pp(r.filename_pattern,e)),c=(o.split("/").pop()??o).replace(/\.md$/i,"").trim();if(c.length>0)return`${$p(c)}.md`}return`${$p(s)}.md`}function Zi(r){return Array.isArray(r)?`[${r.map(Zi).join(",")}]`:W(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${Zi(r[e])}`).join(",")}}`:JSON.stringify(r)}function $R(r,e){let t=[r];for(let n of e.split(".").filter(Boolean)){let i=n.endsWith("[]"),s=i?n.slice(0,-2):n,o=[];for(let a of t){if(!W(a)||!Object.prototype.hasOwnProperty.call(a,s))continue;let c=a[s];i&&Array.isArray(c)?o.push(...c):i||o.push(c)}if(!o.length)return{present:!1,value:void 0};t=o}return{present:!0,value:t[0]}}function gc(r,e,t){return(typeof r=="number"&&typeof e=="number"&&Number.isFinite(r)&&Number.isFinite(e)||typeof r=="string"&&typeof e=="string")&&t(r,e)}function xR(r,e,t,n){let i=(s,o)=>Zi(s)===Zi(o);switch(e){case"eq":case"const":return r.present&&r.value!=null&&i(r.value,t);case"neq":return r.present&&r.value!=null&&!i(r.value,t);case"gt":return gc(r.value,t,(s,o)=>s>o);case"gte":return gc(r.value,t,(s,o)=>s>=o);case"lt":return gc(r.value,t,(s,o)=>ss<=o);case"exists":return n.startsWith("0.3.")?t===!0?r.present:!r.present:t===!0?r.present&&r.value!=null:!r.present||r.value==null;case"contains":return Array.isArray(r.value)?r.value.some(s=>i(s,t)):typeof r.value=="string"&&r.value.includes(String(t));case"containsAll":return!Array.isArray(r.value)||!Array.isArray(t)?!1:t.every(s=>r.value.some(o=>i(o,s)));case"containsAny":return!Array.isArray(r.value)||!Array.isArray(t)?!1:t.some(s=>r.value.some(o=>i(o,s)));case"in":return r.value!=null&&Array.isArray(t)&&t.some(s=>i(s,r.value));case"startsWith":case"starts_with":return typeof r.value=="string"&&typeof t=="string"&&r.value.startsWith(t);case"endsWith":case"ends_with":return typeof r.value=="string"&&typeof t=="string"&&r.value.endsWith(t);case"matches":try{return typeof r.value=="string"&&typeof t=="string"&&new RegExp(t.replace(/\\\\/g,"\\")).test(r.value)}catch{return!1}default:return!1}}function vc(r,e,t){if("and"in r)return Array.isArray(r.and)&&r.and.every(n=>W(n)&&vc(n,e,t));if("or"in r)return Array.isArray(r.or)&&r.or.some(n=>W(n)&&vc(n,e,t));if("not"in r)return W(r.not)&&!vc(r.not,e,t);for(let[n,i]of Object.entries(r)){let s=$R(e,n);if(!W(i)){if(!s.present||Zi(s.value)!==Zi(i))return!1;continue}for(let[o,a]of Object.entries(i))if(!xR(s,o,a,t))return!1}return!0}function Ke(r,e,t,n){let i=_R(e,t.settings.explicit_type_keys);if(i)return i;let s=[];for(let[o,a]of n.entries()){let c=a.match;if(!c)continue;let l=!0;if(typeof c.path_glob=="string"&&!FR(c.path_glob,r,t)&&(l=!1),l&&Array.isArray(c.fields_present)){for(let u of c.fields_present)if(!(u in e)){l=!1;break}}l&&W(c.where)&&(l=vc(c.where,e,t.spec_version)),l&&typeof c.where=="string"&&(l=!1),l&&s.push(o)}return s}function pw(r){return r==null||typeof r=="string"&&r.trim().length===0}function ER(r){return/^\d{4}-\d{2}-\d{2}$/.test(r)}function AR(r){return/^\d{2}:\d{2}(:\d{2})?$/.test(r)}function kR(r){return typeof r=="string"||Array.isArray(r)?r.length:null}function Ce(r,e,t,n,i,s){r.push({path:e,code:n,message:i,severity:t,field:s})}function jt(r,e,t,n,i){typeof r=="number"&&(typeof e.min=="number"&&re.max&&Ce(i,n,"error","above_max",`'${t}' is ${r}; must be at most ${e.max}`,t));let s=kR(r);if(s!=null&&(typeof e.min_length=="number"&&se.max_length&&Ce(i,n,"error","above_max_length",`'${t}' has length ${s}; limit is ${e.max_length}`,t)),typeof e.pattern=="string"&&typeof r=="string")try{new RegExp(e.pattern).test(r)||Ce(i,n,"error","pattern_mismatch",`'${t}' is ${_p(r)}; does not match /${e.pattern}/`,t)}catch(o){Ce(i,n,"warn","invalid_pattern",`Field '${t}' has invalid regex pattern: ${o instanceof Error?o.message:String(o)}`,t)}}function wp(r,e,t,n,i,s){let o=e.type??"any";if(r==null)return;e.deprecated===!0&&Ce(i,n,"warn","deprecated_field",`Field '${t}' is marked deprecated`,t);let a=c=>{Ce(i,n,"error","invalid_type",`Field '${t}' expected ${c}`,t)};switch(o){case"any":jt(r,e,t,n,i);return;case"string":if(typeof r!="string"){a("a string");return}jt(r,e,t,n,i);return;case"integer":if(typeof r!="number"||!Number.isInteger(r)){a("an integer");return}jt(r,e,t,n,i);return;case"number":if(typeof r!="number"||Number.isNaN(r)){a("a number");return}jt(r,e,t,n,i);return;case"boolean":typeof r!="boolean"&&a("a boolean");return;case"date":if(typeof r!="string"||!ER(r)){a("a date (YYYY-MM-DD)");return}jt(r,e,t,n,i);return;case"datetime":if(typeof r!="string"||Number.isNaN(Date.parse(r))){a("a datetime string");return}jt(r,e,t,n,i);return;case"time":if(typeof r!="string"||!AR(r)){a("a time string (HH:MM)");return}jt(r,e,t,n,i);return;case"enum":{let c=Array.isArray(e.values)?e.values:[];if(!c.includes(r)){Ce(i,n,"error","invalid_enum",`Field '${t}' must be one of: ${c.map(l=>String(l)).join(", ")}`,t);return}jt(r,e,t,n,i);return}case"list":{if(!Array.isArray(r)){a("a list");return}jt(r,e,t,n,i),e.items&&r.forEach((c,l)=>{wp(c,e.items,`${t}[${l}]`,n,i,s)});return}case"object":{if(!W(r)){a("an object");return}if(e.fields&&W(e.fields))for(let[c,l]of Object.entries(e.fields)){if(!W(l))continue;let u=l,d=`${t}.${c}`,f=r[c];if(u.required&&pw(f)){Ce(i,n,"error","missing_required",`Missing required field '${d}'`,d);continue}wp(f,u,d,n,i,s)}return}case"link":{if(typeof r!="string"&&!W(r)){a("a link string");return}if(e.validate_exists===!0&&s){let c=typeof r=="string"?r:typeof r.path=="string"?r.path:typeof r.file=="string"?r.file:"";(!c||!wR(s,n,c))&&Ce(i,n,"error","missing_link_target",`Field '${t}' references a missing note`,t)}return}case"tags":if(typeof r=="string"){jt(r,e,t,n,i);return}if(Array.isArray(r)&&r.every(c=>typeof c=="string")){jt(r,e,t,n,i);return}a("a tag string or list of strings");return;default:jt(r,e,t,n,i);return}}function PR(r){return r.replace(/^\//,"").split("/").filter(Boolean).map(t=>t.replace(/~1/g,"/").replace(/~0/g,"~")).join(".")||void 0}function CR(r){return r.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function _p(r){return r===null?"empty":typeof r=="string"?r.trim()?`'${r.length>40?`${r.slice(0,39)}\u2026`:r}'`:"empty":typeof r=="number"||typeof r=="boolean"?String(r):Array.isArray(r)?`a list of ${r.length}`:W(r)?"an object":r===void 0?"missing":JSON.stringify(r)??"unknown"}function bc(r,e){return`${r} ${e}${r===1?"":"s"}`}function RR(r,e,t,n){let i=r.params,s=e?`'${e}'`:"This note",o=_p(t);switch(r.keyword){case"required":return`Missing required field '${e??String(i.missingProperty)}'`;case"additionalProperties":return`Field '${e??String(i.additionalProperty)}' is not declared by type '${n}'`;case"type":{let c=(Array.isArray(i.type)?i.type.join(","):typeof i.type=="string"?i.type:"").split(",").map(l=>MR[l]??l).join(" or ");return`${s} is ${o}; expected ${c}`}case"enum":{let a=Array.isArray(i.allowedValues)?i.allowedValues.map(l=>String(l)):[],c=a.length>6?`${a.slice(0,6).join(", ")}, \u2026`:a.join(", ");return`${s} is ${o}; expected one of ${c}`}case"const":return`${s} is ${o}; expected ${_p(i.allowedValue)}`;case"maximum":return`${s} is ${o}; must be at most ${String(i.limit)}`;case"minimum":return`${s} is ${o}; must be at least ${String(i.limit)}`;case"exclusiveMaximum":return`${s} is ${o}; must be less than ${String(i.limit)}`;case"exclusiveMinimum":return`${s} is ${o}; must be more than ${String(i.limit)}`;case"maxLength":return`${s} is ${bc(typeof t=="string"?t.length:0,"character")}; limit is ${String(i.limit)}`;case"minLength":return`${s} is ${bc(typeof t=="string"?t.length:0,"character")}; needs at least ${String(i.limit)}`;case"maxItems":return`${s} has ${bc(Array.isArray(t)?t.length:0,"item")}; limit is ${String(i.limit)}`;case"minItems":return`${s} has ${bc(Array.isArray(t)?t.length:0,"item")}; needs at least ${String(i.limit)}`;case"uniqueItems":return`${s} contains duplicate items`;case"pattern":return`${s} is ${o}; does not match ${String(i.pattern)}`;case"format":return`${s} is ${o}; expected ${TR[String(i.format)]??String(i.format)}`;default:return`${s}: ${r.message??"invalid value"}`}}function IR(r,e,t,n={}){let i=r.params,s=PR(r.instancePath),o=typeof i.missingProperty=="string"?i.missingProperty:typeof i.additionalProperty=="string"?i.additionalProperty:void 0,a=s&&o?`${s}.${o}`:o??s,c=r.keyword==="format"?"format_invalid":`schema_${CR(r.keyword)}`,l=lw(n,r.instancePath);return{path:e,code:c,message:RR(r,a,l,t),severity:"error",field:a,type:t,schema_location:`embedded://type/schema#${r.schemaPath}`,details:{instance_path:r.instancePath,schema_path:r.schemaPath,technical_message:`JSON Schema ${r.keyword} failed for type '${t}': ${r.message??"invalid value"}`,...o===void 0?{}:{property:o}}}}function Sp(r){if(Array.isArray(r)){for(let e of r){let t=Sp(e);if(t)return t}return null}if(!W(r))return null;if(typeof r.$ref=="string"&&!r.$ref.startsWith("#"))return r.$ref;for(let e of Object.values(r)){let t=Sp(e);if(t)return t}return null}function OR(r,e,t,n){if(!t.schema)return;let i=Sp(t.schema);if(i){n.push({path:r,code:/^[a-z][a-z0-9+.-]*:/i.test(i)?"schema_ref_forbidden":"unsupported_profile",message:`Unsupported JSON Schema reference '${i}' for type '${t.name}'`,severity:"error",type:t.name});return}try{let s=yR().compile(t.schema);if(s(e))return;for(let o of s.errors??[])n.push(IR(o,r,t.name,e))}catch(s){n.push({path:r,code:"invalid_embedded_schema",message:s instanceof Error?s.message:String(s),severity:"error",type:t.name})}}async function DR(r,e,t,n,i,s,o){for(let[a,c]of Object.entries(n.collection?.links??{})){let l=t[a],u=Array.isArray(l)?l:[l];for(let d of u){if(d==null||typeof d!="string")continue;let f=ow(r,e,d);if(!f&&c.validate_exists===!0){Ce(o,e,"error","link_not_found",`Field '${a}' references a missing note`,a);continue}if(f&&c.target_type&&c.target_type!=="any"){let p=Me(await r.cachedRead(f));Ke(f.path,p.frontmatter,i,s).includes(c.target_type)||Ce(o,e,"error","link_wrong_type",`Field '${a}' must reference type '${c.target_type}'`,a)}}}}function hw(r,e,t,n,i){if(t.specProfile==="v0.3"){OR(r,e,t,n);return}for(let[s,o]of Object.entries(t.fields)){if(!W(o))continue;let a=o,c=e[s];if(a.required&&pw(c)){Ce(n,r,"error","missing_required",`Missing required field '${s}' for type '${t.name}'`,s);continue}wp(c,a,s,r,n,i)}}function NR(r){let e=new Set;for(let t of r)for(let n of Object.keys(t.fields))e.add(n);return e}function LR(r,e){let t=!1,n=!1;for(let i of r){if(i.strict===!0)return!0;i.strict==="warn"&&(t=!0),i.strict===void 0&&(n=!0)}return t||n&&e.settings.default_strict?"warn":!1}function yt(r,e){let t=(0,oe.normalizePath)(r),n=(0,oe.normalizePath)(e.settings.types_folder);if(t.startsWith(`${n}/`)||t===n)return!0;if(Cp(e.spec_version)){let i=(0,oe.normalizePath)(e.settings.contracts_folder??"_contracts");return t===i||t.startsWith(`${i}/`)||t.split("/").some(s=>s.startsWith(".")||s==="node_modules")?!0:e.settings.exclude.some(s=>bp(s,t))}if(e.settings.include_subfolders===!1&&t.includes("/"))return!0;for(let i of e.settings.exclude)if((0,xp.default)(i,{dot:!0,matchBase:!i.includes("/")})(t)||!i.includes("*")&&!i.includes("?")&&!i.includes("/")&&t.startsWith(`${i}/`))return!0;return!1}function Cp(r){return typeof r=="string"&&r.startsWith("0.3.")}function FR(r,e,t){return Cp(t.spec_version)?bp(r,e):(0,xp.default)(r,{dot:!0})(e)}async function _c(r,e,t,n){if(yt(e.path,t))return[];let i=[],s=await r.cachedRead(e),o=Me(s);if(o.error)return Ce(i,e.path,"error","invalid_frontmatter",o.error),i;let a=o.frontmatter,c=Ke(e.path,a,t,n);if(c.length===0)return Ce(i,e.path,"warn","no_matching_type","No type could be resolved for this file"),i;let l=c.map(f=>n.get(f)).filter(f=>!!f),u=c.filter(f=>!n.has(f));if(u.length>0&&Ce(i,e.path,"error","unknown_type",`Resolved types are not defined: ${u.join(", ")}`),l.length===0)return i;for(let f of l)hw(e.path,a,f,i,r),f.specProfile==="v0.3"&&await DR(r,e.path,a,f,t,n,i);let d=t.spec_version.startsWith("0.3.")?!1:LR(l,t);if(d!==!1){let f=NR(l),p=new Set(t.settings.explicit_type_keys),m=d===!0?"error":"warn";for(let h of Object.keys(a))f.has(h)||p.has(h)||Ce(i,e.path,m,"unknown_field",`Unknown field '${h}' in strict mode`,h)}return i}async function jR(r,e,t,n={}){let i=new Map;for(let o of r.getMarkdownFiles()){if(yt(o.path,e))continue;n.signal?.throwIfAborted();let a=await r.cachedRead(o),c=Me(a);if(c.error)continue;let u=Ke(o.path,c.frontmatter,e,t).map(d=>t.get(d)).filter(d=>!!d);for(let d of u)for(let[f,p]of Object.entries(d.fields)){if(!W(p))continue;let m=p;if(m.unique!==!0)continue;let h=c.frontmatter[f];if(h==null)continue;let y=vp(h),g=m.unique_scope==="collection"?"collection":"type",b=`${g==="collection"?"*":d.name}::${f}::${y}`,v=i.get(b)??[];v.some(S=>S.path===o.path)||(v.push({path:o.path,typeName:d.name,fieldName:f,scope:g,specProfile:d.specProfile,value:h,fingerprint:y}),i.set(b,v))}}let s=[];for(let o of i.values())if(!(o.length<=1))for(let a of o){let c=o.filter(l=>l.path!==a.path).map(l=>l.path).join(", ");Ce(s,a.path,"error",a.specProfile==="v0.3"?"duplicate_value":"duplicate_unique",a.scope==="collection"?`Field '${a.fieldName}' must be unique across the collection. Duplicate found in: ${c}`:`Field '${a.fieldName}' must be unique for type '${a.typeName}'. Duplicate found in: ${c}`,a.fieldName)}return s}function qR(r,e){let t=Oe(r);for(let n of e)for(let[i,s]of Object.entries(n.collection?.read_defaults??{}))i in t||(t[i]=Oe(s));return t}async function Mp(r,e,t,n={}){let i=[],s=r.getMarkdownFiles().filter(a=>!yt(a.path,e));n.onProgress?.({completed:0,total:s.length,phase:"notes"});for(let[a,c]of s.entries()){n.signal?.throwIfAborted();let l=await _c(r,c,e,t);n.signal?.throwIfAborted(),n.onFile?.(c,l),i.push(...l),n.onProgress?.({completed:a+1,total:s.length,phase:"notes"}),a%25===0&&await new Promise(u=>setTimeout(u,0))}n.signal?.throwIfAborted(),n.onProgress?.({completed:s.length,total:s.length,phase:"uniqueness"});let o=await jR(r,e,t,n);return n.signal?.throwIfAborted(),i.push(...o),i}function Tp(r,e,t=qr.spec_version){if(t.startsWith("0.3.")){let i={kind:"mdbase.type",name:r,version:1,description:`${r} type`,schema:{dialect:"json-schema-2020-12",value:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",required:["title"],additionalProperties:!0,properties:{title:{type:"string",minLength:1},tags:{type:"array",items:{type:"string"}}}}}};return e&&e.trim()&&(i.match={path_glob:e.trim()}),`${mt(i,`# ${r} +${n}`}async function ai(r){let e=r.getAbstractFileByPath("mdbase.yaml");if(!(e instanceof oe.TFile))return null;try{let t=await r.cachedRead(e),n=(0,oe.parseYaml)(t);if(!K(n))return null;let i=K(n.settings)?n.settings:{},s=K(n.runtime)?n.runtime:void 0;return{spec_version:typeof n.spec_version=="string"?n.spec_version:jr.spec_version,name:typeof n.name=="string"?n.name:jr.name,description:typeof n.description=="string"?n.description:jr.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:jr.settings.types_folder,contracts_folder:typeof i.contracts_folder=="string"?i.contracts_folder:jr.settings.contracts_folder,explicit_type_keys:Array.isArray(i.explicit_type_keys)?i.explicit_type_keys.filter(o=>typeof o=="string"):[...jr.settings.explicit_type_keys],...typeof i.default_strict=="boolean"?{default_strict:i.default_strict}:{},...typeof i.include_subfolders=="boolean"?{include_subfolders:i.include_subfolders}:{},exclude:Array.isArray(i.exclude)?i.exclude.filter(o=>typeof o=="string"):Tp(n.spec_version)?[]:[...gR]}}}catch{return null}}async function $o(r,e={}){let t=[];if(!(r.getAbstractFileByPath("mdbase.yaml")instanceof oe.TFile)){let l=(0,oe.stringifyYaml)(jr).trimEnd()+` +`;await r.create("mdbase.yaml",l),t.push("mdbase.yaml")}let i=await ai(r)??jr,s=i.settings.types_folder;await r.adapter.exists(s)||(await r.createFolder(s),t.push(s));let a=(0,oe.normalizePath)(`${s}/note.md`);if(!await r.adapter.exists(a)&&e.seedNoteType!==!1){let l=Ip("note",void 0,i.spec_version);await r.create(a,l),t.push(a)}return{created:t}}function dw(r,e){let t=K(r)?r:{},n=Array.isArray(t.type)?t.type.find(s=>s!=="null"):t.type,i={required:e};return Array.isArray(t.enum)?(i.type="enum",i.values=De(t.enum)):n==="array"?(i.type="list",i.items=dw(t.items,!1)):n==="object"?(i.type="object",i.fields=gn(t)):n==="string"&&t.format==="date"?i.type="date":n==="string"&&t.format==="date-time"?i.type="datetime":n==="string"&&t.format==="time"?i.type="time":typeof n=="string"?i.type=n:i.type="any",t.default!==void 0&&(i.default=De(t.default)),typeof t.description=="string"&&(i.description=t.description),typeof t.minimum=="number"&&(i.min=t.minimum),typeof t.maximum=="number"&&(i.max=t.maximum),typeof t.minLength=="number"&&(i.min_length=t.minLength),typeof t.maxLength=="number"&&(i.max_length=t.maxLength),typeof t.pattern=="string"&&(i.pattern=t.pattern),typeof t.minItems=="number"&&(i.min_length=t.minItems),typeof t.maxItems=="number"&&(i.max_length=t.maxItems),i}function gn(r){let e=K(r.properties)?r.properties:{},t=new Set(Array.isArray(r.required)?r.required.filter(n=>typeof n=="string"):[]);return Object.fromEntries(Object.entries(e).map(([n,i])=>[n,dw(i,t.has(n))]))}function uw(r,e){let t={...De(e)},n=r.type??"string",i=()=>{delete t.properties,delete t.required,delete t.additionalProperties},s=()=>{delete t.items};if(n==="enum")delete t.type,t.enum=De(r.values??[]),delete t.format,i(),s();else if(n==="list")t.type="array",delete t.enum,delete t.format,i(),t.items=uw(r.items??{type:"any"},K(t.items)?t.items:{});else if(n==="object"){t.type="object",delete t.enum,delete t.format,s();let c=es(r.fields??{},K(t)?t:{},!1);t.properties=c.properties,c.required?t.required=c.required:delete t.required}else n==="link"?(t.type="string",delete t.enum,delete t.format,i(),s()):["date","datetime","time"].includes(n)?(t.type="string",t.format=n==="datetime"?"date-time":n,delete t.enum,i(),s()):["string","integer","number","boolean"].includes(n)?(t.type=n,delete t.format,delete t.enum,i(),s()):(delete t.type,delete t.enum,delete t.format,i(),s());r.default!==void 0?t.default=De(r.default):delete t.default,typeof r.description=="string"&&r.description.trim()?t.description=r.description:delete t.description;let o=n==="integer"||n==="number";o&&typeof r.min=="number"?t.minimum=r.min:delete t.minimum,o&&typeof r.max=="number"?t.maximum=r.max:delete t.maximum;let a=["string","link","date","datetime","time"].includes(n);return n==="list"&&typeof r.min_length=="number"?t.minItems=r.min_length:delete t.minItems,n==="list"&&typeof r.max_length=="number"?t.maxItems=r.max_length:delete t.maxItems,a&&typeof r.min_length=="number"?t.minLength=r.min_length:delete t.minLength,a&&typeof r.max_length=="number"?t.maxLength=r.max_length:delete t.maxLength,a&&typeof r.pattern=="string"?t.pattern=r.pattern:delete t.pattern,t}function es(r,e={},t=!1){let n=K(e.properties)?e.properties:{},i=Object.create(null),s=[];for(let[a,c]of Object.entries(r))i[a]=uw(c,K(n[a])?n[a]:{}),c.required===!0&&s.push(a);let o={...De(e),type:"object",properties:i,additionalProperties:!t};return s.length>0?o.required=s:delete o.required,o}function fw(r,e){if(!e)return r;if(!e.startsWith("/"))return;let t=r;for(let n of e.slice(1).split("/")){let i=n.replace(/~1/g,"/").replace(/~0/g,"~");if(Array.isArray(t)){let s=Number(i);if(!Number.isInteger(s)||s<0||s>=t.length)return;t=t[s]}else if(K(t)&&i in t)t=t[i];else return}return t}async function pw(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=ow(e),o=[];for(let l of`${s}/${n}`.replace(/\\/g,"/").split("/"))if(!(!l||l==="."))if(l===".."){if(o.length===0)return null;o.pop()}else o.push(l);let a=(0,oe.normalizePath)(o.join("/")),c=r.getAbstractFileByPath(a);if(!(c instanceof oe.TFile))return null;try{let l=JSON.parse(await r.cachedRead(c)),u=fw(l,i);return K(u)?u:null}catch{return null}}function _c(r,e,t){let n=K(r.collection)?De(r.collection):void 0,i=gn(t);for(let s of n?.unique??[])typeof s.field=="string"&&i[s.field]&&(i[s.field].unique=!0,i[s.field].unique_scope=s.scope);for(let[s,o]of Object.entries(n?.links??{}))i[s]&&(i[s].target=o.target_type,i[s].validate_exists=o.validate_exists);return{name:String(r.name),version:typeof r.version=="number"?r.version:void 0,description:typeof r.description=="string"?r.description:void 0,display_name_key:n?.display?.name_field,path_pattern:n?.path?.pattern,strict:t.additionalProperties===!1,match:K(r.match)?r.match:void 0,fields:i,filePath:e,specProfile:"v0.3",schema:De(t),collection:n,originalFrontmatter:De(r)}}async function kp(r,e){let t=[],n=performance.now();for(let i of r.getMarkdownFiles()){if(performance.now()-n>=8&&(await new Promise(o=>setTimeout(o,0)),n=performance.now()),yt(i.path,e))continue;let s=Ce(await r.cachedRead(i));s.error||t.push({path:i.path,frontmatter:s.frontmatter})}return t}function ts(r,e,t){let n=[];return gw(r,e,t,n),n}async function Pp(r,e){let t=new Map,n=`${(0,oe.normalizePath)(e.settings.types_folder)}/`;for(let i of r.getMarkdownFiles()){if(!i.path.startsWith(n))continue;let s=await r.cachedRead(i),o=Ce(s);if(!o.hasFrontmatter||o.error)continue;let a=o.frontmatter;if(e.spec_version.startsWith("0.3.")){if(a.kind!=="mdbase.type"||typeof a.name!="string"||!K(a.schema))continue;let u=a.schema,d=K(u.value)?u.value:null;if(!d&&typeof u.ref=="string"&&(d=await pw(r,i.path,u.ref)),!d)continue;t.set(a.name,_c(a,i.path,d));continue}if(!K(a.fields))continue;let c=typeof a.name=="string"&&a.name.trim().length>0?a.name.trim():i.basename,l={};for(let[u,d]of Object.entries(a.fields))K(d)&&(l[u]=d);t.set(c,{name:c,extends:typeof a.extends=="string"?a.extends:void 0,display_name_key:typeof a.display_name_key=="string"?a.display_name_key:void 0,path_pattern:typeof a.path_pattern=="string"?a.path_pattern:void 0,filename_pattern:typeof a.filename_pattern=="string"?a.filename_pattern:void 0,strict:vR(a.strict),match:K(a.match)?a.match:void 0,fields:l,filePath:i.path,specProfile:"v0.2",originalFrontmatter:De(a)})}return _R(t)}async function Mp(r,e){let t=new Map,n=`${(0,oe.normalizePath)(e.settings.contracts_folder||"_contracts")}/`;for(let i of r.getMarkdownFiles()){if(!i.path.startsWith(n))continue;let s=Ce(await r.cachedRead(i));if(!s.hasFrontmatter||s.error)continue;let o=s.frontmatter;if(o.kind!=="mdbase.contract"||o.contract_type!=="record"||typeof o.id!="string"||typeof o.version!="string")continue;let a=K(o.record_schema)?o.record_schema:{},c=K(o.binding_schema)?o.binding_schema:void 0,l=await nw(r,i.path,a);if(!l)continue;let u=c?await nw(r,i.path,c):null,d=`${o.id}@${o.version}`;t.set(d,{contract_type:"record",id:o.id,version:o.version,digest:typeof o.digest=="string"?o.digest:"",schema:l,...u?{binding_schema:u}:{},implementations:[]})}return t}async function nw(r,e,t){return K(t.value)?De(t.value):typeof t.ref!="string"?null:pw(r,e,t.ref)}function xR(r,e){for(let t of e){let n=r[t];if(Array.isArray(n))return n.filter(s=>typeof s=="string")}for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim().length>0)return[n.trim()]}return null}function Cp(r,e){return r.replace(/\{([^}]+)\}/g,(t,n)=>{let i=e[n];return i==null?"":Array.isArray(i)?i.filter(s=>["string","number","boolean"].includes(typeof s)).map(String).join("-"):typeof i=="string"?i:typeof i=="number"||typeof i=="boolean"?String(i):""})}function yn(r){let e=r.replace(/\\/g,"/");if(!e||e.startsWith("/")||/^[A-Za-z]:\//.test(e)||e.includes("\0"))throw new xo("invalid_path",`Invalid collection-relative path: ${r}`);let t=e.split("/");if(t.includes(".."))throw new xo("path_traversal",`Path escapes the collection root: ${r}`);return(0,oe.normalizePath)(t.filter(n=>n&&n!==".").join("/"))}function $R(r){let e=r.search(/[*?]|\[/),n=(e===-1?r:r.slice(0,e)).replace(/\/+$/,"");if(n.endsWith(".md")){let i=n.lastIndexOf("/");return i>=0?n.slice(0,i):""}return n}function hw(r,e){if(r.path_pattern){let t=(0,oe.normalizePath)(Cp(r.path_pattern,e));if(t.endsWith(".md")){let n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}return t.replace(/\/+$/,"")}return r.match?.path_glob?$R(r.match.path_glob):""}function mw(r,e){let t=r.display_name_key??"title",n=e[t],i=`${r.name}-${new Date().toISOString().slice(0,10)}`,s=typeof n=="string"&&n.trim().length>0?n:i;if(r.filename_pattern&&r.filename_pattern.trim().length>0){let o=(0,oe.normalizePath)(Cp(r.filename_pattern,e)),c=(o.split("/").pop()??o).replace(/\.md$/i,"").trim();if(c.length>0)return`${Ep(c)}.md`}return`${Ep(s)}.md`}function Zi(r){return Array.isArray(r)?`[${r.map(Zi).join(",")}]`:K(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${Zi(r[e])}`).join(",")}}`:JSON.stringify(r)}function ER(r,e){let t=[r];for(let n of e.split(".").filter(Boolean)){let i=n.endsWith("[]"),s=i?n.slice(0,-2):n,o=[];for(let a of t){if(!K(a)||!Object.prototype.hasOwnProperty.call(a,s))continue;let c=a[s];i&&Array.isArray(c)?o.push(...c):i||o.push(c)}if(!o.length)return{present:!1,value:void 0};t=o}return{present:!0,value:t[0]}}function bc(r,e,t){return(typeof r=="number"&&typeof e=="number"&&Number.isFinite(r)&&Number.isFinite(e)||typeof r=="string"&&typeof e=="string")&&t(r,e)}function AR(r,e,t,n){let i=(s,o)=>Zi(s)===Zi(o);switch(e){case"eq":case"const":return r.present&&r.value!=null&&i(r.value,t);case"neq":return r.present&&r.value!=null&&!i(r.value,t);case"gt":return bc(r.value,t,(s,o)=>s>o);case"gte":return bc(r.value,t,(s,o)=>s>=o);case"lt":return bc(r.value,t,(s,o)=>ss<=o);case"exists":return n.startsWith("0.3.")?t===!0?r.present:!r.present:t===!0?r.present&&r.value!=null:!r.present||r.value==null;case"contains":return Array.isArray(r.value)?r.value.some(s=>i(s,t)):typeof r.value=="string"&&r.value.includes(String(t));case"containsAll":return!Array.isArray(r.value)||!Array.isArray(t)?!1:t.every(s=>r.value.some(o=>i(o,s)));case"containsAny":return!Array.isArray(r.value)||!Array.isArray(t)?!1:t.some(s=>r.value.some(o=>i(o,s)));case"in":return r.value!=null&&Array.isArray(t)&&t.some(s=>i(s,r.value));case"startsWith":case"starts_with":return typeof r.value=="string"&&typeof t=="string"&&r.value.startsWith(t);case"endsWith":case"ends_with":return typeof r.value=="string"&&typeof t=="string"&&r.value.endsWith(t);case"matches":try{return typeof r.value=="string"&&typeof t=="string"&&new RegExp(t.replace(/\\\\/g,"\\")).test(r.value)}catch{return!1}default:return!1}}function wc(r,e,t){if("and"in r)return Array.isArray(r.and)&&r.and.every(n=>K(n)&&wc(n,e,t));if("or"in r)return Array.isArray(r.or)&&r.or.some(n=>K(n)&&wc(n,e,t));if("not"in r)return K(r.not)&&!wc(r.not,e,t);for(let[n,i]of Object.entries(r)){let s=ER(e,n);if(!K(i)){if(!s.present||Zi(s.value)!==Zi(i))return!1;continue}for(let[o,a]of Object.entries(i))if(!AR(s,o,a,t))return!1}return!0}function Ke(r,e,t,n){let i=xR(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"&&!qR(c.path_glob,r,t)&&(l=!1),l&&Array.isArray(c.fields_present)){for(let u of c.fields_present)if(!(u in e)){l=!1;break}}l&&K(c.where)&&(l=wc(c.where,e,t.spec_version)),l&&typeof c.where=="string"&&(l=!1),l&&s.push(o)}return s}function yw(r){return r==null||typeof r=="string"&&r.trim().length===0}function kR(r){return/^\d{4}-\d{2}-\d{2}$/.test(r)}function PR(r){return/^\d{2}:\d{2}(:\d{2})?$/.test(r)}function MR(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 jt(r,e,t,n,i){typeof r=="number"&&(typeof e.min=="number"&&re.max&&Me(i,n,"error","above_max",`'${t}' is ${r}; must be at most ${e.max}`,t));let s=MR(r);if(s!=null&&(typeof e.min_length=="number"&&se.max_length&&Me(i,n,"error","above_max_length",`'${t}' has length ${s}; limit is ${e.max_length}`,t)),typeof e.pattern=="string"&&typeof r=="string")try{new RegExp(e.pattern).test(r)||Me(i,n,"error","pattern_mismatch",`'${t}' is ${xp(r)}; does not match /${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 Sp(r,e,t,n,i,s){let o=e.type??"any";if(r==null)return;e.deprecated===!0&&Me(i,n,"warn","deprecated_field",`Field '${t}' is marked deprecated`,t);let a=c=>{Me(i,n,"error","invalid_type",`Field '${t}' expected ${c}`,t)};switch(o){case"any":jt(r,e,t,n,i);return;case"string":if(typeof r!="string"){a("a string");return}jt(r,e,t,n,i);return;case"integer":if(typeof r!="number"||!Number.isInteger(r)){a("an integer");return}jt(r,e,t,n,i);return;case"number":if(typeof r!="number"||Number.isNaN(r)){a("a number");return}jt(r,e,t,n,i);return;case"boolean":typeof r!="boolean"&&a("a boolean");return;case"date":if(typeof r!="string"||!kR(r)){a("a date (YYYY-MM-DD)");return}jt(r,e,t,n,i);return;case"datetime":if(typeof r!="string"||Number.isNaN(Date.parse(r))){a("a datetime string");return}jt(r,e,t,n,i);return;case"time":if(typeof r!="string"||!PR(r)){a("a time string (HH:MM)");return}jt(r,e,t,n,i);return;case"enum":{let c=Array.isArray(e.values)?e.values:[];if(!c.includes(r)){Me(i,n,"error","invalid_enum",`Field '${t}' must be one of: ${c.map(l=>String(l)).join(", ")}`,t);return}jt(r,e,t,n,i);return}case"list":{if(!Array.isArray(r)){a("a list");return}jt(r,e,t,n,i),e.items&&r.forEach((c,l)=>{Sp(c,e.items,`${t}[${l}]`,n,i,s)});return}case"object":{if(!K(r)){a("an object");return}if(e.fields&&K(e.fields))for(let[c,l]of Object.entries(e.fields)){if(!K(l))continue;let u=l,d=`${t}.${c}`,f=r[c];if(u.required&&yw(f)){Me(i,n,"error","missing_required",`Missing required field '${d}'`,d);continue}Sp(f,u,d,n,i,s)}return}case"link":{if(typeof r!="string"&&!K(r)){a("a link string");return}if(e.validate_exists===!0&&s){let c=typeof r=="string"?r:typeof r.path=="string"?r.path:typeof r.file=="string"?r.file:"";(!c||!SR(s,n,c))&&Me(i,n,"error","missing_link_target",`Field '${t}' references a missing note`,t)}return}case"tags":if(typeof r=="string"){jt(r,e,t,n,i);return}if(Array.isArray(r)&&r.every(c=>typeof c=="string")){jt(r,e,t,n,i);return}a("a tag string or list of strings");return;default:jt(r,e,t,n,i);return}}function CR(r){return r.replace(/^\//,"").split("/").filter(Boolean).map(t=>t.replace(/~1/g,"/").replace(/~0/g,"~")).join(".")||void 0}function TR(r){return r.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function xp(r){return r===null?"empty":typeof r=="string"?r.trim()?`'${r.length>40?`${r.slice(0,39)}\u2026`:r}'`:"empty":typeof r=="number"||typeof r=="boolean"?String(r):Array.isArray(r)?`a list of ${r.length}`:K(r)?"an object":r===void 0?"missing":JSON.stringify(r)??"unknown"}function vc(r,e){return`${r} ${e}${r===1?"":"s"}`}function OR(r,e,t,n){let i=r.params,s=e?`'${e}'`:"This note",o=xp(t);switch(r.keyword){case"required":return`Missing required field '${e??String(i.missingProperty)}'`;case"additionalProperties":return`Field '${e??String(i.additionalProperty)}' is not declared by type '${n}'`;case"type":{let c=(Array.isArray(i.type)?i.type.join(","):typeof i.type=="string"?i.type:"").split(",").map(l=>RR[l]??l).join(" or ");return`${s} is ${o}; expected ${c}`}case"enum":{let a=Array.isArray(i.allowedValues)?i.allowedValues.map(l=>String(l)):[],c=a.length>6?`${a.slice(0,6).join(", ")}, \u2026`:a.join(", ");return`${s} is ${o}; expected one of ${c}`}case"const":return`${s} is ${o}; expected ${xp(i.allowedValue)}`;case"maximum":return`${s} is ${o}; must be at most ${String(i.limit)}`;case"minimum":return`${s} is ${o}; must be at least ${String(i.limit)}`;case"exclusiveMaximum":return`${s} is ${o}; must be less than ${String(i.limit)}`;case"exclusiveMinimum":return`${s} is ${o}; must be more than ${String(i.limit)}`;case"maxLength":return`${s} is ${vc(typeof t=="string"?t.length:0,"character")}; limit is ${String(i.limit)}`;case"minLength":return`${s} is ${vc(typeof t=="string"?t.length:0,"character")}; needs at least ${String(i.limit)}`;case"maxItems":return`${s} has ${vc(Array.isArray(t)?t.length:0,"item")}; limit is ${String(i.limit)}`;case"minItems":return`${s} has ${vc(Array.isArray(t)?t.length:0,"item")}; needs at least ${String(i.limit)}`;case"uniqueItems":return`${s} contains duplicate items`;case"pattern":return`${s} is ${o}; does not match ${String(i.pattern)}`;case"format":return`${s} is ${o}; expected ${IR[String(i.format)]??String(i.format)}`;default:return`${s}: ${r.message??"invalid value"}`}}function DR(r,e,t,n={}){let i=r.params,s=CR(r.instancePath),o=typeof i.missingProperty=="string"?i.missingProperty:typeof i.additionalProperty=="string"?i.additionalProperty:void 0,a=s&&o?`${s}.${o}`:o??s,c=r.keyword==="format"?"format_invalid":`schema_${TR(r.keyword)}`,l=fw(n,r.instancePath);return{path:e,code:c,message:OR(r,a,l,t),severity:"error",field:a,type:t,schema_location:`embedded://type/schema#${r.schemaPath}`,details:{instance_path:r.instancePath,schema_path:r.schemaPath,technical_message:`JSON Schema ${r.keyword} failed for type '${t}': ${r.message??"invalid value"}`,...o===void 0?{}:{property:o}}}}function $p(r){if(Array.isArray(r)){for(let e of r){let t=$p(e);if(t)return t}return null}if(!K(r))return null;if(typeof r.$ref=="string"&&!r.$ref.startsWith("#"))return r.$ref;for(let e of Object.values(r)){let t=$p(e);if(t)return t}return null}function NR(r,e,t,n){if(!t.schema)return;let i=$p(t.schema);if(i){n.push({path:r,code:/^[a-z][a-z0-9+.-]*:/i.test(i)?"schema_ref_forbidden":"unsupported_profile",message:`Unsupported JSON Schema reference '${i}' for type '${t.name}'`,severity:"error",type:t.name});return}try{let s=bR().compile(t.schema);if(s(e))return;for(let o of s.errors??[])n.push(DR(o,r,t.name,e))}catch(s){n.push({path:r,code:"invalid_embedded_schema",message:s instanceof Error?s.message:String(s),severity:"error",type:t.name})}}async function LR(r,e,t,n,i,s,o){for(let[a,c]of Object.entries(n.collection?.links??{})){let l=t[a],u=Array.isArray(l)?l:[l];for(let d of u){if(d==null||typeof d!="string")continue;let f=lw(r,e,d);if(!f&&c.validate_exists===!0){Me(o,e,"error","link_not_found",`Field '${a}' references a missing note`,a);continue}if(f&&c.target_type&&c.target_type!=="any"){let p=Ce(await r.cachedRead(f));Ke(f.path,p.frontmatter,i,s).includes(c.target_type)||Me(o,e,"error","link_wrong_type",`Field '${a}' must reference type '${c.target_type}'`,a)}}}}function gw(r,e,t,n,i){if(t.specProfile==="v0.3"){NR(r,e,t,n);return}for(let[s,o]of Object.entries(t.fields)){if(!K(o))continue;let a=o,c=e[s];if(a.required&&yw(c)){Me(n,r,"error","missing_required",`Missing required field '${s}' for type '${t.name}'`,s);continue}Sp(c,a,s,r,n,i)}}function FR(r){let e=new Set;for(let t of r)for(let n of Object.keys(t.fields))e.add(n);return e}function jR(r,e){let t=!1,n=!1;for(let i of r){if(i.strict===!0)return!0;i.strict==="warn"&&(t=!0),i.strict===void 0&&(n=!0)}return t||n&&e.settings.default_strict?"warn":!1}function yt(r,e){let t=(0,oe.normalizePath)(r),n=(0,oe.normalizePath)(e.settings.types_folder);if(t.startsWith(`${n}/`)||t===n)return!0;if(Tp(e.spec_version)){let i=(0,oe.normalizePath)(e.settings.contracts_folder??"_contracts");return t===i||t.startsWith(`${i}/`)||t.split("/").some(s=>s.startsWith(".")||s==="node_modules")?!0:e.settings.exclude.some(s=>wp(s,t))}if(e.settings.include_subfolders===!1&&t.includes("/"))return!0;for(let i of e.settings.exclude)if((0,Ap.default)(i,{dot:!0,matchBase:!i.includes("/")})(t)||!i.includes("*")&&!i.includes("?")&&!i.includes("/")&&t.startsWith(`${i}/`))return!0;return!1}function Tp(r){return typeof r=="string"&&r.startsWith("0.3.")}function qR(r,e,t){return Tp(t.spec_version)?wp(r,e):(0,Ap.default)(r,{dot:!0})(e)}async function Sc(r,e,t,n){if(yt(e.path,t))return[];let i=[],s=await r.cachedRead(e),o=Ce(s);if(o.error)return Me(i,e.path,"error","invalid_frontmatter",o.error),i;let a=o.frontmatter,c=Ke(e.path,a,t,n);if(c.length===0)return Me(i,e.path,"warn","no_matching_type","No type could be resolved for this file"),i;let l=c.map(f=>n.get(f)).filter(f=>!!f),u=c.filter(f=>!n.has(f));if(u.length>0&&Me(i,e.path,"error","unknown_type",`Resolved types are not defined: ${u.join(", ")}`),l.length===0)return i;for(let f of l)gw(e.path,a,f,i,r),f.specProfile==="v0.3"&&await LR(r,e.path,a,f,t,n,i);let d=t.spec_version.startsWith("0.3.")?!1:jR(l,t);if(d!==!1){let f=FR(l),p=new Set(t.settings.explicit_type_keys),h=d===!0?"error":"warn";for(let m of Object.keys(a))f.has(m)||p.has(m)||Me(i,e.path,h,"unknown_field",`Unknown field '${m}' in strict mode`,m)}return i}async function BR(r,e,t,n={}){let i=new Map;for(let o of r.getMarkdownFiles()){if(yt(o.path,e))continue;n.signal?.throwIfAborted();let a=await r.cachedRead(o),c=Ce(a);if(c.error)continue;let u=Ke(o.path,c.frontmatter,e,t).map(d=>t.get(d)).filter(d=>!!d);for(let d of u)for(let[f,p]of Object.entries(d.fields)){if(!K(p))continue;let h=p;if(h.unique!==!0)continue;let m=c.frontmatter[f];if(m==null)continue;let y=_p(m),g=h.unique_scope==="collection"?"collection":"type",b=`${g==="collection"?"*":d.name}::${f}::${y}`,v=i.get(b)??[];v.some(S=>S.path===o.path)||(v.push({path:o.path,typeName:d.name,fieldName:f,scope:g,specProfile:d.specProfile,value:m,fingerprint:y}),i.set(b,v))}}let s=[];for(let o of i.values())if(!(o.length<=1))for(let a of o){let c=o.filter(l=>l.path!==a.path).map(l=>l.path).join(", ");Me(s,a.path,"error",a.specProfile==="v0.3"?"duplicate_value":"duplicate_unique",a.scope==="collection"?`Field '${a.fieldName}' must be unique across the collection. Duplicate found in: ${c}`:`Field '${a.fieldName}' must be unique for type '${a.typeName}'. Duplicate found in: ${c}`,a.fieldName)}return s}function UR(r,e){let t=De(r);for(let n of e)for(let[i,s]of Object.entries(n.collection?.read_defaults??{}))i in t||(t[i]=De(s));return t}async function Rp(r,e,t,n={}){let i=[],s=r.getMarkdownFiles().filter(a=>!yt(a.path,e));n.onProgress?.({completed:0,total:s.length,phase:"notes"});for(let[a,c]of s.entries()){n.signal?.throwIfAborted();let l=await Sc(r,c,e,t);n.signal?.throwIfAborted(),n.onFile?.(c,l),i.push(...l),n.onProgress?.({completed:a+1,total:s.length,phase:"notes"}),a%25===0&&await new Promise(u=>setTimeout(u,0))}n.signal?.throwIfAborted(),n.onProgress?.({completed:s.length,total:s.length,phase:"uniqueness"});let o=await BR(r,e,t,n);return n.signal?.throwIfAborted(),i.push(...o),i}function Ip(r,e,t=jr.spec_version){if(t.startsWith("0.3.")){let i={kind:"mdbase.type",name:r,version:1,description:`${r} type`,schema:{dialect:"json-schema-2020-12",value:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",required:["title"],additionalProperties:!0,properties:{title:{type:"string",minLength:1},tags:{type:"array",items:{type:"string"}}}}}};return e&&e.trim()&&(i.match={path_glob:e.trim()}),`${mt(i,`# ${r} Type definition for ${r}.`)} `}let n={name:r,description:`${r} type`,strict:!1,fields:{title:{type:"string",required:!0}}};return e&&e.trim().length>0&&(n.match={path_glob:e.trim()}),`${mt(n,`# ${r} Type definition for ${r}.`)} -`}async function BR(r,e,t,n){let i=t.trim(),s=(0,oe.normalizePath)(`${e.settings.types_folder}/${i}.md`);if(await r.adapter.exists(s))throw new Error(`Type already exists: ${s}`);let o=Tp(i,n,e.spec_version);return await r.create(s,o),s}function Rp(r,e){let t={},n=e.settings.explicit_type_keys[0]??"type";t[n]=n==="types"?[r.name]:r.name;for(let[i,s]of Object.entries(r.fields)){if(!W(s))continue;let o=s;o.default!==void 0&&(t[i]=Oe(o.default))}return t}function Ip(r,e){let t=[];for(let[n,i]of Object.entries(r.fields)){if(!W(i))continue;let s=i;s.computed||s.required&&e[n]===void 0&&t.push([n,s])}return t}function Sc(r,e){let t=r.trim();switch(e.type??"string"){case"string":case"date":case"datetime":case"time":case"link":case"enum":case"any":return t;case"integer":{let i=Number(t);if(!/^[+-]?\d+$/.test(t)||!Number.isSafeInteger(i))throw new Error("Expected a whole integer");return i}case"number":{let i=Number(t);if(!/^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(t)||!Number.isFinite(i))throw new Error("Expected a finite number");return i}case"boolean":{let i=t.toLowerCase();if(["true","1","yes","y"].includes(i))return!0;if(["false","0","no","n"].includes(i))return!1;throw new Error("Expected boolean input: true/false")}case"list":{if(t.startsWith("[")||/^-\s/.test(t)){let s=(0,oe.parseYaml)(t);if(!Array.isArray(s))throw new Error("Expected a YAML or JSON list");return s}let i=t.split(",").map(s=>s.trim()).filter(s=>s.length>0);return e.items?i.map(s=>Sc(s,e.items)):i}case"object":{let i=(0,oe.parseYaml)(t);if(!W(i))throw new Error("Expected YAML object value");return i}case"tags":return t.split(",").map(i=>i.trim()).filter(i=>i.length>0);default:return t}}function $p(r){let e=r.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-+/,"").replace(/-+$/,"");return e.length>0?e:"note"}async function UR(r,e){let t=(0,oe.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let n=t.split("/"),i="";for(let s of n)i=i?`${i}/${s}`:s,await r.adapter.exists(i)||await r.createFolder(i)}function VR(r,e){if(!r.path_pattern||r.path_pattern.trim().length===0)return null;let t=(0,oe.normalizePath)(Pp(r.path_pattern,e));return t.endsWith(".md")?t:null}async function Op(r,e,t){let n=VR(e,t),i=uw(e,t),s=n?n.split("/").pop()??n:fw(e,t),o=yn(n||`${i?`${i}/`:""}${s.endsWith(".md")?s:`${s}.md`}`),a=o,c=2;for(;r.getAbstractFileByPath(a);)a=o.replace(/\.md$/,`-${c}.md`),c+=1;return a}async function HR(r,e,t,n=""){let i=yn(e),s=i.lastIndexOf("/");if(s>0&&await UR(r,i.slice(0,s)),await r.adapter.exists(i))throw new Error(`File already exists: ${i}`);let o=`${mt(t,n)} -`;return r.create(i,o)}function Dp(r){return bR(r)}var oe,tw,rw,xp,So,qr,mR,_o,MR,TR,qt=oy(()=>{oe=require("obsidian"),tw=Kn(Yf(),1),rw=Kn(op(),1),xp=Kn(gp(),1);Zv();So=class extends Error{constructor(t,n){super(n);this.code=t;this.name="MdbasePathError"}},qr={spec_version:"0.3.0",name:"My mdbase collection",description:"Typed markdown collection",settings:{types_folder:"_types",contracts_folder:"_contracts",explicit_type_keys:["type","types"],exclude:[]}},mR=["_types",".obsidian",".git","node_modules",".trash",".mdbase"],_o=null;MR={string:"text",integer:"a whole number",number:"a number",boolean:"true or false",array:"a list",object:"an object",null:"empty"},TR={date:"a date (YYYY-MM-DD)","date-time":"a date and time",time:"a time (HH:MM)",email:"an email address",uri:"a URI"}});var ss=A((EB,kw)=>{"use strict";var ZR="2.0.0",eI=Number.MAX_SAFE_INTEGER||9007199254740991,tI=16,rI=250,nI=["major","premajor","minor","preminor","patch","prepatch","prerelease"];kw.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:tI,MAX_SAFE_BUILD_LENGTH:rI,MAX_SAFE_INTEGER:eI,RELEASE_TYPES:nI,SEMVER_SPEC_VERSION:ZR,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Eo=A((AB,Pw)=>{"use strict";var iI=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};Pw.exports=iI});var os=A((Sr,Cw)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Vp,MAX_SAFE_BUILD_LENGTH:sI,MAX_LENGTH:oI}=ss(),aI=Eo();Sr=Cw.exports={};var cI=Sr.re=[],lI=Sr.safeRe=[],D=Sr.src=[],dI=Sr.safeSrc=[],N=Sr.t={},uI=0,Hp="[a-zA-Z0-9-]",fI=[["\\s",1],["\\d",oI],[Hp,sI]],pI=r=>{for(let[e,t]of fI)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},H=(r,e,t)=>{let n=pI(e),i=uI++;aI(r,i,e),N[r]=i,D[i]=e,dI[i]=n,cI[i]=new RegExp(e,t?"g":void 0),lI[i]=new RegExp(n,t?"g":void 0)};H("NUMERICIDENTIFIER","0|[1-9]\\d*");H("NUMERICIDENTIFIERLOOSE","\\d+");H("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Hp}*`);H("MAINVERSION",`(${D[N.NUMERICIDENTIFIER]})\\.(${D[N.NUMERICIDENTIFIER]})\\.(${D[N.NUMERICIDENTIFIER]})`);H("MAINVERSIONLOOSE",`(${D[N.NUMERICIDENTIFIERLOOSE]})\\.(${D[N.NUMERICIDENTIFIERLOOSE]})\\.(${D[N.NUMERICIDENTIFIERLOOSE]})`);H("PRERELEASEIDENTIFIER",`(?:${D[N.NONNUMERICIDENTIFIER]}|${D[N.NUMERICIDENTIFIER]})`);H("PRERELEASEIDENTIFIERLOOSE",`(?:${D[N.NONNUMERICIDENTIFIER]}|${D[N.NUMERICIDENTIFIERLOOSE]})`);H("PRERELEASE",`(?:-(${D[N.PRERELEASEIDENTIFIER]}(?:\\.${D[N.PRERELEASEIDENTIFIER]})*))`);H("PRERELEASELOOSE",`(?:-?(${D[N.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${D[N.PRERELEASEIDENTIFIERLOOSE]})*))`);H("BUILDIDENTIFIER",`${Hp}+`);H("BUILD",`(?:\\+(${D[N.BUILDIDENTIFIER]}(?:\\.${D[N.BUILDIDENTIFIER]})*))`);H("FULLPLAIN",`v?${D[N.MAINVERSION]}${D[N.PRERELEASE]}?${D[N.BUILD]}?`);H("FULL",`^${D[N.FULLPLAIN]}$`);H("LOOSEPLAIN",`[v=\\s]*${D[N.MAINVERSIONLOOSE]}${D[N.PRERELEASELOOSE]}?${D[N.BUILD]}?`);H("LOOSE",`^${D[N.LOOSEPLAIN]}$`);H("GTLT","((?:<|>)?=?)");H("XRANGEIDENTIFIERLOOSE",`${D[N.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);H("XRANGEIDENTIFIER",`${D[N.NUMERICIDENTIFIER]}|x|X|\\*`);H("XRANGEPLAIN",`[v=\\s]*(${D[N.XRANGEIDENTIFIER]})(?:\\.(${D[N.XRANGEIDENTIFIER]})(?:\\.(${D[N.XRANGEIDENTIFIER]})(?:${D[N.PRERELEASE]})?${D[N.BUILD]}?)?)?`);H("XRANGEPLAINLOOSE",`[v=\\s]*(${D[N.XRANGEIDENTIFIERLOOSE]})(?:\\.(${D[N.XRANGEIDENTIFIERLOOSE]})(?:\\.(${D[N.XRANGEIDENTIFIERLOOSE]})(?:${D[N.PRERELEASELOOSE]})?${D[N.BUILD]}?)?)?`);H("XRANGE",`^${D[N.GTLT]}\\s*${D[N.XRANGEPLAIN]}$`);H("XRANGELOOSE",`^${D[N.GTLT]}\\s*${D[N.XRANGEPLAINLOOSE]}$`);H("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Vp}})(?:\\.(\\d{1,${Vp}}))?(?:\\.(\\d{1,${Vp}}))?`);H("COERCE",`${D[N.COERCEPLAIN]}(?:$|[^\\d])`);H("COERCEFULL",D[N.COERCEPLAIN]+`(?:${D[N.PRERELEASE]})?(?:${D[N.BUILD]})?(?:$|[^\\d])`);H("COERCERTL",D[N.COERCE],!0);H("COERCERTLFULL",D[N.COERCEFULL],!0);H("LONETILDE","(?:~>?)");H("TILDETRIM",`(\\s*)${D[N.LONETILDE]}\\s+`,!0);Sr.tildeTrimReplace="$1~";H("TILDE",`^${D[N.LONETILDE]}${D[N.XRANGEPLAIN]}$`);H("TILDELOOSE",`^${D[N.LONETILDE]}${D[N.XRANGEPLAINLOOSE]}$`);H("LONECARET","(?:\\^)");H("CARETTRIM",`(\\s*)${D[N.LONECARET]}\\s+`,!0);Sr.caretTrimReplace="$1^";H("CARET",`^${D[N.LONECARET]}${D[N.XRANGEPLAIN]}$`);H("CARETLOOSE",`^${D[N.LONECARET]}${D[N.XRANGEPLAINLOOSE]}$`);H("COMPARATORLOOSE",`^${D[N.GTLT]}\\s*(${D[N.LOOSEPLAIN]})$|^$`);H("COMPARATOR",`^${D[N.GTLT]}\\s*(${D[N.FULLPLAIN]})$|^$`);H("COMPARATORTRIM",`(\\s*)${D[N.GTLT]}\\s*(${D[N.LOOSEPLAIN]}|${D[N.XRANGEPLAIN]})`,!0);Sr.comparatorTrimReplace="$1$2$3";H("HYPHENRANGE",`^\\s*(${D[N.XRANGEPLAIN]})\\s+-\\s+(${D[N.XRANGEPLAIN]})\\s*$`);H("HYPHENRANGELOOSE",`^\\s*(${D[N.XRANGEPLAINLOOSE]})\\s+-\\s+(${D[N.XRANGEPLAINLOOSE]})\\s*$`);H("STAR","(<|>)?=?\\s*\\*");H("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");H("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Cc=A((kB,Mw)=>{"use strict";var hI=Object.freeze({loose:!0}),mI=Object.freeze({}),yI=r=>r?typeof r!="object"?hI:r:mI;Mw.exports=yI});var zp=A((PB,Iw)=>{"use strict";var Tw=/^[0-9]+$/,Rw=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:rRw(e,r);Iw.exports={compareIdentifiers:Rw,rcompareIdentifiers:gI}});var je=A((CB,Dw)=>{"use strict";var Mc=Eo(),{MAX_LENGTH:Ow,MAX_SAFE_INTEGER:Tc}=ss(),{safeRe:Rc,t:Ic}=os(),bI=Cc(),{compareIdentifiers:Kp}=zp(),vI=(r,e)=>{let t=e.split(".");if(t.length>r.length)return!1;for(let n=0;nOw)throw new TypeError(`version is longer than ${Ow} characters`);Mc("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?Rc[Ic.LOOSE]:Rc[Ic.FULL]);if(!n)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>Tc||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Tc||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Tc||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(i=>{if(/^[0-9]+$/.test(i)){let s=+i;if(s>=0&&se.major?1:this.minore.minor?1:this.patche.patch?1:0}comparePre(e){if(e instanceof r||(e=new r(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{let n=this.prerelease[t],i=e.prerelease[t];if(Mc("prerelease compare",t,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return Kp(n,i)}while(++t)}compareBuild(e){e instanceof r||(e=new r(e,this.options));let t=0;do{let n=this.build[t],i=e.build[t];if(Mc("build compare",t,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return Kp(n,i)}while(++t)}inc(e,t,n){if(e.startsWith("pre")){if(!t&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(t){let i=`-${t}`.match(this.options.loose?Rc[Ic.PRERELEASELOOSE]:Rc[Ic.PRERELEASE]);if(!i||i[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,n),this.inc("pre",t,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,n),this.inc("pre",t,n);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let i=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[i];else{let s=this.prerelease.length;for(;--s>=0;)typeof this.prerelease[s]=="number"&&(this.prerelease[s]++,s=-2);if(s===-1){if(t===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(i)}}if(t){let s=[t,i];if(n===!1&&(s=[t]),vI(this.prerelease,t)){let o=this.prerelease[t.split(".").length];isNaN(o)&&(this.prerelease=s)}else this.prerelease=s}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Dw.exports=Wp});var vn=A((MB,Lw)=>{"use strict";var Nw=je(),wI=(r,e,t=!1)=>{if(r instanceof Nw)return r;try{return new Nw(r,e)}catch(n){if(!t)return null;throw n}};Lw.exports=wI});var jw=A((TB,Fw)=>{"use strict";var _I=vn(),SI=(r,e)=>{let t=_I(r,e);return t?t.version:null};Fw.exports=SI});var Bw=A((RB,qw)=>{"use strict";var $I=vn(),xI=(r,e)=>{let t=$I(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};qw.exports=xI});var Hw=A((IB,Vw)=>{"use strict";var Uw=je(),EI=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new Uw(r instanceof Uw?r.version:r,t).inc(e,n,i).version}catch{return null}};Vw.exports=EI});var Ww=A((OB,Kw)=>{"use strict";var zw=vn(),AI=(r,e)=>{let t=zw(r,null,!0),n=zw(e,null,!0),i=t.compare(n);if(i===0)return null;let s=i>0,o=s?t:n,a=s?n:t,c=!!o.prerelease.length;if(!!a.prerelease.length&&!c){if(!a.patch&&!a.minor)return"major";if(a.compareMain(o)===0)return a.minor&&!a.patch?"minor":"patch"}let u=c?"pre":"";return t.major!==n.major?u+"major":t.minor!==n.minor?u+"minor":t.patch!==n.patch?u+"patch":"prerelease"};Kw.exports=AI});var Jw=A((DB,Gw)=>{"use strict";var kI=je(),PI=(r,e)=>new kI(r,e).major;Gw.exports=PI});var Xw=A((NB,Yw)=>{"use strict";var CI=je(),MI=(r,e)=>new CI(r,e).minor;Yw.exports=MI});var Zw=A((LB,Qw)=>{"use strict";var TI=je(),RI=(r,e)=>new TI(r,e).patch;Qw.exports=RI});var t_=A((FB,e_)=>{"use strict";var II=vn(),OI=(r,e)=>{let t=II(r,e);return t&&t.prerelease.length?t.prerelease:null};e_.exports=OI});var Bt=A((jB,n_)=>{"use strict";var r_=je(),DI=(r,e,t)=>new r_(r,t).compare(new r_(e,t));n_.exports=DI});var s_=A((qB,i_)=>{"use strict";var NI=Bt(),LI=(r,e,t)=>NI(e,r,t);i_.exports=LI});var a_=A((BB,o_)=>{"use strict";var FI=Bt(),jI=(r,e)=>FI(r,e,!0);o_.exports=jI});var Oc=A((UB,l_)=>{"use strict";var c_=je(),qI=(r,e,t)=>{let n=new c_(r,t),i=new c_(e,t);return n.compare(i)||n.compareBuild(i)};l_.exports=qI});var u_=A((VB,d_)=>{"use strict";var BI=Oc(),UI=(r,e)=>r.sort((t,n)=>BI(t,n,e));d_.exports=UI});var p_=A((HB,f_)=>{"use strict";var VI=Oc(),HI=(r,e)=>r.sort((t,n)=>VI(n,t,e));f_.exports=HI});var Ao=A((zB,h_)=>{"use strict";var zI=Bt(),KI=(r,e,t)=>zI(r,e,t)>0;h_.exports=KI});var Dc=A((KB,m_)=>{"use strict";var WI=Bt(),GI=(r,e,t)=>WI(r,e,t)<0;m_.exports=GI});var Gp=A((WB,y_)=>{"use strict";var JI=Bt(),YI=(r,e,t)=>JI(r,e,t)===0;y_.exports=YI});var Jp=A((GB,g_)=>{"use strict";var XI=Bt(),QI=(r,e,t)=>XI(r,e,t)!==0;g_.exports=QI});var Nc=A((JB,b_)=>{"use strict";var ZI=Bt(),eO=(r,e,t)=>ZI(r,e,t)>=0;b_.exports=eO});var Lc=A((YB,v_)=>{"use strict";var tO=Bt(),rO=(r,e,t)=>tO(r,e,t)<=0;v_.exports=rO});var Yp=A((XB,w_)=>{"use strict";var nO=Gp(),iO=Jp(),sO=Ao(),oO=Nc(),aO=Dc(),cO=Lc(),lO=(r,e,t,n)=>{switch(e){case"===":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r===t;case"!==":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r!==t;case"":case"=":case"==":return nO(r,t,n);case"!=":return iO(r,t,n);case">":return sO(r,t,n);case">=":return oO(r,t,n);case"<":return aO(r,t,n);case"<=":return cO(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};w_.exports=lO});var S_=A((QB,__)=>{"use strict";var dO=je(),uO=vn(),{safeRe:Fc,t:jc}=os(),fO=(r,e)=>{if(r instanceof dO)return r;if(typeof r=="number"&&(r=String(r)),typeof r!="string")return null;e=e||{};let t=null;if(!e.rtl)t=r.match(e.includePrerelease?Fc[jc.COERCEFULL]:Fc[jc.COERCE]);else{let c=e.includePrerelease?Fc[jc.COERCERTLFULL]:Fc[jc.COERCERTL],l;for(;(l=c.exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||l.index+l[0].length!==t.index+t[0].length)&&(t=l),c.lastIndex=l.index+l[1].length+l[2].length;c.lastIndex=-1}if(t===null)return null;let n=t[2],i=t[3]||"0",s=t[4]||"0",o=e.includePrerelease&&t[5]?`-${t[5]}`:"",a=e.includePrerelease&&t[6]?`+${t[6]}`:"";return uO(`${n}.${i}.${s}${o}${a}`,e)};__.exports=fO});var x_=A((ZB,$_)=>{"use strict";var pO=vn(),hO=ss(),mO=je(),yO=(r,e,t)=>{if(!hO.RELEASE_TYPES.includes(e))return null;let n=gO(r,t);return n&&bO(n,e)},gO=(r,e)=>{let t=r instanceof mO?r.version:r;return pO(t,e)},bO=(r,e)=>{if(vO(e))return r.version;switch(r.prerelease=[],e){case"major":r.minor=0,r.patch=0;break;case"minor":r.patch=0;break}return r.format()},vO=r=>r.startsWith("pre");$_.exports=yO});var A_=A((eU,E_)=>{"use strict";var Xp=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let i=this.map.keys().next().value;this.delete(i)}this.map.set(e,t)}return this}};E_.exports=Xp});var Ut=A((tU,M_)=>{"use strict";var wO=/\s+/g,Qp=class r{constructor(e,t){if(t=SO(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof Zp)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(wO," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(i=>!P_(i[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let i of this.set)if(i.length===1&&TO(i[0])){this.set=[i];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e0&&(this.formatted+="||");let t=this.set[e];for(let n=0;n0&&(this.formatted+=" "),this.formatted+=t[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){e=e.replace(MO,"");let n=((this.options.includePrerelease&&PO)|(this.options.loose&&CO))+":"+e,i=k_.get(n);if(i)return i;let s=this.options.loose,o=s?rt[qe.HYPHENRANGELOOSE]:rt[qe.HYPHENRANGE];e=e.replace(o,UO(this.options.includePrerelease)),be("hyphen replace",e),e=e.replace(rt[qe.COMPARATORTRIM],EO),be("comparator trim",e),e=e.replace(rt[qe.TILDETRIM],AO),be("tilde trim",e),e=e.replace(rt[qe.CARETTRIM],kO),be("caret trim",e);let a=e.split(" ").map(d=>RO(d,this.options)).join(" ").split(/\s+/).map(d=>BO(d,this.options));s&&(a=a.filter(d=>(be("loose invalid filter",d,this.options),!!d.match(rt[qe.COMPARATORLOOSE])))),be("range list",a);let c=new Map,l=a.map(d=>new Zp(d,this.options));for(let d of l){if(P_(d))return[d];c.set(d.value,d)}c.size>1&&c.has("")&&c.delete("");let u=[...c.values()];return k_.set(n,u),u}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>C_(n,t)&&e.set.some(i=>C_(i,t)&&n.every(s=>i.every(o=>s.intersects(o,t)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new $O(e,this.options)}catch{return!1}for(let t=0;tr.value==="<0.0.0-0",TO=r=>r.value==="",C_=(r,e)=>{let t=!0,n=r.slice(),i=n.pop();for(;t&&n.length;)t=n.every(s=>i.intersects(s,e)),i=n.pop();return t},RO=(r,e)=>(r=r.replace(rt[qe.BUILD],""),be("comp",r,e),r=NO(r,e),be("caret",r),r=OO(r,e),be("tildes",r),r=FO(r,e),be("xrange",r),r=qO(r,e),be("stars",r),r),Te=r=>!r||r.toLowerCase()==="x"||r==="*",IO=(r,e,t)=>Te(r)&&!Te(e)||Te(e)&&t&&!Te(t),OO=(r,e)=>r.trim().split(/\s+/).map(t=>DO(t,e)).join(" "),DO=(r,e)=>{let t=e.loose?rt[qe.TILDELOOSE]:rt[qe.TILDE],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{be("tilde",r,i,s,o,a,c);let l;return Te(s)?l="":Te(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Te(a)?l=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:c?(be("replaceTilde pr",c),l=`>=${s}.${o}.${a}-${c} <${s}.${+o+1}.0-0`):l=`>=${s}.${o}.${a} <${s}.${+o+1}.0-0`,be("tilde return",l),l})},NO=(r,e)=>r.trim().split(/\s+/).map(t=>LO(t,e)).join(" "),LO=(r,e)=>{be("caret",r,e);let t=e.loose?rt[qe.CARETLOOSE]:rt[qe.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{be("caret",r,i,s,o,a,c);let l;return Te(s)?l="":Te(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Te(a)?s==="0"?l=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.0${n} <${+s+1}.0.0-0`:c?(be("replaceCaret pr",c),s==="0"?o==="0"?l=`>=${s}.${o}.${a}-${c} <${s}.${o}.${+a+1}-0`:l=`>=${s}.${o}.${a}-${c} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.${a}-${c} <${+s+1}.0.0-0`):(be("no pr"),s==="0"?o==="0"?l=`>=${s}.${o}.${a} <${s}.${o}.${+a+1}-0`:l=`>=${s}.${o}.${a} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.${a} <${+s+1}.0.0-0`),be("caret return",l),l})},FO=(r,e)=>(be("replaceXRanges",r,e),r.split(/\s+/).map(t=>jO(t,e)).join(" ")),jO=(r,e)=>{r=r.trim();let t=e.loose?rt[qe.XRANGELOOSE]:rt[qe.XRANGE];return r.replace(t,(n,i,s,o,a,c)=>{if(be("xRange",r,n,i,s,o,a,c),IO(s,o,a))return r;let l=Te(s),u=l||Te(o),d=u||Te(a),f=d;return i==="="&&f&&(i=""),c=e.includePrerelease?"-0":"",l?i===">"||i==="<"?n="<0.0.0-0":n="*":i&&f?(u&&(o=0),a=0,i===">"?(i=">=",u?(s=+s+1,o=0,a=0):(o=+o+1,a=0)):i==="<="&&(i="<",u?s=+s+1:o=+o+1),i==="<"&&(c="-0"),n=`${i+s}.${o}.${a}${c}`):u?n=`>=${s}.0.0${c} <${+s+1}.0.0-0`:d&&(n=`>=${s}.${o}.0${c} <${s}.${+o+1}.0-0`),be("xRange return",n),n})},qO=(r,e)=>(be("replaceStars",r,e),r.trim().replace(rt[qe.STAR],"")),BO=(r,e)=>(be("replaceGTE0",r,e),r.trim().replace(rt[e.includePrerelease?qe.GTE0PRE:qe.GTE0],"")),UO=r=>(e,t,n,i,s,o,a,c,l,u,d,f)=>(Te(n)?t="":Te(i)?t=`>=${n}.0.0${r?"-0":""}`:Te(s)?t=`>=${n}.${i}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,Te(l)?c="":Te(u)?c=`<${+l+1}.0.0-0`:Te(d)?c=`<${l}.${+u+1}.0-0`:f?c=`<=${l}.${u}.${d}-${f}`:r?c=`<${l}.${u}.${+d+1}-0`:c=`<=${c}`,`${t} ${c}`.trim()),VO=(r,e,t)=>{for(let n=0;n0){let i=r[n].semver;if(i.major===e.major&&i.minor===e.minor&&i.patch===e.patch)return!0}return!1}return!0}});var ko=A((rU,N_)=>{"use strict";var Po=Symbol("SemVer ANY"),rh=class r{static get ANY(){return Po}constructor(e,t){if(t=T_(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),th("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Po?this.value="":this.value=this.operator+this.semver.version,th("comp",this)}parse(e){let t=this.options.loose?R_[I_.COMPARATORLOOSE]:R_[I_.COMPARATOR],n=e.match(t);if(!n)throw new TypeError(`Invalid comparator: ${e}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new O_(n[2],this.options.loose):this.semver=Po}toString(){return this.value}test(e){if(th("Comparator.test",e,this.options.loose),this.semver===Po||e===Po)return!0;if(typeof e=="string")try{e=new O_(e,this.options)}catch{return!1}return eh(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new D_(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new D_(this.value,t).test(e.semver):(t=T_(t),t.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||eh(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||eh(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};N_.exports=rh;var T_=Cc(),{safeRe:R_,t:I_}=os(),eh=Yp(),th=Eo(),O_=je(),D_=Ut()});var Co=A((nU,L_)=>{"use strict";var HO=Ut(),zO=(r,e,t)=>{try{e=new HO(e,t)}catch{return!1}return e.test(r)};L_.exports=zO});var j_=A((iU,F_)=>{"use strict";var KO=Ut(),WO=(r,e)=>new KO(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));F_.exports=WO});var B_=A((sU,q_)=>{"use strict";var GO=je(),JO=Ut(),YO=(r,e,t)=>{let n=null,i=null,s=null;try{s=new JO(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===-1)&&(n=o,i=new GO(n,t))}),n};q_.exports=YO});var V_=A((oU,U_)=>{"use strict";var XO=je(),QO=Ut(),ZO=(r,e,t)=>{let n=null,i=null,s=null;try{s=new QO(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===1)&&(n=o,i=new XO(n,t))}),n};U_.exports=ZO});var K_=A((aU,z_)=>{"use strict";var nh=je(),eD=Ut(),H_=Ao(),tD=(r,e)=>{r=new eD(r,e);let t=new nh("0.0.0");if(r.test(t)||(t=new nh("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n{let a=new nh(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||H_(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||H_(t,s))&&(t=s)}return t&&r.test(t)?t:null};z_.exports=tD});var G_=A((cU,W_)=>{"use strict";var rD=Ut(),nD=(r,e)=>{try{return new rD(r,e).range||"*"}catch{return null}};W_.exports=nD});var qc=A((lU,Q_)=>{"use strict";var iD=je(),X_=ko(),{ANY:sD}=X_,oD=Ut(),aD=Co(),J_=Ao(),Y_=Dc(),cD=Lc(),lD=Nc(),dD=(r,e,t,n)=>{r=new iD(r,n),e=new oD(e,n);let i,s,o,a,c;switch(t){case">":i=J_,s=cD,o=Y_,a=">",c=">=";break;case"<":i=Y_,s=lD,o=J_,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(aD(r,e,n))return!1;for(let l=0;l{p.semver===sD&&(p=new X_(">=0.0.0")),d=d||p,f=f||p,i(p.semver,d.semver,n)?d=p:o(p.semver,f.semver,n)&&(f=p)}),d.operator===a||d.operator===c||(!f.operator||f.operator===a)&&s(r,f.semver))return!1;if(f.operator===c&&o(r,f.semver))return!1}return!0};Q_.exports=dD});var e0=A((dU,Z_)=>{"use strict";var uD=qc(),fD=(r,e,t)=>uD(r,e,">",t);Z_.exports=fD});var r0=A((uU,t0)=>{"use strict";var pD=qc(),hD=(r,e,t)=>pD(r,e,"<",t);t0.exports=hD});var s0=A((fU,i0)=>{"use strict";var n0=Ut(),mD=(r,e,t)=>(r=new n0(r,t),e=new n0(e,t),r.intersects(e,t));i0.exports=mD});var a0=A((pU,o0)=>{"use strict";var yD=Co(),gD=Bt();o0.exports=(r,e,t)=>{let n=[],i=null,s=null,o=r.sort((u,d)=>gD(u,d,t));for(let u of o)yD(u,e,t)?(s=u,i||(i=u)):(s&&n.push([i,s]),s=null,i=null);i&&n.push([i,null]);let a=[];for(let[u,d]of n)u===d?a.push(u):!d&&u===o[0]?a.push("*"):d?u===o[0]?a.push(`<=${d}`):a.push(`${u} - ${d}`):a.push(`>=${u}`);let c=a.join(" || "),l=typeof e.raw=="string"?e.raw:String(e);return c.length{"use strict";var c0=Ut(),oh=ko(),{ANY:ih}=oh,sh=Co(),ah=Bt(),bD=(r,e,t={})=>{if(r===e)return!0;r=new c0(r,t),e=new c0(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let o=wD(i,s,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},vD=[new oh(">=0.0.0-0")],l0=[new oh(">=0.0.0")],wD=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===ih){if(e.length===1&&e[0].semver===ih)return!0;t.includePrerelease?r=vD:r=l0}if(e.length===1&&e[0].semver===ih){if(t.includePrerelease)return!0;e=l0}let n=new Set,i,s;for(let p of r)p.operator===">"||p.operator===">="?i=d0(i,p,t):p.operator==="<"||p.operator==="<="?s=u0(s,p,t):n.add(p.semver);if(n.size>1)return null;let o;if(i&&s){if(o=ah(i.semver,s.semver,t),o>0)return null;if(o===0&&(i.operator!==">="||s.operator!=="<="))return null}for(let p of n){if(i&&!sh(p,String(i),t)||s&&!sh(p,String(s),t))return null;for(let m of e)if(!sh(p,String(m),t))return!1;return!0}let a,c,l,u,d=s&&!t.includePrerelease&&s.semver.prerelease.length?s.semver:!1,f=i&&!t.includePrerelease&&i.semver.prerelease.length?i.semver:!1;d&&d.prerelease.length===1&&s.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(let p of e){if(u=u||p.operator===">"||p.operator===">=",l=l||p.operator==="<"||p.operator==="<=",i){if(f&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===f.major&&p.semver.minor===f.minor&&p.semver.patch===f.patch&&(f=!1),p.operator===">"||p.operator===">="){if(a=d0(i,p,t),a===p&&a!==i)return!1}else if(i.operator===">="&&!p.test(i.semver))return!1}if(s){if(d&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===d.major&&p.semver.minor===d.minor&&p.semver.patch===d.patch&&(d=!1),p.operator==="<"||p.operator==="<="){if(c=u0(s,p,t),c===p&&c!==s)return!1}else if(s.operator==="<="&&!p.test(s.semver))return!1}if(!p.operator&&(s||i)&&o!==0)return!1}return!(i&&l&&!s&&o!==0||s&&u&&!i&&o!==0||f||d)},d0=(r,e,t)=>{if(!r)return e;let n=ah(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},u0=(r,e,t)=>{if(!r)return e;let n=ah(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};f0.exports=bD});var g0=A((mU,y0)=>{"use strict";var ch=os(),h0=ss(),_D=je(),m0=zp(),SD=vn(),$D=jw(),xD=Bw(),ED=Hw(),AD=Ww(),kD=Jw(),PD=Xw(),CD=Zw(),MD=t_(),TD=Bt(),RD=s_(),ID=a_(),OD=Oc(),DD=u_(),ND=p_(),LD=Ao(),FD=Dc(),jD=Gp(),qD=Jp(),BD=Nc(),UD=Lc(),VD=Yp(),HD=S_(),zD=x_(),KD=ko(),WD=Ut(),GD=Co(),JD=j_(),YD=B_(),XD=V_(),QD=K_(),ZD=G_(),eN=qc(),tN=e0(),rN=r0(),nN=s0(),iN=a0(),sN=p0();y0.exports={parse:SD,valid:$D,clean:xD,inc:ED,diff:AD,major:kD,minor:PD,patch:CD,prerelease:MD,compare:TD,rcompare:RD,compareLoose:ID,compareBuild:OD,sort:DD,rsort:ND,gt:LD,lt:FD,eq:jD,neq:qD,gte:BD,lte:UD,cmp:VD,coerce:HD,truncate:zD,Comparator:KD,Range:WD,satisfies:GD,toComparators:JD,maxSatisfying:YD,minSatisfying:XD,minVersion:QD,validRange:ZD,outside:eN,gtr:tN,ltr:rN,intersects:nN,simplifyRange:iN,subset:sN,SemVer:_D,re:ch.re,src:ch.src,tokens:ch.t,SEMVER_SPEC_VERSION:h0.SEMVER_SPEC_VERSION,RELEASE_TYPES:h0.RELEASE_TYPES,compareIdentifiers:m0.compareIdentifiers,rcompareIdentifiers:m0.rcompareIdentifiers}});var uj={};ay(uj,{default:()=>Rd});module.exports=iE(uj);var It=require("obsidian"),Od="https://mdbase.dev/contracts/catalog.json",Ls="mdbase.lock.yaml",Nr=".mdbase/obsidian-pack-install.json";function mr(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid contract catalog or type pack.");return r}function Wt(r){if(typeof r!="string"||!r)throw new Error("Missing catalog field.");return r}function dy(r){let e=Wt(r);if(!/^sha256:[a-f0-9]{64}$/.test(e))throw new Error("Invalid pack digest.");return e}function Ca(r){let e=Wt(r);if(e.includes("\\")||e.includes(":")||Array.from(e).some(t=>t.charCodeAt(0)<32)||e.split("/").some(t=>!t||t==="."||t===".."||t.startsWith(".")))throw new Error(`Unsafe pack path: ${e}`);return e}async function Pi(r){let e=typeof r=="string"?new TextEncoder().encode(r):r;return`sha256:${Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",e))).map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Dd(r){return Array.isArray(r)?`[${r.map(Dd).join(",")}]`:r&&typeof r=="object"?`{${Object.entries(r).sort(([e],[t])=>et?1:0).map(([e,t])=>`${JSON.stringify(e)}:${Dd(t)}`).join(",")}}`:JSON.stringify(r)}function sE(r){let e=new URL(Wt(r),Od);if(e.origin!==new URL(Od).origin||!e.pathname.startsWith("/contracts/"))throw new Error("Pack artifacts must come from the first-party contract catalog.");return e.href}async function oE(){let r=await(0,It.requestUrl)({url:Od,throw:!1});if(r.status!==200)throw new Error(`Catalog unavailable (${r.status}). Your vault is unchanged. Try again when online.`);if(r.arrayBuffer.byteLength>1024*1024)throw new Error("Contract catalog is too large.");let e=mr(r.json);if(e.catalog_version!==2||!Array.isArray(e.packs))throw new Error("Unsupported contract catalog.");return e.packs.map(t=>{let n=mr(t),i=mr(n.display),s=mr(n.installation);if(!Number.isInteger(n.resource_count)||Number(n.resource_count)<1||Number(n.resource_count)>100)throw new Error("Invalid pack resource count.");return{id:Wt(n.id),version:Wt(n.version),digest:dy(n.digest),provision:sE(n.provision),resource_count:Number(n.resource_count),display:{name:Wt(i.name),summary:Wt(i.summary)},installation:{visibility:Wt(s.visibility),recommendation:Wt(s.recommendation),primary_type:s.primary_type==null?null:Wt(s.primary_type),...typeof s.caution=="string"?{caution:s.caution}:{}}}})}async function Wn(r,e){let t=r.vault.getAbstractFileByPath(e);if(t&&!(t instanceof It.TFile))throw new Error(`A folder occupies ${e}.`);return t instanceof It.TFile?r.vault.read(t):null}async function ly(r,e){let t=e.split("/");t.pop();let n="";for(let i of t)n=n?`${n}/${i}`:i,r.vault.getAbstractFileByPath(n)||await r.vault.createFolder(n)}async function aE(r,e){let t=await(0,It.requestUrl)({url:e.provision,throw:!1});if(t.status!==200)throw new Error(`Type pack unavailable (${t.status}).`);if(t.arrayBuffer.byteLength>1024*1024||await Pi(t.arrayBuffer)!==e.digest)throw new Error("The type pack does not match its catalog digest.");return cE(r,e,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t.arrayBuffer)))}async function cE(r,e,t){let n=mr(t),i=mr(n.manifest);if(i.kind!=="mdbase.type-pack"||i.id!==e.id||i.version!==e.version||!Array.isArray(i.resources)||i.resources.length!==e.resource_count||!Array.isArray(n.resources)||n.resources.length!==i.resources.length)throw new Error("The type-pack identity or resources do not match the catalog.");let s=new Map;for(let h of n.resources){let y=mr(h),g=Ca(y.source);if(s.has(g))throw new Error("Duplicate pack source.");let b=Wt(y.document);if(new TextEncoder().encode(b).byteLength>262144)throw new Error("Pack resource is too large.");s.set(g,b)}let o=new Set,a=[],c=[],l=await Wn(r,Ls),u=l?(0,It.parseYaml)(l):{kind:"mdbase.type-pack-lock",lock_version:1,packs:[]};if(u.kind!=="mdbase.type-pack-lock"||u.lock_version!==1||!Array.isArray(u.packs))throw new Error("Existing pack lock cannot be read safely.");let d=u.packs.find(h=>h.id===e.id),f=await Pi(Dd(i));if(d&&(d.version!==e.version||d.digest!==f))throw new Error("This pack is already installed at another revision. Upgrade it with mdbase editor; Obsidian currently supports fresh installs and same-version repair only.");for(let h of i.resources){let y=mr(h),g=Ca(y.source),b=Ca(y.target);if(!["contract","type","schema"].includes(String(y.kind))||!["managed","seed"].includes(String(y.mode))||o.has(b))throw new Error("Invalid pack resource or duplicate target.");let v=y.kind==="type"?"_types/":y.kind==="contract"?"_contracts/":"schemas/";if(!b.startsWith(v))throw new Error(`Unsupported pack target ${b}. Default definition folders are required.`);o.add(b);let S=s.get(g),_=dy(y.digest);if(!S||await Pi(S)!==_)throw new Error(`Resource digest mismatch: ${g}`);if(u.packs.some(M=>M.id!==e.id&&M.resources.some(x=>x.mode==="managed"&&x.target===b)))throw new Error(`${b} belongs to another installed pack.`);let E=await Wn(r,b),k=d?.resources.find(M=>M.target===b);if(y.mode==="managed"&&E!==null&&await Pi(E)!==_)throw new Error(`${b} already exists with different contents. Nothing was overwritten.`);let $=E===null&&!(y.mode==="seed"&&k)?"create":y.mode==="seed"?"preserve":"unchanged";a.push({path:b,before:E,after:S,action:$}),c.push({kind:y.kind,mode:y.mode,source:g,target:b,digest:_})}let p={id:e.id,version:e.version,digest:f,installed_by:d?.installed_by??"mdbase-obsidian",resources:c},m=`${JSON.stringify({...u,packs:[...u.packs.filter(h=>h.id!==e.id),p].sort((h,y)=>h.id.localeCompare(y.id))},null,2)} -`;return{pack:e,provision:t,lockBefore:l,lockAfter:m,files:a}}async function Nd(r){if(!await r.vault.adapter.exists(Nr))return;let e=mr(JSON.parse(await r.vault.adapter.read(Nr)));if(!Array.isArray(e.created))throw new Error("Invalid pack recovery journal.");if(await Wn(r,Ls)===e.lockAfter){await r.vault.adapter.remove(Nr);return}for(let t of[...e.created].reverse()){let n=mr(t),i=Ca(n.path),s=r.vault.getAbstractFileByPath(i);if(s instanceof It.TFile&&await Pi(await r.vault.read(s))===n.digest)await r.fileManager.trashFile(s);else if(s)throw new Error(`Pack recovery stopped: ${i} changed. Your edits and the journal were preserved.`)}await r.vault.adapter.remove(Nr)}var Id=new WeakSet;async function lE(r,e,t,n){if(Id.has(r))throw new Error("Another contract pack is installing. Wait for it to finish.");Id.add(r);try{await dE(r,e,t,n)}finally{Id.delete(r)}}async function dE(r,e,t,n){if(t(),await r.vault.adapter.exists(Nr))throw new Error("Recover the previous pack installation before trying again.");if(await Wn(r,Ls)!==e.lockBefore)throw new Error("Pack lock changed. Review again.");for(let s of e.files)if(await Wn(r,s.path)!==s.before)throw new Error(`${s.path} changed. Review again.`);await ly(r,Nr);let i={lockAfter:e.lockAfter,created:[]};await r.vault.adapter.write(Nr,JSON.stringify(i));try{let s=e.files.filter(a=>a.action==="create");n?.(0,s.length);for(let[a,c]of s.entries()){if(t(),await ly(r,c.path),await Wn(r,c.path)!==null)throw new Error(`${c.path} appeared during installation.`);if(i.created.push({path:c.path,digest:await Pi(c.after)}),await r.vault.adapter.write(Nr,JSON.stringify(i)),await r.vault.create(c.path,c.after),await Wn(r,c.path)!==c.after)throw new Error(`${c.path} changed during installation. Recovery will preserve competing edits.`);n?.(a+1,s.length)}t();let o=r.vault.getAbstractFileByPath(Ls);o instanceof It.TFile?await r.vault.process(o,a=>{if(a!==e.lockBefore)throw new Error("Pack lock changed during installation.");return e.lockAfter}):await r.vault.create(Ls,e.lockAfter),await r.vault.adapter.remove(Nr)}catch(s){throw await Nd(r),s}}var Ma=class extends It.Modal{constructor(t,n,i){super(t);this.assertWritable=n;this.installed=i;this.dismissed=!1}onOpen(){this.titleEl.setText("Ready-made types \xB7 mdbase-contracts"),this.load()}async load(){this.contentEl.empty(),this.contentEl.createEl("p",{text:"Loading first-party contract catalog\u2026"});try{let t=await oE();if(this.dismissed)return;this.contentEl.empty(),this.contentEl.createEl("p",{text:"Install standard application contracts plus editable starter types. Nothing grants applications access to your vault. Existing starter types are preserved."});let n=this.contentEl.createEl("details");n.createEl("summary",{text:"Advanced and integration packs"});for(let i of t.filter(s=>s.installation.visibility!=="hidden")){let s=(i.installation.visibility==="default"?this.contentEl:n).createDiv({cls:"mdbase-editor-section"});s.createEl("h3",{text:i.display.name}),s.createDiv({cls:"mdbase-muted",text:`Version ${i.version}`}),s.createEl("p",{text:i.display.summary}),i.installation.caution&&s.createEl("p",{text:i.installation.caution});let o=s.createEl("button",{text:"Review installation"}),a=s.createDiv();o.onclick=()=>{o.disabled=!0,aE(this.app,i).then(c=>{if(this.dismissed)return;a.empty();for(let u of c.files)a.createDiv({text:`${u.action} \xB7 ${u.path}`});let l=a.createEl("button",{text:"Install reviewed pack",cls:"mod-cta"});l.onclick=()=>{l.disabled=!0,lE(this.app,c,this.assertWritable,(u,d)=>{l.textContent=`Installing ${u} of ${d} files\u2026`}).then(async()=>{await this.installed(i.installation.primary_type),this.close()}).catch(u=>{a.createDiv({cls:"mdbase-inline-error",text:String(u)}),l.disabled=!1,l.textContent="Install reviewed pack"})}}).catch(c=>{a.createDiv({cls:"mdbase-inline-error",text:String(c)})}).finally(()=>{o.disabled=!1})}}}catch(t){if(this.dismissed)return;this.contentEl.empty(),this.contentEl.createEl("p",{cls:"mdbase-inline-error",text:String(t)}),this.contentEl.createEl("button",{text:"Retry catalog"}).onclick=()=>void this.load()}}onClose(){this.dismissed=!0}};var Ta=class{constructor(){this.checked=new Set;this.revision=0;this.lastCompletedAt=null;this.completedRevision=-1;this.cancelled=!1;this.progress=null}changed(e){this.revision++,e?this.checked.delete(e):this.checked.clear()}markChecked(e){this.checked.add(e)}isChecked(e){return this.checked.has(e)}summary(e){if(this.progress)return this.progress.phase==="uniqueness"?`Checked ${this.progress.completed} of ${this.progress.total} notes \xB7 checking uniqueness\u2026`:`Checking ${this.progress.completed} of ${this.progress.total} notes\u2026`;let t=e.filter(n=>this.checked.has(n)).length;return this.cancelled?`Validation stopped \xB7 ${t} of ${e.length} notes checked \xB7 results incomplete`:this.lastCompletedAt&&this.completedRevision===this.revision?`Validated ${new Date(this.lastCompletedAt).toLocaleTimeString()} \xB7 ${e.length} notes \xB7 including uniqueness`:this.lastCompletedAt?`Changed since last collection validation \xB7 ${t} of ${e.length} notes checked`:t?`Checked ${t} of ${e.length} notes \xB7 collection uniqueness not checked`:"Not checked yet"}};var tt=require("obsidian");var yw=require("obsidian");qt();function zR(r){let e=r.trim();if(!e||e.startsWith("/")||e.includes("\\")||Array.from(e).some(t=>t.charCodeAt(0)<32)||e.split("/").some(t=>!t||t==="."||t===".."||t.startsWith(".")))throw new Error("Choose a visible, vault-relative note path without .. or empty folders.");return e.endsWith(".md")?e:`${e}.md`}var $c=class extends yw.Modal{constructor(t,n,i,s,o){super(t);this.type=n;this.config=i;this.types=s;this.create=o;this.inputs=new Map;this.customPath=!1;this.suggestionVersion=0;this.creating=!1;this.dismissed=!1;this.frontmatter=Rp(n,i)}onOpen(){this.titleEl.setText(`New ${this.type.name}`),this.contentEl.addClass("mdbase-create-note");let t=Ip(this.type,this.frontmatter),n=this.type.display_name_key??"title";!t.some(([c])=>c===n)&&this.frontmatter[n]==null&&t.unshift([n,this.type.fields[n]??{type:"string",description:"Used for the file name."}]);for(let[c,l]of t){let u=this.contentEl.createDiv({cls:"mdbase-form-row"}),d=u.createEl("label",{text:`${c}${l.required?" *":""}`});l.description&&u.createDiv({cls:"mdbase-form-description",text:l.description});let f;if(l.type==="boolean"||l.type==="enum"){let m=u.createEl("select");f=m,m.createEl("option",{value:"",text:"Choose\u2026"}),(l.type==="boolean"?[!0,!1]:l.values??[]).forEach((y,g)=>m.createEl("option",{value:String(g),text:String(y)}))}else if(["object","list","any"].includes(l.type??""))f=u.createEl("textarea"),f.placeholder=l.type==="object"?"YAML object":l.type==="list"?"YAML list or comma-separated values":"Value";else{let m=l.type==="date"?"date":l.type==="datetime"?"datetime-local":l.type==="time"?"time":"text";if(f=u.createEl("input",{type:m}),["integer","number"].includes(l.type??"")&&(f.inputMode="decimal"),l.type==="link"){let h=u.createEl("datalist");h.id=`mdbase-links-${this.inputs.size}`,this.app.vault.getMarkdownFiles().slice(0,500).forEach(y=>h.createEl("option",{value:`[[${y.path.replace(/\.md$/,"")}]]`})),f.setAttr("list",h.id)}}d.htmlFor=f.id=`mdbase-note-${c}`;let p=u.createDiv({cls:"mdbase-inline-error",attr:{"aria-live":"polite"}});f.addEventListener("input",()=>{this.readInputs(),this.suggestPath()}),f.addEventListener("change",()=>{this.readInputs(),this.suggestPath()}),this.inputs.set(c,{input:f,definition:l,error:p})}let i=this.contentEl.createDiv({cls:"mdbase-form-row"}),s=i.createEl("label",{text:"Location"});this.pathInput=i.createEl("input",{type:"text"}),s.htmlFor=this.pathInput.id="mdbase-note-location",this.pathInput.addEventListener("input",()=>{this.customPath=!0,this.problem.textContent=""});let o=i.createEl("button",{text:"Use suggested location"});o.onclick=()=>{this.customPath=!1,this.suggestPath()},this.problem=this.contentEl.createDiv({cls:"mdbase-inline-error",attr:{role:"alert"}});let a=this.contentEl.createDiv({cls:"modal-button-container"});a.createEl("button",{text:"Cancel"}).onclick=()=>{this.creating||this.close()},this.submit=a.createEl("button",{text:"Create note",cls:"mod-cta"}),this.submit.onclick=()=>void this.save(),this.suggestPath(),this.inputs.values().next().value?.input.focus()}readInputs(){let t=!0;for(let[n,{input:i,definition:s,error:o}]of this.inputs){o.textContent="";try{if(!i.value.trim()){if(delete this.frontmatter[n],s.required)throw new Error("Required");continue}let a=s.type==="boolean"?[!0,!1]:s.values??[];this.frontmatter[n]=["boolean","enum"].includes(s.type??"")?a[Number(i.value)]:Sc(i.value,s)}catch(a){t=!1,o.textContent=a instanceof Error?a.message:String(a)}}return t}async suggestPath(){let t=++this.suggestionVersion;try{let n=await Op(this.app.vault,this.type,this.frontmatter);!this.dismissed&&t===this.suggestionVersion&&!this.customPath&&(this.pathInput.value=n)}catch(n){!this.dismissed&&t===this.suggestionVersion&&(this.problem.textContent=String(n))}}async save(){if(!(this.creating||!this.readInputs()))try{let t=zR(this.pathInput.value);if(yt(t,this.config))throw new Error("Choose a location included in this collection, not a definition or excluded folder.");if(this.app.vault.getAbstractFileByPath(t))throw new Error("A file already exists at this location. Choose another path.");let n=[...this.types.values()].flatMap(i=>i.name===this.type.name||this.type.extends===i.name?ts(t,this.frontmatter,i):[]);if(n.some(i=>i.severity==="error")){for(let i of n){let s=i.field?this.inputs.get(i.field):void 0;s&&(s.error.textContent=i.message)}throw new Error(n.filter(i=>i.severity==="error").map(i=>i.message).join(" \xB7 "))}this.creating=!0,this.submit.disabled=!0,await this.create(t,structuredClone(this.frontmatter)),this.close()}catch(t){this.problem.textContent=t instanceof Error?t.message:String(t)}finally{this.creating=!1,this.submit.disabled=!1}}onClose(){this.dismissed=!0}};qt();var rs=require("obsidian");var Np=class extends rs.SuggestModal{constructor(t,n,i){super(t);this.resultHandled=!1;this.typeDefs=[...n].sort((s,o)=>s.name.localeCompare(o.name)),this.onResult=i,this.setPlaceholder("Type to search..."),this.setInstructions([{command:"\u2191\u2193",purpose:"navigate"},{command:"\u21B5",purpose:"select"},{command:"esc",purpose:"cancel"}]),this.containerEl.addClass("mdbase-type-picker-modal"),this.titleEl.setText("Select type definition")}getSuggestions(t){let n=t.trim().toLowerCase();return n?this.typeDefs.filter(i=>{let s=i.match?.path_glob??"";return`${i.name} ${i.display_name_key??""} ${i.filePath} ${s}`.toLowerCase().includes(n)}).slice(0,100):this.typeDefs.slice(0,100)}renderSuggestion(t,n){let i=n.createDiv({cls:"mdbase-type-picker-suggestion"});i.createDiv({cls:"mdbase-type-picker-name",text:t.name});let s=i.createDiv({cls:"mdbase-type-picker-meta"});s.createSpan({cls:"mdbase-type-picker-path",text:t.filePath}),s.createSpan({cls:"mdbase-type-picker-count",text:`${Object.keys(t.fields??{}).length} fields`}),t.match?.path_glob&&i.createDiv({cls:"mdbase-type-picker-match",text:`match: ${t.match.path_glob}`})}onChooseSuggestion(t){this.resultHandled=!0,this.onResult({type:"selected",typeDef:t})}onClose(){window.setTimeout(()=>{this.resultHandled||this.onResult({type:"cancelled"})},0),super.onClose()}};function Lp(r,e){return new Promise(t=>{new Np(r,e,i=>{if(i.type==="selected"){t(i.typeDef);return}t(null)}).open()})}var xc=class extends rs.Modal{constructor(){super(...arguments);this.resolve=null;this.settled=!1}confirm(t,n=[]){return new Promise(i=>{this.resolve=i,this.titleEl.setText("Confirm high-impact type changes"),this.contentEl.createEl("p",{text:n.length?`${n.length} existing ${n.length===1?"note":"notes"} would fail validation. Only the type definition will be saved; notes are not changed.`:"These changes may invalidate existing notes. Only the type definition will be saved."});let s=this.contentEl.createEl("ul",{cls:"mdbase-confirm-change-list"});for(let l of t)s.createEl("li",{text:l.summary});if(n.length){let l=this.contentEl.createEl("ul",{cls:"mdbase-confirm-change-list mdbase-confirm-notes"});for(let u of n.slice(0,5))l.createEl("li",{text:u});n.length>5&&l.createEl("li",{text:`${n.length-5} more`})}let o=this.contentEl.createDiv({cls:"modal-button-container"}),a=o.createEl("button",{text:"Keep reviewing"});a.onclick=()=>this.finish(!1);let c=o.createEl("button",{text:"Save high-impact changes"});c.addClass("mod-warning"),c.onclick=()=>this.finish(!0),this.open()})}onClose(){this.settled||this.finish(!1,!1),this.contentEl.empty()}finish(t,n=!0){this.settled||(this.settled=!0,this.resolve?.(t),this.resolve=null,n&&this.close())}},Ec=class extends rs.Modal{constructor(){super(...arguments);this.resolve=null;this.settled=!1}confirm(t,n){return new Promise(i=>{this.resolve=i;let s=[...new Set(n.map(d=>d.path))],o=`${s.length} ${s.length===1?"note":"notes"}`;this.titleEl.setText(`${t} in ${o}?`),this.contentEl.createEl("p",{text:`Only the '${n[0]?.field??"affected"}' frontmatter field changes in each note. Notes that changed since validation are skipped.`});let a=this.contentEl.createEl("ul",{cls:"mdbase-confirm-change-list"});for(let d of s.slice(0,8))a.createEl("li",{text:d});s.length>8&&a.createEl("li",{text:`${s.length-8} more`});let c=this.contentEl.createDiv({cls:"modal-button-container"}),l=c.createEl("button",{text:"Cancel"});l.onclick=()=>this.finish(!1);let u=c.createEl("button",{text:`Update ${o}`});u.addClass("mod-cta"),u.onclick=()=>this.finish(!0),this.open()})}onClose(){this.settled||this.finish(!1,!1),this.contentEl.empty()}finish(t,n=!0){this.settled||(this.settled=!0,this.resolve?.(t),this.resolve=null,n&&this.close())}},Ac=class extends rs.Modal{constructor(){super(...arguments);this.resolve=null;this.settled=!1}choose(t){return new Promise(n=>{this.resolve=n,this.titleEl.setText("Disconnect this vault?"),this.contentEl.createEl("p",{text:`This stops synchronization with ${t}. It does not delete the hosted collection.`}),this.contentEl.createEl("p",{text:"Keep all local files, or remove unchanged synced files. Local edits are kept either way."});let i=this.contentEl.createDiv({cls:"modal-button-container"}),s=i.createEl("button",{text:"Cancel"});s.onclick=()=>this.finish(null);let o=i.createEl("button",{text:"Keep files",cls:"mod-cta"});o.onclick=()=>this.finish("keep");let a=i.createEl("button",{text:"Remove unchanged files"});a.addClass("mod-warning"),a.onclick=()=>this.finish("remove"),this.open()})}onClose(){this.settled||this.finish(null,!1),this.contentEl.empty()}finish(t,n=!0){this.settled||(this.settled=!0,this.resolve?.(t),this.resolve=null,n&&this.close())}};function gw(r){let{app:e}=r,t=()=>r.getMirrorProfile()!==null;r.addCommand({id:"mdbase-open",name:"Open workspace",callback:()=>void r.openWorkspace()}),r.addCommand({id:"mdbase-initialize-collection",name:"Initialize collection",checkCallback:n=>t()||e.vault.getAbstractFileByPath("mdbase.yaml")?!1:(n||WR(r),!0)}),r.addCommand({id:"mdbase-create-type",name:"Create type definition",callback:()=>void r.openWorkspace("types").then(n=>n.createNewType())}),r.addCommand({id:"mdbase-edit-type",name:"Edit type definition",callback:()=>void GR(r)}),r.addCommand({id:"mdbase-create-note-from-type",name:"Create note from type",callback:()=>void Fp(r)}),r.addCommand({id:"mdbase-validate-current-note",name:"Validate current note",checkCallback:n=>{let i=e.workspace.getActiveFile();return!(i instanceof tt.TFile)||i.extension!=="md"?!1:(n||JR(r,i),!0)}}),r.addCommand({id:"mdbase-validate-collection",name:"Validate collection",callback:()=>void r.runCollectionValidation(!0)}),r.addCommand({id:"mdbase-sync-now",name:"Sync now",checkCallback:n=>t()?(n||KR(r),!0):!1}),r.addCommand({id:"mdbase-cancel-sync",name:"Cancel current sync",checkCallback:n=>r.sync.isSyncing()?(n||r.sync.cancel(),!0):!1}),r.addCommand({id:"mdbase-resolve-conflicts",name:"Resolve sync conflicts",checkCallback:n=>!t()||!r.sync.state.status?.conflicts.length?!1:(n||r.openWorkspace("sync").then(i=>i.focusSyncSection("conflicts")),!0)}),r.addCommand({id:"mdbase-reconnect",name:"Reconnect collection",checkCallback:n=>{let i=r.sync.state.problem;return!t()||!i||i.action!=="reauthorize"?!1:(n||r.openWorkspace("sync").then(s=>s.reconnectCollection()),!0)}}),r.addCommand({id:"mdbase-copy-sync-diagnostics",name:"Copy sync diagnostics",checkCallback:n=>t()?(n||r.copySyncDiagnostics(),!0):!1}),r.addCommand({id:"mdbase-note-sync-history",name:"Show sync history for current note",checkCallback:n=>{let i=e.workspace.getActiveFile();return!i||!t()?!1:(n||r.openNoteSyncHistory(i.path),!0)}}),r.registerEvent(e.workspace.on("file-menu",(n,i)=>{!(i instanceof tt.TFile)||!t()||n.addItem(s=>s.setTitle("Sync history").setIcon("history").onClick(()=>r.openNoteSyncHistory(i.path)))}))}async function KR(r){let e=await r.sync.syncNow(),{message:t,problem:n}=r.sync.state;if(e==="needs_review"){let i=r.sync.safety()?.reasons??[];new tt.Notice(`Review before syncing: ${i.join(", ").toLowerCase()||"changes need attention"}.`),await r.openWorkspace("sync")}else e==="busy"?new tt.Notice("A sync is already running."):e==="paused"?new tt.Notice("Sync is paused."):e==="failed"?new tt.Notice(n?.message??(t||"Sync failed.")):t&&new tt.Notice(t)}async function WR(r){r.connectSync.assertLocalAuthorityWritable();let{created:e}=await $o(r.app.vault,{seedNoteType:!1});r.invalidateSchemaCache(),new tt.Notice(e.length?`Initialized mdbase collection: ${e.join(", ")}`:"mdbase collection already initialized.")}async function GR(r){let e=await r.requireConfigAndTypes();if(!e)return;if(e.types.size===0){new tt.Notice("No type definitions found.");return}let t=r.app.workspace.getActiveFile(),n=[];if(t instanceof tt.TFile&&t.extension==="md"){let o=[...e.types.values()].find(a=>a.filePath===t.path);if(o)n=[o];else{let a=Me(await r.app.vault.cachedRead(t));a.error||(n=Ke(t.path,a.frontmatter,e.config,e.types).flatMap(c=>e.types.get(c)??[]))}}let i=n.length===1?n[0]:await Lp(r.app,n.length?n:[...e.types.values()]);if(!i)return;await(await r.openWorkspace("types")).editType(i.filePath)}async function JR(r,e){let t=await r.validateFileAndStore(e,"manual");if(t.length===0){new tt.Notice("No issues in current note.");return}new tt.Notice(`Found ${t.length} issue${t.length===1?"":"s"} in current note.`),(await r.openWorkspace("issues")).showIssuesForPath(e.path)}async function Fp(r,e){r.connectSync.assertLocalAuthorityWritable();let t=await r.requireConfigAndTypes();if(!t)return;if(t.types.size===0){new tt.Notice("No type definitions found.");return}if(r.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access.");let n=e?t.types.get(e):await Lp(r.app,Array.from(t.types.values()));n&&new $c(r.app,n,t.config,t.types,async(i,s)=>{if(r.connectSync.assertLocalAuthorityWritable(),r.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access.");let{createNoteFromType:o}=await Promise.resolve().then(()=>(qt(),mw)),a=await o(r.app.vault,i,s);await r.app.workspace.getLeaf(!0).openFile(a),await r.validateFileAndStore(a,"manual")}).open()}var bw=require("obsidian");qt();function jp(r,e){let t=Me(r);if(t.error)throw new Error(`Invalid frontmatter: ${t.error}`);return YR(t.frontmatter,e)?{content:`--- -${(0,bw.stringifyYaml)(t.frontmatter).trimEnd()} +`}async function VR(r,e,t,n){let i=t.trim(),s=(0,oe.normalizePath)(`${e.settings.types_folder}/${i}.md`);if(await r.adapter.exists(s))throw new Error(`Type already exists: ${s}`);let o=Ip(i,n,e.spec_version);return await r.create(s,o),s}function Op(r,e){let t={},n=e.settings.explicit_type_keys[0]??"type";t[n]=n==="types"?[r.name]:r.name;for(let[i,s]of Object.entries(r.fields)){if(!K(s))continue;let o=s;o.default!==void 0&&(t[i]=De(o.default))}return t}function Dp(r,e){let t=[];for(let[n,i]of Object.entries(r.fields)){if(!K(i))continue;let s=i;s.computed||s.required&&e[n]===void 0&&t.push([n,s])}return t}function xc(r,e){let t=r.trim();switch(e.type??"string"){case"string":case"date":case"datetime":case"time":case"link":case"enum":case"any":return t;case"integer":{let i=Number(t);if(!/^[+-]?\d+$/.test(t)||!Number.isSafeInteger(i))throw new Error("Expected a whole integer");return i}case"number":{let i=Number(t);if(!/^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(t)||!Number.isFinite(i))throw new Error("Expected a finite number");return i}case"boolean":{let i=t.toLowerCase();if(["true","1","yes","y"].includes(i))return!0;if(["false","0","no","n"].includes(i))return!1;throw new Error("Expected boolean input: true/false")}case"list":{if(t.startsWith("[")||/^-\s/.test(t)){let s=(0,oe.parseYaml)(t);if(!Array.isArray(s))throw new Error("Expected a YAML or JSON list");return s}let i=t.split(",").map(s=>s.trim()).filter(s=>s.length>0);return e.items?i.map(s=>xc(s,e.items)):i}case"object":{let i=(0,oe.parseYaml)(t);if(!K(i))throw new Error("Expected YAML object value");return i}case"tags":return t.split(",").map(i=>i.trim()).filter(i=>i.length>0);default:return t}}function Ep(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 HR(r,e){let t=(0,oe.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let n=t.split("/"),i="";for(let s of n)i=i?`${i}/${s}`:s,await r.adapter.exists(i)||await r.createFolder(i)}function zR(r,e){if(!r.path_pattern||r.path_pattern.trim().length===0)return null;let t=(0,oe.normalizePath)(Cp(r.path_pattern,e));return t.endsWith(".md")?t:null}async function Np(r,e,t){let n=zR(e,t),i=hw(e,t),s=n?n.split("/").pop()??n:mw(e,t),o=yn(n||`${i?`${i}/`:""}${s.endsWith(".md")?s:`${s}.md`}`),a=o,c=2;for(;r.getAbstractFileByPath(a);)a=o.replace(/\.md$/,`-${c}.md`),c+=1;return a}async function KR(r,e,t,n=""){let i=yn(e),s=i.lastIndexOf("/");if(s>0&&await HR(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 Lp(r){return wR(r)}var oe,iw,sw,Ap,xo,jr,gR,So,RR,IR,qt=ly(()=>{oe=require("obsidian"),iw=Kn(Qf(),1),sw=Kn(cp(),1),Ap=Kn(vp(),1);rw();xo=class extends Error{constructor(t,n){super(n);this.code=t;this.name="MdbasePathError"}},jr={spec_version:"0.3.0",name:"My mdbase collection",description:"Typed markdown collection",settings:{types_folder:"_types",contracts_folder:"_contracts",explicit_type_keys:["type","types"],exclude:[]}},gR=["_types",".obsidian",".git","node_modules",".trash",".mdbase"],So=null;RR={string:"text",integer:"a whole number",number:"a number",boolean:"true or false",array:"a list",object:"an object",null:"empty"},IR={date:"a date (YYYY-MM-DD)","date-time":"a date and time",time:"a time (HH:MM)",email:"an email address",uri:"a URI"}});var ss=A((AB,Cw)=>{"use strict";var tI="2.0.0",rI=Number.MAX_SAFE_INTEGER||9007199254740991,nI=16,iI=250,sI=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Cw.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:nI,MAX_SAFE_BUILD_LENGTH:iI,MAX_SAFE_INTEGER:rI,RELEASE_TYPES:sI,SEMVER_SPEC_VERSION:tI,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Ao=A((kB,Tw)=>{"use strict";var oI=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};Tw.exports=oI});var os=A((Sr,Rw)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:zp,MAX_SAFE_BUILD_LENGTH:aI,MAX_LENGTH:cI}=ss(),lI=Ao();Sr=Rw.exports={};var dI=Sr.re=[],uI=Sr.safeRe=[],D=Sr.src=[],fI=Sr.safeSrc=[],N=Sr.t={},pI=0,Kp="[a-zA-Z0-9-]",hI=[["\\s",1],["\\d",cI],[Kp,aI]],mI=r=>{for(let[e,t]of hI)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},H=(r,e,t)=>{let n=mI(e),i=pI++;lI(r,i,e),N[r]=i,D[i]=e,fI[i]=n,dI[i]=new RegExp(e,t?"g":void 0),uI[i]=new RegExp(n,t?"g":void 0)};H("NUMERICIDENTIFIER","0|[1-9]\\d*");H("NUMERICIDENTIFIERLOOSE","\\d+");H("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Kp}*`);H("MAINVERSION",`(${D[N.NUMERICIDENTIFIER]})\\.(${D[N.NUMERICIDENTIFIER]})\\.(${D[N.NUMERICIDENTIFIER]})`);H("MAINVERSIONLOOSE",`(${D[N.NUMERICIDENTIFIERLOOSE]})\\.(${D[N.NUMERICIDENTIFIERLOOSE]})\\.(${D[N.NUMERICIDENTIFIERLOOSE]})`);H("PRERELEASEIDENTIFIER",`(?:${D[N.NONNUMERICIDENTIFIER]}|${D[N.NUMERICIDENTIFIER]})`);H("PRERELEASEIDENTIFIERLOOSE",`(?:${D[N.NONNUMERICIDENTIFIER]}|${D[N.NUMERICIDENTIFIERLOOSE]})`);H("PRERELEASE",`(?:-(${D[N.PRERELEASEIDENTIFIER]}(?:\\.${D[N.PRERELEASEIDENTIFIER]})*))`);H("PRERELEASELOOSE",`(?:-?(${D[N.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${D[N.PRERELEASEIDENTIFIERLOOSE]})*))`);H("BUILDIDENTIFIER",`${Kp}+`);H("BUILD",`(?:\\+(${D[N.BUILDIDENTIFIER]}(?:\\.${D[N.BUILDIDENTIFIER]})*))`);H("FULLPLAIN",`v?${D[N.MAINVERSION]}${D[N.PRERELEASE]}?${D[N.BUILD]}?`);H("FULL",`^${D[N.FULLPLAIN]}$`);H("LOOSEPLAIN",`[v=\\s]*${D[N.MAINVERSIONLOOSE]}${D[N.PRERELEASELOOSE]}?${D[N.BUILD]}?`);H("LOOSE",`^${D[N.LOOSEPLAIN]}$`);H("GTLT","((?:<|>)?=?)");H("XRANGEIDENTIFIERLOOSE",`${D[N.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);H("XRANGEIDENTIFIER",`${D[N.NUMERICIDENTIFIER]}|x|X|\\*`);H("XRANGEPLAIN",`[v=\\s]*(${D[N.XRANGEIDENTIFIER]})(?:\\.(${D[N.XRANGEIDENTIFIER]})(?:\\.(${D[N.XRANGEIDENTIFIER]})(?:${D[N.PRERELEASE]})?${D[N.BUILD]}?)?)?`);H("XRANGEPLAINLOOSE",`[v=\\s]*(${D[N.XRANGEIDENTIFIERLOOSE]})(?:\\.(${D[N.XRANGEIDENTIFIERLOOSE]})(?:\\.(${D[N.XRANGEIDENTIFIERLOOSE]})(?:${D[N.PRERELEASELOOSE]})?${D[N.BUILD]}?)?)?`);H("XRANGE",`^${D[N.GTLT]}\\s*${D[N.XRANGEPLAIN]}$`);H("XRANGELOOSE",`^${D[N.GTLT]}\\s*${D[N.XRANGEPLAINLOOSE]}$`);H("COERCEPLAIN",`(^|[^\\d])(\\d{1,${zp}})(?:\\.(\\d{1,${zp}}))?(?:\\.(\\d{1,${zp}}))?`);H("COERCE",`${D[N.COERCEPLAIN]}(?:$|[^\\d])`);H("COERCEFULL",D[N.COERCEPLAIN]+`(?:${D[N.PRERELEASE]})?(?:${D[N.BUILD]})?(?:$|[^\\d])`);H("COERCERTL",D[N.COERCE],!0);H("COERCERTLFULL",D[N.COERCEFULL],!0);H("LONETILDE","(?:~>?)");H("TILDETRIM",`(\\s*)${D[N.LONETILDE]}\\s+`,!0);Sr.tildeTrimReplace="$1~";H("TILDE",`^${D[N.LONETILDE]}${D[N.XRANGEPLAIN]}$`);H("TILDELOOSE",`^${D[N.LONETILDE]}${D[N.XRANGEPLAINLOOSE]}$`);H("LONECARET","(?:\\^)");H("CARETTRIM",`(\\s*)${D[N.LONECARET]}\\s+`,!0);Sr.caretTrimReplace="$1^";H("CARET",`^${D[N.LONECARET]}${D[N.XRANGEPLAIN]}$`);H("CARETLOOSE",`^${D[N.LONECARET]}${D[N.XRANGEPLAINLOOSE]}$`);H("COMPARATORLOOSE",`^${D[N.GTLT]}\\s*(${D[N.LOOSEPLAIN]})$|^$`);H("COMPARATOR",`^${D[N.GTLT]}\\s*(${D[N.FULLPLAIN]})$|^$`);H("COMPARATORTRIM",`(\\s*)${D[N.GTLT]}\\s*(${D[N.LOOSEPLAIN]}|${D[N.XRANGEPLAIN]})`,!0);Sr.comparatorTrimReplace="$1$2$3";H("HYPHENRANGE",`^\\s*(${D[N.XRANGEPLAIN]})\\s+-\\s+(${D[N.XRANGEPLAIN]})\\s*$`);H("HYPHENRANGELOOSE",`^\\s*(${D[N.XRANGEPLAINLOOSE]})\\s+-\\s+(${D[N.XRANGEPLAINLOOSE]})\\s*$`);H("STAR","(<|>)?=?\\s*\\*");H("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");H("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Cc=A((PB,Iw)=>{"use strict";var yI=Object.freeze({loose:!0}),gI=Object.freeze({}),bI=r=>r?typeof r!="object"?yI:r:gI;Iw.exports=bI});var Wp=A((MB,Nw)=>{"use strict";var Ow=/^[0-9]+$/,Dw=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:rDw(e,r);Nw.exports={compareIdentifiers:Dw,rcompareIdentifiers:vI}});var je=A((CB,Fw)=>{"use strict";var Tc=Ao(),{MAX_LENGTH:Lw,MAX_SAFE_INTEGER:Rc}=ss(),{safeRe:Ic,t:Oc}=os(),wI=Cc(),{compareIdentifiers:Gp}=Wp(),_I=(r,e)=>{let t=e.split(".");if(t.length>r.length)return!1;for(let n=0;nLw)throw new TypeError(`version is longer than ${Lw} characters`);Tc("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?Ic[Oc.LOOSE]:Ic[Oc.FULL]);if(!n)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>Rc||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Rc||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Rc||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(Tc("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 Gp(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(Tc("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 Gp(n,i)}while(++t)}inc(e,t,n){if(e.startsWith("pre")){if(!t&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(t){let i=`-${t}`.match(this.options.loose?Ic[Oc.PRERELEASELOOSE]:Ic[Oc.PRERELEASE]);if(!i||i[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,n),this.inc("pre",t,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,n),this.inc("pre",t,n);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let i=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[i];else{let s=this.prerelease.length;for(;--s>=0;)typeof this.prerelease[s]=="number"&&(this.prerelease[s]++,s=-2);if(s===-1){if(t===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(i)}}if(t){let s=[t,i];if(n===!1&&(s=[t]),_I(this.prerelease,t)){let o=this.prerelease[t.split(".").length];isNaN(o)&&(this.prerelease=s)}else this.prerelease=s}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Fw.exports=Jp});var vn=A((TB,qw)=>{"use strict";var jw=je(),SI=(r,e,t=!1)=>{if(r instanceof jw)return r;try{return new jw(r,e)}catch(n){if(!t)return null;throw n}};qw.exports=SI});var Uw=A((RB,Bw)=>{"use strict";var xI=vn(),$I=(r,e)=>{let t=xI(r,e);return t?t.version:null};Bw.exports=$I});var Hw=A((IB,Vw)=>{"use strict";var EI=vn(),AI=(r,e)=>{let t=EI(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};Vw.exports=AI});var Ww=A((OB,Kw)=>{"use strict";var zw=je(),kI=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new zw(r instanceof zw?r.version:r,t).inc(e,n,i).version}catch{return null}};Kw.exports=kI});var Yw=A((DB,Jw)=>{"use strict";var Gw=vn(),PI=(r,e)=>{let t=Gw(r,null,!0),n=Gw(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"};Jw.exports=PI});var Qw=A((NB,Xw)=>{"use strict";var MI=je(),CI=(r,e)=>new MI(r,e).major;Xw.exports=CI});var e_=A((LB,Zw)=>{"use strict";var TI=je(),RI=(r,e)=>new TI(r,e).minor;Zw.exports=RI});var r_=A((FB,t_)=>{"use strict";var II=je(),OI=(r,e)=>new II(r,e).patch;t_.exports=OI});var i_=A((jB,n_)=>{"use strict";var DI=vn(),NI=(r,e)=>{let t=DI(r,e);return t&&t.prerelease.length?t.prerelease:null};n_.exports=NI});var Bt=A((qB,o_)=>{"use strict";var s_=je(),LI=(r,e,t)=>new s_(r,t).compare(new s_(e,t));o_.exports=LI});var c_=A((BB,a_)=>{"use strict";var FI=Bt(),jI=(r,e,t)=>FI(e,r,t);a_.exports=jI});var d_=A((UB,l_)=>{"use strict";var qI=Bt(),BI=(r,e)=>qI(r,e,!0);l_.exports=BI});var Dc=A((VB,f_)=>{"use strict";var u_=je(),UI=(r,e,t)=>{let n=new u_(r,t),i=new u_(e,t);return n.compare(i)||n.compareBuild(i)};f_.exports=UI});var h_=A((HB,p_)=>{"use strict";var VI=Dc(),HI=(r,e)=>r.sort((t,n)=>VI(t,n,e));p_.exports=HI});var y_=A((zB,m_)=>{"use strict";var zI=Dc(),KI=(r,e)=>r.sort((t,n)=>zI(n,t,e));m_.exports=KI});var ko=A((KB,g_)=>{"use strict";var WI=Bt(),GI=(r,e,t)=>WI(r,e,t)>0;g_.exports=GI});var Nc=A((WB,b_)=>{"use strict";var JI=Bt(),YI=(r,e,t)=>JI(r,e,t)<0;b_.exports=YI});var Yp=A((GB,v_)=>{"use strict";var XI=Bt(),QI=(r,e,t)=>XI(r,e,t)===0;v_.exports=QI});var Xp=A((JB,w_)=>{"use strict";var ZI=Bt(),eO=(r,e,t)=>ZI(r,e,t)!==0;w_.exports=eO});var Lc=A((YB,__)=>{"use strict";var tO=Bt(),rO=(r,e,t)=>tO(r,e,t)>=0;__.exports=rO});var Fc=A((XB,S_)=>{"use strict";var nO=Bt(),iO=(r,e,t)=>nO(r,e,t)<=0;S_.exports=iO});var Qp=A((QB,x_)=>{"use strict";var sO=Yp(),oO=Xp(),aO=ko(),cO=Lc(),lO=Nc(),dO=Fc(),uO=(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 sO(r,t,n);case"!=":return oO(r,t,n);case">":return aO(r,t,n);case">=":return cO(r,t,n);case"<":return lO(r,t,n);case"<=":return dO(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};x_.exports=uO});var E_=A((ZB,$_)=>{"use strict";var fO=je(),pO=vn(),{safeRe:jc,t:qc}=os(),hO=(r,e)=>{if(r instanceof fO)return r;if(typeof r=="number"&&(r=String(r)),typeof r!="string")return null;e=e||{};let t=null;if(!e.rtl)t=r.match(e.includePrerelease?jc[qc.COERCEFULL]:jc[qc.COERCE]);else{let c=e.includePrerelease?jc[qc.COERCERTLFULL]:jc[qc.COERCERTL],l;for(;(l=c.exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||l.index+l[0].length!==t.index+t[0].length)&&(t=l),c.lastIndex=l.index+l[1].length+l[2].length;c.lastIndex=-1}if(t===null)return null;let n=t[2],i=t[3]||"0",s=t[4]||"0",o=e.includePrerelease&&t[5]?`-${t[5]}`:"",a=e.includePrerelease&&t[6]?`+${t[6]}`:"";return pO(`${n}.${i}.${s}${o}${a}`,e)};$_.exports=hO});var k_=A((eU,A_)=>{"use strict";var mO=vn(),yO=ss(),gO=je(),bO=(r,e,t)=>{if(!yO.RELEASE_TYPES.includes(e))return null;let n=vO(r,t);return n&&wO(n,e)},vO=(r,e)=>{let t=r instanceof gO?r.version:r;return mO(t,e)},wO=(r,e)=>{if(_O(e))return r.version;switch(r.prerelease=[],e){case"major":r.minor=0,r.patch=0;break;case"minor":r.patch=0;break}return r.format()},_O=r=>r.startsWith("pre");A_.exports=bO});var M_=A((tU,P_)=>{"use strict";var Zp=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}};P_.exports=Zp});var Ut=A((rU,I_)=>{"use strict";var SO=/\s+/g,eh=class r{constructor(e,t){if(t=$O(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof th)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(SO," "),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=>!T_(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&&IO(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(RO,"");let n=((this.options.includePrerelease&&CO)|(this.options.loose&&TO))+":"+e,i=C_.get(n);if(i)return i;let s=this.options.loose,o=s?nt[qe.HYPHENRANGELOOSE]:nt[qe.HYPHENRANGE];e=e.replace(o,HO(this.options.includePrerelease)),be("hyphen replace",e),e=e.replace(nt[qe.COMPARATORTRIM],kO),be("comparator trim",e),e=e.replace(nt[qe.TILDETRIM],PO),be("tilde trim",e),e=e.replace(nt[qe.CARETTRIM],MO),be("caret trim",e);let a=e.split(" ").map(d=>OO(d,this.options)).join(" ").split(/\s+/).map(d=>VO(d,this.options));s&&(a=a.filter(d=>(be("loose invalid filter",d,this.options),!!d.match(nt[qe.COMPARATORLOOSE])))),be("range list",a);let c=new Map,l=a.map(d=>new th(d,this.options));for(let d of l){if(T_(d))return[d];c.set(d.value,d)}c.size>1&&c.has("")&&c.delete("");let u=[...c.values()];return C_.set(n,u),u}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>R_(n,t)&&e.set.some(i=>R_(i,t)&&n.every(s=>i.every(o=>s.intersects(o,t)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new EO(e,this.options)}catch{return!1}for(let t=0;tr.value==="<0.0.0-0",IO=r=>r.value==="",R_=(r,e)=>{let t=!0,n=r.slice(),i=n.pop();for(;t&&n.length;)t=n.every(s=>i.intersects(s,e)),i=n.pop();return t},OO=(r,e)=>(r=r.replace(nt[qe.BUILD],""),be("comp",r,e),r=FO(r,e),be("caret",r),r=NO(r,e),be("tildes",r),r=qO(r,e),be("xrange",r),r=UO(r,e),be("stars",r),r),Te=r=>!r||r.toLowerCase()==="x"||r==="*",DO=(r,e,t)=>Te(r)&&!Te(e)||Te(e)&&t&&!Te(t),NO=(r,e)=>r.trim().split(/\s+/).map(t=>LO(t,e)).join(" "),LO=(r,e)=>{let t=e.loose?nt[qe.TILDELOOSE]:nt[qe.TILDE],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{be("tilde",r,i,s,o,a,c);let l;return Te(s)?l="":Te(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Te(a)?l=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:c?(be("replaceTilde pr",c),l=`>=${s}.${o}.${a}-${c} <${s}.${+o+1}.0-0`):l=`>=${s}.${o}.${a} <${s}.${+o+1}.0-0`,be("tilde return",l),l})},FO=(r,e)=>r.trim().split(/\s+/).map(t=>jO(t,e)).join(" "),jO=(r,e)=>{be("caret",r,e);let t=e.loose?nt[qe.CARETLOOSE]:nt[qe.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{be("caret",r,i,s,o,a,c);let l;return Te(s)?l="":Te(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Te(a)?s==="0"?l=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.0${n} <${+s+1}.0.0-0`:c?(be("replaceCaret pr",c),s==="0"?o==="0"?l=`>=${s}.${o}.${a}-${c} <${s}.${o}.${+a+1}-0`:l=`>=${s}.${o}.${a}-${c} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.${a}-${c} <${+s+1}.0.0-0`):(be("no pr"),s==="0"?o==="0"?l=`>=${s}.${o}.${a} <${s}.${o}.${+a+1}-0`:l=`>=${s}.${o}.${a} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.${a} <${+s+1}.0.0-0`),be("caret return",l),l})},qO=(r,e)=>(be("replaceXRanges",r,e),r.split(/\s+/).map(t=>BO(t,e)).join(" ")),BO=(r,e)=>{r=r.trim();let t=e.loose?nt[qe.XRANGELOOSE]:nt[qe.XRANGE];return r.replace(t,(n,i,s,o,a,c)=>{if(be("xRange",r,n,i,s,o,a,c),DO(s,o,a))return r;let l=Te(s),u=l||Te(o),d=u||Te(a),f=d;return i==="="&&f&&(i=""),c=e.includePrerelease?"-0":"",l?i===">"||i==="<"?n="<0.0.0-0":n="*":i&&f?(u&&(o=0),a=0,i===">"?(i=">=",u?(s=+s+1,o=0,a=0):(o=+o+1,a=0)):i==="<="&&(i="<",u?s=+s+1:o=+o+1),i==="<"&&(c="-0"),n=`${i+s}.${o}.${a}${c}`):u?n=`>=${s}.0.0${c} <${+s+1}.0.0-0`:d&&(n=`>=${s}.${o}.0${c} <${s}.${+o+1}.0-0`),be("xRange return",n),n})},UO=(r,e)=>(be("replaceStars",r,e),r.trim().replace(nt[qe.STAR],"")),VO=(r,e)=>(be("replaceGTE0",r,e),r.trim().replace(nt[e.includePrerelease?qe.GTE0PRE:qe.GTE0],"")),HO=r=>(e,t,n,i,s,o,a,c,l,u,d,f)=>(Te(n)?t="":Te(i)?t=`>=${n}.0.0${r?"-0":""}`:Te(s)?t=`>=${n}.${i}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,Te(l)?c="":Te(u)?c=`<${+l+1}.0.0-0`:Te(d)?c=`<${l}.${+u+1}.0-0`:f?c=`<=${l}.${u}.${d}-${f}`:r?c=`<${l}.${u}.${+d+1}-0`:c=`<=${c}`,`${t} ${c}`.trim()),zO=(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 Po=A((nU,j_)=>{"use strict";var Mo=Symbol("SemVer ANY"),ih=class r{static get ANY(){return Mo}constructor(e,t){if(t=O_(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),nh("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Mo?this.value="":this.value=this.operator+this.semver.version,nh("comp",this)}parse(e){let t=this.options.loose?D_[N_.COMPARATORLOOSE]:D_[N_.COMPARATOR],n=e.match(t);if(!n)throw new TypeError(`Invalid comparator: ${e}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new L_(n[2],this.options.loose):this.semver=Mo}toString(){return this.value}test(e){if(nh("Comparator.test",e,this.options.loose),this.semver===Mo||e===Mo)return!0;if(typeof e=="string")try{e=new L_(e,this.options)}catch{return!1}return rh(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 F_(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new F_(this.value,t).test(e.semver):(t=O_(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("=")||rh(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||rh(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};j_.exports=ih;var O_=Cc(),{safeRe:D_,t:N_}=os(),rh=Qp(),nh=Ao(),L_=je(),F_=Ut()});var Co=A((iU,q_)=>{"use strict";var KO=Ut(),WO=(r,e,t)=>{try{e=new KO(e,t)}catch{return!1}return e.test(r)};q_.exports=WO});var U_=A((sU,B_)=>{"use strict";var GO=Ut(),JO=(r,e)=>new GO(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));B_.exports=JO});var H_=A((oU,V_)=>{"use strict";var YO=je(),XO=Ut(),QO=(r,e,t)=>{let n=null,i=null,s=null;try{s=new XO(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===-1)&&(n=o,i=new YO(n,t))}),n};V_.exports=QO});var K_=A((aU,z_)=>{"use strict";var ZO=je(),eD=Ut(),tD=(r,e,t)=>{let n=null,i=null,s=null;try{s=new eD(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===1)&&(n=o,i=new ZO(n,t))}),n};z_.exports=tD});var J_=A((cU,G_)=>{"use strict";var sh=je(),rD=Ut(),W_=ko(),nD=(r,e)=>{r=new rD(r,e);let t=new sh("0.0.0");if(r.test(t)||(t=new sh("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n{let a=new sh(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||W_(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||W_(t,s))&&(t=s)}return t&&r.test(t)?t:null};G_.exports=nD});var X_=A((lU,Y_)=>{"use strict";var iD=Ut(),sD=(r,e)=>{try{return new iD(r,e).range||"*"}catch{return null}};Y_.exports=sD});var Bc=A((dU,t0)=>{"use strict";var oD=je(),e0=Po(),{ANY:aD}=e0,cD=Ut(),lD=Co(),Q_=ko(),Z_=Nc(),dD=Fc(),uD=Lc(),fD=(r,e,t,n)=>{r=new oD(r,n),e=new cD(e,n);let i,s,o,a,c;switch(t){case">":i=Q_,s=dD,o=Z_,a=">",c=">=";break;case"<":i=Z_,s=uD,o=Q_,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(lD(r,e,n))return!1;for(let l=0;l{p.semver===aD&&(p=new e0(">=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};t0.exports=fD});var n0=A((uU,r0)=>{"use strict";var pD=Bc(),hD=(r,e,t)=>pD(r,e,">",t);r0.exports=hD});var s0=A((fU,i0)=>{"use strict";var mD=Bc(),yD=(r,e,t)=>mD(r,e,"<",t);i0.exports=yD});var c0=A((pU,a0)=>{"use strict";var o0=Ut(),gD=(r,e,t)=>(r=new o0(r,t),e=new o0(e,t),r.intersects(e,t));a0.exports=gD});var d0=A((hU,l0)=>{"use strict";var bD=Co(),vD=Bt();l0.exports=(r,e,t)=>{let n=[],i=null,s=null,o=r.sort((u,d)=>vD(u,d,t));for(let u of o)bD(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 u0=Ut(),ch=Po(),{ANY:oh}=ch,ah=Co(),lh=Bt(),wD=(r,e,t={})=>{if(r===e)return!0;r=new u0(r,t),e=new u0(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let o=SD(i,s,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},_D=[new ch(">=0.0.0-0")],f0=[new ch(">=0.0.0")],SD=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===oh){if(e.length===1&&e[0].semver===oh)return!0;t.includePrerelease?r=_D:r=f0}if(e.length===1&&e[0].semver===oh){if(t.includePrerelease)return!0;e=f0}let n=new Set,i,s;for(let p of r)p.operator===">"||p.operator===">="?i=p0(i,p,t):p.operator==="<"||p.operator==="<="?s=h0(s,p,t):n.add(p.semver);if(n.size>1)return null;let o;if(i&&s){if(o=lh(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&&!ah(p,String(i),t)||s&&!ah(p,String(s),t))return null;for(let h of e)if(!ah(p,String(h),t))return!1;return!0}let a,c,l,u,d=s&&!t.includePrerelease&&s.semver.prerelease.length?s.semver:!1,f=i&&!t.includePrerelease&&i.semver.prerelease.length?i.semver:!1;d&&d.prerelease.length===1&&s.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(let p of e){if(u=u||p.operator===">"||p.operator===">=",l=l||p.operator==="<"||p.operator==="<=",i){if(f&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===f.major&&p.semver.minor===f.minor&&p.semver.patch===f.patch&&(f=!1),p.operator===">"||p.operator===">="){if(a=p0(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=h0(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)},p0=(r,e,t)=>{if(!r)return e;let n=lh(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},h0=(r,e,t)=>{if(!r)return e;let n=lh(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};m0.exports=wD});var w0=A((yU,v0)=>{"use strict";var dh=os(),g0=ss(),xD=je(),b0=Wp(),$D=vn(),ED=Uw(),AD=Hw(),kD=Ww(),PD=Yw(),MD=Qw(),CD=e_(),TD=r_(),RD=i_(),ID=Bt(),OD=c_(),DD=d_(),ND=Dc(),LD=h_(),FD=y_(),jD=ko(),qD=Nc(),BD=Yp(),UD=Xp(),VD=Lc(),HD=Fc(),zD=Qp(),KD=E_(),WD=k_(),GD=Po(),JD=Ut(),YD=Co(),XD=U_(),QD=H_(),ZD=K_(),eN=J_(),tN=X_(),rN=Bc(),nN=n0(),iN=s0(),sN=c0(),oN=d0(),aN=y0();v0.exports={parse:$D,valid:ED,clean:AD,inc:kD,diff:PD,major:MD,minor:CD,patch:TD,prerelease:RD,compare:ID,rcompare:OD,compareLoose:DD,compareBuild:ND,sort:LD,rsort:FD,gt:jD,lt:qD,eq:BD,neq:UD,gte:VD,lte:HD,cmp:zD,coerce:KD,truncate:WD,Comparator:GD,Range:JD,satisfies:YD,toComparators:XD,maxSatisfying:QD,minSatisfying:ZD,minVersion:eN,validRange:tN,outside:rN,gtr:nN,ltr:iN,intersects:sN,simplifyRange:oN,subset:aN,SemVer:xD,re:dh.re,src:dh.src,tokens:dh.t,SEMVER_SPEC_VERSION:g0.SEMVER_SPEC_VERSION,RELEASE_TYPES:g0.RELEASE_TYPES,compareIdentifiers:b0.compareIdentifiers,rcompareIdentifiers:b0.rcompareIdentifiers}});var fj={};dy(fj,{default:()=>Od});module.exports=oE(fj);var It=require("obsidian"),Nd="https://mdbase.dev/contracts/catalog.json",Fs="mdbase.lock.yaml",Dr=".mdbase/obsidian-pack-install.json";function mr(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid contract catalog or type pack.");return r}function Gt(r){if(typeof r!="string"||!r)throw new Error("Missing catalog field.");return r}function py(r){let e=Gt(r);if(!/^sha256:[a-f0-9]{64}$/.test(e))throw new Error("Invalid pack digest.");return e}function Ca(r){let e=Gt(r);if(e.includes("\\")||e.includes(":")||Array.from(e).some(t=>t.charCodeAt(0)<32)||e.split("/").some(t=>!t||t==="."||t===".."||t.startsWith(".")))throw new Error(`Unsafe pack path: ${e}`);return e}async function Pi(r){let e=typeof r=="string"?new TextEncoder().encode(r):r;return`sha256:${Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",e))).map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Ld(r){return Array.isArray(r)?`[${r.map(Ld).join(",")}]`:r&&typeof r=="object"?`{${Object.entries(r).sort(([e],[t])=>et?1:0).map(([e,t])=>`${JSON.stringify(e)}:${Ld(t)}`).join(",")}}`:JSON.stringify(r)}function aE(r){let e=new URL(Gt(r),Nd);if(e.origin!==new URL(Nd).origin||!e.pathname.startsWith("/contracts/"))throw new Error("Pack artifacts must come from the first-party contract catalog.");return e.href}async function cE(){let r=await(0,It.requestUrl)({url:Nd,throw:!1});if(r.status!==200)throw new Error(`Catalog unavailable (${r.status}). Your vault is unchanged. Try again when online.`);if(r.arrayBuffer.byteLength>1024*1024)throw new Error("Contract catalog is too large.");let e=mr(r.json);if(e.catalog_version!==2||!Array.isArray(e.packs))throw new Error("Unsupported contract catalog.");return e.packs.map(t=>{let n=mr(t),i=mr(n.display),s=mr(n.installation);if(!Number.isInteger(n.resource_count)||Number(n.resource_count)<1||Number(n.resource_count)>100)throw new Error("Invalid pack resource count.");return{id:Gt(n.id),version:Gt(n.version),digest:py(n.digest),provision:aE(n.provision),resource_count:Number(n.resource_count),display:{name:Gt(i.name),summary:Gt(i.summary)},installation:{visibility:Gt(s.visibility),recommendation:Gt(s.recommendation),primary_type:s.primary_type==null?null:Gt(s.primary_type),...typeof s.caution=="string"?{caution:s.caution}:{}}}})}async function Wn(r,e){let t=r.vault.getAbstractFileByPath(e);if(t&&!(t instanceof It.TFile))throw new Error(`A folder occupies ${e}.`);return t instanceof It.TFile?r.vault.read(t):null}async function fy(r,e){let t=e.split("/");t.pop();let n="";for(let i of t)n=n?`${n}/${i}`:i,r.vault.getAbstractFileByPath(n)||await r.vault.createFolder(n)}async function lE(r,e){let t=await(0,It.requestUrl)({url:e.provision,throw:!1});if(t.status!==200)throw new Error(`Type pack unavailable (${t.status}).`);if(t.arrayBuffer.byteLength>1024*1024||await Pi(t.arrayBuffer)!==e.digest)throw new Error("The type pack does not match its catalog digest.");return dE(r,e,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t.arrayBuffer)))}async function dE(r,e,t){let n=mr(t),i=mr(n.manifest);if(i.kind!=="mdbase.type-pack"||i.id!==e.id||i.version!==e.version||!Array.isArray(i.resources)||i.resources.length!==e.resource_count||!Array.isArray(n.resources)||n.resources.length!==i.resources.length)throw new Error("The type-pack identity or resources do not match the catalog.");let s=new Map;for(let m of n.resources){let y=mr(m),g=Ca(y.source);if(s.has(g))throw new Error("Duplicate pack source.");let b=Gt(y.document);if(new TextEncoder().encode(b).byteLength>262144)throw new Error("Pack resource is too large.");s.set(g,b)}let o=new Set,a=[],c=[],l=await Wn(r,Fs),u=l?(0,It.parseYaml)(l):{kind:"mdbase.type-pack-lock",lock_version:1,packs:[]};if(u.kind!=="mdbase.type-pack-lock"||u.lock_version!==1||!Array.isArray(u.packs))throw new Error("Existing pack lock cannot be read safely.");let d=u.packs.find(m=>m.id===e.id),f=await Pi(Ld(i));if(d&&(d.version!==e.version||d.digest!==f))throw new Error("This pack is already installed at another revision. Upgrade it with mdbase editor; Obsidian currently supports fresh installs and same-version repair only.");for(let m of i.resources){let y=mr(m),g=Ca(y.source),b=Ca(y.target);if(!["contract","type","schema"].includes(String(y.kind))||!["managed","seed"].includes(String(y.mode))||o.has(b))throw new Error("Invalid pack resource or duplicate target.");let v=y.kind==="type"?"_types/":y.kind==="contract"?"_contracts/":"schemas/";if(!b.startsWith(v))throw new Error(`Unsupported pack target ${b}. Default definition folders are required.`);o.add(b);let S=s.get(g),_=py(y.digest);if(!S||await Pi(S)!==_)throw new Error(`Resource digest mismatch: ${g}`);if(u.packs.some(T=>T.id!==e.id&&T.resources.some($=>$.mode==="managed"&&$.target===b)))throw new Error(`${b} belongs to another installed pack.`);let E=await Wn(r,b),k=d?.resources.find(T=>T.target===b);if(y.mode==="managed"&&E!==null&&await Pi(E)!==_)throw new Error(`${b} already exists with different contents. Nothing was overwritten.`);let x=E===null&&!(y.mode==="seed"&&k)?"create":y.mode==="seed"?"preserve":"unchanged";a.push({path:b,before:E,after:S,action:x}),c.push({kind:y.kind,mode:y.mode,source:g,target:b,digest:_})}let p={id:e.id,version:e.version,digest:f,installed_by:d?.installed_by??"mdbase-obsidian",resources:c},h=`${JSON.stringify({...u,packs:[...u.packs.filter(m=>m.id!==e.id),p].sort((m,y)=>m.id.localeCompare(y.id))},null,2)} +`;return{pack:e,provision:t,lockBefore:l,lockAfter:h,files:a}}async function Fd(r){if(!await r.vault.adapter.exists(Dr))return;let e=mr(JSON.parse(await r.vault.adapter.read(Dr)));if(!Array.isArray(e.created))throw new Error("Invalid pack recovery journal.");if(await Wn(r,Fs)===e.lockAfter){await r.vault.adapter.remove(Dr);return}for(let t of[...e.created].reverse()){let n=mr(t),i=Ca(n.path),s=r.vault.getAbstractFileByPath(i);if(s instanceof It.TFile&&await Pi(await r.vault.read(s))===n.digest)await r.fileManager.trashFile(s);else if(s)throw new Error(`Pack recovery stopped: ${i} changed. Your edits and the journal were preserved.`)}await r.vault.adapter.remove(Dr)}var Dd=new WeakSet;async function uE(r,e,t,n){if(Dd.has(r))throw new Error("Another contract pack is installing. Wait for it to finish.");Dd.add(r);try{await fE(r,e,t,n)}finally{Dd.delete(r)}}async function fE(r,e,t,n){if(t(),await r.vault.adapter.exists(Dr))throw new Error("Recover the previous pack installation before trying again.");if(await Wn(r,Fs)!==e.lockBefore)throw new Error("Pack lock changed. Review again.");for(let s of e.files)if(await Wn(r,s.path)!==s.before)throw new Error(`${s.path} changed. Review again.`);await fy(r,Dr);let i={lockAfter:e.lockAfter,created:[]};await r.vault.adapter.write(Dr,JSON.stringify(i));try{let s=e.files.filter(a=>a.action==="create");n?.(0,s.length);for(let[a,c]of s.entries()){if(t(),await fy(r,c.path),await Wn(r,c.path)!==null)throw new Error(`${c.path} appeared during installation.`);if(i.created.push({path:c.path,digest:await Pi(c.after)}),await r.vault.adapter.write(Dr,JSON.stringify(i)),await r.vault.create(c.path,c.after),await Wn(r,c.path)!==c.after)throw new Error(`${c.path} changed during installation. Recovery will preserve competing edits.`);n?.(a+1,s.length)}t();let o=r.vault.getAbstractFileByPath(Fs);o instanceof It.TFile?await r.vault.process(o,a=>{if(a!==e.lockBefore)throw new Error("Pack lock changed during installation.");return e.lockAfter}):await r.vault.create(Fs,e.lockAfter),await r.vault.adapter.remove(Dr)}catch(s){throw await Fd(r),s}}var Ta=class extends It.Modal{constructor(t,n,i){super(t);this.assertWritable=n;this.installed=i;this.dismissed=!1}onOpen(){this.titleEl.setText("Ready-made types \xB7 mdbase-contracts"),this.load()}async load(){this.contentEl.empty(),this.contentEl.createEl("p",{text:"Loading first-party contract catalog\u2026"});try{let t=await cE();if(this.dismissed)return;this.contentEl.empty(),this.contentEl.createEl("p",{text:"Install standard application contracts plus editable starter types. Nothing grants applications access to your vault. Existing starter types are preserved."});let n=this.contentEl.createEl("details");n.createEl("summary",{text:"Advanced and integration packs"});for(let i of t.filter(s=>s.installation.visibility!=="hidden")){let s=(i.installation.visibility==="default"?this.contentEl:n).createDiv({cls:"mdbase-editor-section"});s.createEl("h3",{text:i.display.name}),s.createDiv({cls:"mdbase-muted",text:`Version ${i.version}`}),s.createEl("p",{text:i.display.summary}),i.installation.caution&&s.createEl("p",{text:i.installation.caution});let o=s.createEl("button",{text:"Review installation"}),a=s.createDiv();o.onclick=()=>{o.disabled=!0,lE(this.app,i).then(c=>{if(this.dismissed)return;a.empty();for(let u of c.files)a.createDiv({text:`${u.action} \xB7 ${u.path}`});let l=a.createEl("button",{text:"Install reviewed pack",cls:"mod-cta"});l.onclick=()=>{l.disabled=!0,uE(this.app,c,this.assertWritable,(u,d)=>{l.textContent=`Installing ${u} of ${d} files\u2026`}).then(async()=>{await this.installed(i.installation.primary_type),this.close()}).catch(u=>{a.createDiv({cls:"mdbase-inline-error",text:String(u)}),l.disabled=!1,l.textContent="Install reviewed pack"})}}).catch(c=>{a.createDiv({cls:"mdbase-inline-error",text:String(c)})}).finally(()=>{o.disabled=!1})}}}catch(t){if(this.dismissed)return;this.contentEl.empty(),this.contentEl.createEl("p",{cls:"mdbase-inline-error",text:String(t)}),this.contentEl.createEl("button",{text:"Retry catalog"}).onclick=()=>void this.load()}}onClose(){this.dismissed=!0}};var Ra=class{constructor(){this.checked=new Set;this.revision=0;this.lastCompletedAt=null;this.completedRevision=-1;this.cancelled=!1;this.progress=null}changed(e){this.revision++,e?this.checked.delete(e):this.checked.clear()}markChecked(e){this.checked.add(e)}isChecked(e){return this.checked.has(e)}summary(e){if(this.progress)return this.progress.phase==="uniqueness"?`Checked ${this.progress.completed} of ${this.progress.total} notes \xB7 checking uniqueness\u2026`:`Checking ${this.progress.completed} of ${this.progress.total} notes\u2026`;let t=e.filter(n=>this.checked.has(n)).length;return this.cancelled?`Validation stopped \xB7 ${t} of ${e.length} notes checked \xB7 results incomplete`:this.lastCompletedAt&&this.completedRevision===this.revision?`Validated ${new Date(this.lastCompletedAt).toLocaleTimeString()} \xB7 ${e.length} notes \xB7 including uniqueness`:this.lastCompletedAt?`Changed since last collection validation \xB7 ${t} of ${e.length} notes checked`:t?`Checked ${t} of ${e.length} notes \xB7 collection uniqueness not checked`:"Not checked yet"}};var rt=require("obsidian");var vw=require("obsidian");qt();function WR(r){let e=r.trim();if(!e||e.startsWith("/")||e.includes("\\")||Array.from(e).some(t=>t.charCodeAt(0)<32)||e.split("/").some(t=>!t||t==="."||t===".."||t.startsWith(".")))throw new Error("Choose a visible, vault-relative note path without .. or empty folders.");return e.endsWith(".md")?e:`${e}.md`}var $c=class extends vw.Modal{constructor(t,n,i,s,o){super(t);this.type=n;this.config=i;this.types=s;this.create=o;this.inputs=new Map;this.customPath=!1;this.suggestionVersion=0;this.creating=!1;this.dismissed=!1;this.frontmatter=Op(n,i)}onOpen(){this.titleEl.setText(`New ${this.type.name}`),this.contentEl.addClass("mdbase-create-note");let t=Dp(this.type,this.frontmatter),n=this.type.display_name_key??"title";!t.some(([c])=>c===n)&&this.frontmatter[n]==null&&t.unshift([n,this.type.fields[n]??{type:"string",description:"Used for the file name."}]);for(let[c,l]of t){let u=this.contentEl.createDiv({cls:"mdbase-form-row"}),d=u.createEl("label",{text:`${c}${l.required?" *":""}`});l.description&&u.createDiv({cls:"mdbase-form-description",text:l.description});let f;if(l.type==="boolean"||l.type==="enum"){let h=u.createEl("select");f=h,h.createEl("option",{value:"",text:"Choose\u2026"}),(l.type==="boolean"?[!0,!1]:l.values??[]).forEach((y,g)=>h.createEl("option",{value:String(g),text:String(y)}))}else if(["object","list","any"].includes(l.type??""))f=u.createEl("textarea"),f.placeholder=l.type==="object"?"YAML object":l.type==="list"?"YAML list or comma-separated values":"Value";else{let h=l.type==="date"?"date":l.type==="datetime"?"datetime-local":l.type==="time"?"time":"text";if(f=u.createEl("input",{type:h}),["integer","number"].includes(l.type??"")&&(f.inputMode="decimal"),l.type==="link"){let m=u.createEl("datalist");m.id=`mdbase-links-${this.inputs.size}`,this.app.vault.getMarkdownFiles().slice(0,500).forEach(y=>m.createEl("option",{value:`[[${y.path.replace(/\.md$/,"")}]]`})),f.setAttr("list",m.id)}}d.htmlFor=f.id=`mdbase-note-${c}`;let p=u.createDiv({cls:"mdbase-inline-error",attr:{"aria-live":"polite"}});f.addEventListener("input",()=>{this.readInputs(),this.suggestPath()}),f.addEventListener("change",()=>{this.readInputs(),this.suggestPath()}),this.inputs.set(c,{input:f,definition:l,error:p})}let i=this.contentEl.createDiv({cls:"mdbase-form-row"}),s=i.createEl("label",{text:"Location"});this.pathInput=i.createEl("input",{type:"text"}),s.htmlFor=this.pathInput.id="mdbase-note-location",this.pathInput.addEventListener("input",()=>{this.customPath=!0,this.problem.textContent=""});let o=i.createEl("button",{text:"Use suggested location"});o.onclick=()=>{this.customPath=!1,this.suggestPath()},this.problem=this.contentEl.createDiv({cls:"mdbase-inline-error",attr:{role:"alert"}});let a=this.contentEl.createDiv({cls:"modal-button-container"});a.createEl("button",{text:"Cancel"}).onclick=()=>{this.creating||this.close()},this.submit=a.createEl("button",{text:"Create note",cls:"mod-cta"}),this.submit.onclick=()=>void this.save(),this.suggestPath(),this.inputs.values().next().value?.input.focus()}readInputs(){let t=!0;for(let[n,{input:i,definition:s,error:o}]of this.inputs){o.textContent="";try{if(!i.value.trim()){if(delete this.frontmatter[n],s.required)throw new Error("Required");continue}let a=s.type==="boolean"?[!0,!1]:s.values??[];this.frontmatter[n]=["boolean","enum"].includes(s.type??"")?a[Number(i.value)]:xc(i.value,s)}catch(a){t=!1,o.textContent=a instanceof Error?a.message:String(a)}}return t}async suggestPath(){let t=++this.suggestionVersion;try{let n=await Np(this.app.vault,this.type,this.frontmatter);!this.dismissed&&t===this.suggestionVersion&&!this.customPath&&(this.pathInput.value=n)}catch(n){!this.dismissed&&t===this.suggestionVersion&&(this.problem.textContent=String(n))}}async save(){if(!(this.creating||!this.readInputs()))try{let t=WR(this.pathInput.value);if(yt(t,this.config))throw new Error("Choose a location included in this collection, not a definition or excluded folder.");if(this.app.vault.getAbstractFileByPath(t))throw new Error("A file already exists at this location. Choose another path.");let n=[...this.types.values()].flatMap(i=>i.name===this.type.name||this.type.extends===i.name?ts(t,this.frontmatter,i):[]);if(n.some(i=>i.severity==="error")){for(let i of n){let s=i.field?this.inputs.get(i.field):void 0;s&&(s.error.textContent=i.message)}throw new Error(n.filter(i=>i.severity==="error").map(i=>i.message).join(" \xB7 "))}this.creating=!0,this.submit.disabled=!0,await this.create(t,structuredClone(this.frontmatter)),this.close()}catch(t){this.problem.textContent=t instanceof Error?t.message:String(t)}finally{this.creating=!1,this.submit.disabled=!1}}onClose(){this.dismissed=!0}};qt();var rs=require("obsidian");var Fp=class extends rs.SuggestModal{constructor(t,n,i){super(t);this.resultHandled=!1;this.typeDefs=[...n].sort((s,o)=>s.name.localeCompare(o.name)),this.onResult=i,this.setPlaceholder("Type to search..."),this.setInstructions([{command:"\u2191\u2193",purpose:"navigate"},{command:"\u21B5",purpose:"select"},{command:"esc",purpose:"cancel"}]),this.containerEl.addClass("mdbase-type-picker-modal"),this.titleEl.setText("Select type definition")}getSuggestions(t){let n=t.trim().toLowerCase();return n?this.typeDefs.filter(i=>{let s=i.match?.path_glob??"";return`${i.name} ${i.display_name_key??""} ${i.filePath} ${s}`.toLowerCase().includes(n)}).slice(0,100):this.typeDefs.slice(0,100)}renderSuggestion(t,n){let i=n.createDiv({cls:"mdbase-type-picker-suggestion"});i.createDiv({cls:"mdbase-type-picker-name",text:t.name});let s=i.createDiv({cls:"mdbase-type-picker-meta"});s.createSpan({cls:"mdbase-type-picker-path",text:t.filePath}),s.createSpan({cls:"mdbase-type-picker-count",text:`${Object.keys(t.fields??{}).length} fields`}),t.match?.path_glob&&i.createDiv({cls:"mdbase-type-picker-match",text:`match: ${t.match.path_glob}`})}onChooseSuggestion(t){this.resultHandled=!0,this.onResult({type:"selected",typeDef:t})}onClose(){window.setTimeout(()=>{this.resultHandled||this.onResult({type:"cancelled"})},0),super.onClose()}};function jp(r,e){return new Promise(t=>{new Fp(r,e,i=>{if(i.type==="selected"){t(i.typeDef);return}t(null)}).open()})}var Ec=class extends rs.Modal{constructor(){super(...arguments);this.resolve=null;this.settled=!1}confirm(t,n=[]){return new Promise(i=>{this.resolve=i,this.titleEl.setText("Confirm high-impact type changes"),this.contentEl.createEl("p",{text:n.length?`${n.length} existing ${n.length===1?"note":"notes"} would fail validation. Only the type definition will be saved; notes are not changed.`:"These changes may invalidate existing notes. Only the type definition will be saved."});let s=this.contentEl.createEl("ul",{cls:"mdbase-confirm-change-list"});for(let l of t)s.createEl("li",{text:l.summary});if(n.length){let l=this.contentEl.createEl("ul",{cls:"mdbase-confirm-change-list mdbase-confirm-notes"});for(let u of n.slice(0,5))l.createEl("li",{text:u});n.length>5&&l.createEl("li",{text:`${n.length-5} more`})}let o=this.contentEl.createDiv({cls:"modal-button-container"}),a=o.createEl("button",{text:"Keep reviewing"});a.onclick=()=>this.finish(!1);let c=o.createEl("button",{text:"Save high-impact changes"});c.addClass("mod-warning"),c.onclick=()=>this.finish(!0),this.open()})}onClose(){this.settled||this.finish(!1,!1),this.contentEl.empty()}finish(t,n=!0){this.settled||(this.settled=!0,this.resolve?.(t),this.resolve=null,n&&this.close())}},Ac=class extends rs.Modal{constructor(){super(...arguments);this.resolve=null;this.settled=!1}confirm(t,n){return new Promise(i=>{this.resolve=i;let s=[...new Set(n.map(d=>d.path))],o=`${s.length} ${s.length===1?"note":"notes"}`;this.titleEl.setText(`${t} in ${o}?`),this.contentEl.createEl("p",{text:`Only the '${n[0]?.field??"affected"}' frontmatter field changes in each note. Notes that changed since validation are skipped.`});let a=this.contentEl.createEl("ul",{cls:"mdbase-confirm-change-list"});for(let d of s.slice(0,8))a.createEl("li",{text:d});s.length>8&&a.createEl("li",{text:`${s.length-8} more`});let c=this.contentEl.createDiv({cls:"modal-button-container"}),l=c.createEl("button",{text:"Cancel"});l.onclick=()=>this.finish(!1);let u=c.createEl("button",{text:`Update ${o}`});u.addClass("mod-cta"),u.onclick=()=>this.finish(!0),this.open()})}onClose(){this.settled||this.finish(!1,!1),this.contentEl.empty()}finish(t,n=!0){this.settled||(this.settled=!0,this.resolve?.(t),this.resolve=null,n&&this.close())}},kc=class extends rs.Modal{constructor(){super(...arguments);this.resolve=null;this.settled=!1}choose(t){return new Promise(n=>{this.resolve=n,this.titleEl.setText("Disconnect this vault?"),this.contentEl.createEl("p",{text:`This stops synchronization with ${t}. It does not delete the hosted collection.`}),this.contentEl.createEl("p",{text:"Keep all local files, or remove unchanged synced files. Local edits are kept either way."});let i=this.contentEl.createDiv({cls:"modal-button-container"}),s=i.createEl("button",{text:"Cancel"});s.onclick=()=>this.finish(null);let o=i.createEl("button",{text:"Keep files",cls:"mod-cta"});o.onclick=()=>this.finish("keep");let a=i.createEl("button",{text:"Remove unchanged files"});a.addClass("mod-warning"),a.onclick=()=>this.finish("remove"),this.open()})}onClose(){this.settled||this.finish(null,!1),this.contentEl.empty()}finish(t,n=!0){this.settled||(this.settled=!0,this.resolve?.(t),this.resolve=null,n&&this.close())}};function ww(r){let{app:e}=r,t=()=>r.getMirrorProfile()!==null;r.addCommand({id:"mdbase-open",name:"Open workspace",callback:()=>void r.openWorkspace()}),r.addCommand({id:"mdbase-initialize-collection",name:"Initialize collection",checkCallback:n=>t()||e.vault.getAbstractFileByPath("mdbase.yaml")?!1:(n||JR(r),!0)}),r.addCommand({id:"mdbase-create-type",name:"Create type definition",callback:()=>void r.openWorkspace("types").then(n=>n.createNewType())}),r.addCommand({id:"mdbase-edit-type",name:"Edit type definition",callback:()=>void YR(r)}),r.addCommand({id:"mdbase-create-note-from-type",name:"Create note from type",callback:()=>void qp(r)}),r.addCommand({id:"mdbase-validate-current-note",name:"Validate current note",checkCallback:n=>{let i=e.workspace.getActiveFile();return!(i instanceof rt.TFile)||i.extension!=="md"?!1:(n||XR(r,i),!0)}}),r.addCommand({id:"mdbase-validate-collection",name:"Validate collection",callback:()=>void r.runCollectionValidation(!0)}),r.addCommand({id:"mdbase-sync-now",name:"Sync now",checkCallback:n=>t()?(n||GR(r),!0):!1}),r.addCommand({id:"mdbase-cancel-sync",name:"Cancel current sync",checkCallback:n=>r.sync.isSyncing()?(n||r.sync.cancel(),!0):!1}),r.addCommand({id:"mdbase-resolve-conflicts",name:"Resolve sync conflicts",checkCallback:n=>!t()||!r.sync.state.status?.conflicts.length?!1:(n||r.openWorkspace("sync").then(i=>i.focusSyncSection("conflicts")),!0)}),r.addCommand({id:"mdbase-reconnect",name:"Reconnect collection",checkCallback:n=>{let i=r.sync.state.problem;return!t()||!i||i.action!=="reauthorize"?!1:(n||r.openWorkspace("sync").then(s=>s.reconnectCollection()),!0)}}),r.addCommand({id:"mdbase-copy-sync-diagnostics",name:"Copy sync diagnostics",checkCallback:n=>t()?(n||r.copySyncDiagnostics(),!0):!1}),r.addCommand({id:"mdbase-note-sync-history",name:"Show sync history for current note",checkCallback:n=>{let i=e.workspace.getActiveFile();return!i||!t()?!1:(n||r.openNoteSyncHistory(i.path),!0)}}),r.registerEvent(e.workspace.on("file-menu",(n,i)=>{!(i instanceof rt.TFile)||!t()||n.addItem(s=>s.setTitle("Sync history").setIcon("history").onClick(()=>r.openNoteSyncHistory(i.path)))}))}async function GR(r){let e=await r.sync.syncNow(),{message:t,problem:n}=r.sync.state;if(e==="needs_review"){let i=r.sync.safety()?.reasons??[];new rt.Notice(`Review before syncing: ${i.join(", ").toLowerCase()||"changes need attention"}.`),await r.openWorkspace("sync")}else e==="busy"?new rt.Notice("A sync is already running."):e==="paused"?new rt.Notice("Sync is paused."):e==="failed"?new rt.Notice(n?.message??(t||"Sync failed.")):t&&new rt.Notice(t)}async function JR(r){r.connectSync.assertLocalAuthorityWritable();let{created:e}=await $o(r.app.vault,{seedNoteType:!1});r.invalidateSchemaCache(),new rt.Notice(e.length?`Initialized mdbase collection: ${e.join(", ")}`:"mdbase collection already initialized.")}async function YR(r){let e=await r.requireConfigAndTypes();if(!e)return;if(e.types.size===0){new rt.Notice("No type definitions found.");return}let t=r.app.workspace.getActiveFile(),n=[];if(t instanceof rt.TFile&&t.extension==="md"){let o=[...e.types.values()].find(a=>a.filePath===t.path);if(o)n=[o];else{let a=Ce(await r.app.vault.cachedRead(t));a.error||(n=Ke(t.path,a.frontmatter,e.config,e.types).flatMap(c=>e.types.get(c)??[]))}}let i=n.length===1?n[0]:await jp(r.app,n.length?n:[...e.types.values()]);if(!i)return;await(await r.openWorkspace("types")).editType(i.filePath)}async function XR(r,e){let t=await r.validateFileAndStore(e,"manual");if(t.length===0){new rt.Notice("No issues in current note.");return}new rt.Notice(`Found ${t.length} issue${t.length===1?"":"s"} in current note.`),(await r.openWorkspace("issues")).showIssuesForPath(e.path)}async function qp(r,e){r.connectSync.assertLocalAuthorityWritable();let t=await r.requireConfigAndTypes();if(!t)return;if(t.types.size===0){new rt.Notice("No type definitions found.");return}if(r.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access.");let n=e?t.types.get(e):await jp(r.app,Array.from(t.types.values()));n&&new $c(r.app,n,t.config,t.types,async(i,s)=>{if(r.connectSync.assertLocalAuthorityWritable(),r.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access.");let{createNoteFromType:o}=await Promise.resolve().then(()=>(qt(),bw)),a=await o(r.app.vault,i,s);await r.app.workspace.getLeaf(!0).openFile(a),await r.validateFileAndStore(a,"manual")}).open()}var _w=require("obsidian");qt();function Bp(r,e){let t=Ce(r);if(t.error)throw new Error(`Invalid frontmatter: ${t.error}`);return QR(t.frontmatter,e)?{content:`--- +${(0,_w.stringifyYaml)(t.frontmatter).trimEnd()} --- -${t.body}`,changed:!0}:{content:r,changed:!1}}function vw(r){if(!r.field)return null;if(["unknown_field","missing_required"].includes(r.code))return/[.[\]]/.test(r.field)?null:[r.field];if(!["schema_additional_properties","schema_required"].includes(r.code))return null;let e=r.details?.instance_path,t=r.details?.property;return typeof e!="string"||typeof t!="string"?null:[...e===""?[]:e.slice(1).split("/").map(n=>n.replace(/~1/g,"/").replace(/~0/g,"~")),t]}function ww(r){return vw(r)?["unknown_field","schema_additional_properties"].includes(r.code)?"Remove field":"Add placeholder":null}function YR(r,e){let t=vw(e);if(!t?.length)return!1;let n=r;for(let a of t.slice(0,-1)){if(!n||typeof n!="object"||!Object.prototype.hasOwnProperty.call(n,a))return!1;n=n[a]}if(!n||typeof n!="object"||Array.isArray(n))return!1;let i=n,s=t[t.length-1],o=Object.prototype.hasOwnProperty.call(i,s);if(["unknown_field","schema_additional_properties"].includes(e.code)){if(!o)return!1;delete i[s]}else{if(o)return!1;Object.defineProperty(i,s,{value:"TODO",enumerable:!0,configurable:!0,writable:!0})}return!0}var L=require("obsidian");var O=class extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name="InteropError"}toPortableError(e){return{code:this.code,message:this.message,...this.details===void 0?{}:{details:this.details},...e===void 0?{}:{retryable:e}}}},xo=class extends Error{status;error;constructor(e,t){super(t.message),this.status=e,this.error=t,this.name="ActionHandlerError"}};var _w=Kn(Yf(),1),Sw=Kn(op(),1);var qp={contract:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/v0.3/data-contract.schema.json",title:"mdbase v0.3 contract frontmatter",type:"object",required:["kind","contract_type","id","version"],properties:{kind:{const:"mdbase.contract"},contract_type:{enum:["record","event","action"]},id:{$ref:"#/$defs/contractId"},version:{$ref:"#/$defs/semanticVersion"},name:{type:"string",minLength:1},description:{type:"string"},record_schema:{$ref:"#/$defs/schemaWrapper"},binding_schema:{$ref:"#/$defs/schemaWrapper"},data_schema:{$ref:"#/$defs/schemaWrapper"},source_schema:{$ref:"#/$defs/schemaWrapper"},input_schema:{$ref:"#/$defs/schemaWrapper"},output_schema:{$ref:"#/$defs/schemaWrapper"},error_schema:{$ref:"#/$defs/schemaWrapper"},provider_schema:{$ref:"#/$defs/schemaWrapper"},behavior:{$ref:"#/$defs/actionBehavior"}},patternProperties:{"^x-[A-Za-z][A-Za-z0-9._:-]{0,127}$":!0},oneOf:[{properties:{contract_type:{const:"record"},record_schema:!0,binding_schema:!0,data_schema:!1,source_schema:!1,input_schema:!1,output_schema:!1,error_schema:!1,provider_schema:!1,behavior:!1},required:["record_schema"]},{properties:{contract_type:{const:"event"},record_schema:!1,binding_schema:!1,data_schema:!0,source_schema:!0,input_schema:!1,output_schema:!1,error_schema:!1,provider_schema:!1,behavior:!1},required:["data_schema"]},{properties:{contract_type:{const:"action"},record_schema:!1,binding_schema:!1,data_schema:!1,source_schema:!1,input_schema:!0,output_schema:!0,error_schema:!0,provider_schema:!0,behavior:!0},required:["input_schema"]}],additionalProperties:!1,$defs:{contractId:{type:"string",minLength:3,maxLength:128,pattern:"^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$"},semanticVersion:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},schemaWrapper:{type:"object",required:["dialect"],properties:{dialect:{const:"json-schema-2020-12"},value:{type:"object"},ref:{type:"string",minLength:1}},oneOf:[{required:["value"],properties:{value:!0,ref:!1}},{required:["ref"],properties:{ref:!0,value:!1}}],additionalProperties:!1},actionBehavior:{type:"object",properties:{idempotency:{enum:["none","optional","required"]},cancellation:{enum:["none","cooperative"]}},additionalProperties:!1}}},profile:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/profile.schema.json",title:"mdbase event and action interoperability profile 0.1",oneOf:[{$ref:"#/$defs/event"},{$ref:"#/$defs/actionRequest"},{$ref:"#/$defs/actionInvocation"},{$ref:"#/$defs/actionOutcome"},{$ref:"#/$defs/actionCancellation"},{$ref:"#/$defs/eventSourceDeclaration"},{$ref:"#/$defs/actionProviderDeclaration"},{$ref:"#/$defs/conformanceClaim"}],$defs:{contractId:{type:"string",minLength:3,maxLength:128,pattern:"^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$"},semanticVersion:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},semanticVersionRequirement:{type:"string",minLength:1,maxLength:128},digest:{type:"string",pattern:"^sha256:[0-9a-f]{64}$"},portableId:{type:"string",minLength:1,maxLength:256,pattern:"^[A-Za-z0-9][A-Za-z0-9._:@/-]*$"},exactContract:{type:"object",required:["id","version","digest"],properties:{id:{$ref:"#/$defs/contractId"},version:{$ref:"#/$defs/semanticVersion"},digest:{$ref:"#/$defs/digest"}},additionalProperties:!1},contractRequirement:{type:"object",required:["id","version"],properties:{id:{$ref:"#/$defs/contractId"},version:{$ref:"#/$defs/semanticVersionRequirement"},digest:{$ref:"#/$defs/digest"}},additionalProperties:!1},implementationIdentity:{type:"object",required:["application","implementation","version"],properties:{application:{$ref:"#/$defs/portableId"},implementation:{$ref:"#/$defs/portableId"},version:{$ref:"#/$defs/semanticVersion"},instance_id:{$ref:"#/$defs/portableId"}},additionalProperties:!1},transportCapabilities:{type:"object",required:["delivery","ordering","cancellation","deadlines"],properties:{delivery:{type:"array",minItems:1,uniqueItems:!0,items:{enum:["ephemeral","at_least_once","durable_cursor","offline_queue"]}},ordering:{type:"array",uniqueItems:!0,items:{enum:["none","source","subject"]}},cancellation:{type:"boolean"},deadlines:{type:"boolean"},provider_discovery:{type:"boolean"},max_payload_bytes:{type:"integer",minimum:1},outcome_retention_seconds:{type:"integer",minimum:0},request_deduplication:{type:"boolean"},cross_process_identity:{type:"boolean"}},additionalProperties:!1},extensionValue:{oneOf:[{type:"null"},{type:"boolean"},{type:"integer"},{type:"number"},{type:"string"}]},event:{title:"mdbase CloudEvents event envelope",type:"object",required:["specversion","id","source","type","time","datacontenttype","dataschema","data","mdbaseprofile","mdbasecontractversion","mdbasecontractdigest","mdbaseapplication","mdbaseimplementation","mdbaseimplementationversion"],properties:{specversion:{const:"1.0"},id:{$ref:"#/$defs/portableId"},source:{type:"string",format:"uri-reference",minLength:1},type:{$ref:"#/$defs/contractId"},time:{type:"string",format:"date-time"},subject:{type:"string",format:"uri-reference",minLength:1},datacontenttype:{const:"application/json"},dataschema:{type:"string",format:"uri",minLength:1},data:!0,mdbaseprofile:{const:"0.1"},mdbasecontractversion:{$ref:"#/$defs/semanticVersion"},mdbasecontractdigest:{$ref:"#/$defs/digest"},mdbaseapplication:{$ref:"#/$defs/portableId"},mdbaseimplementation:{$ref:"#/$defs/portableId"},mdbaseimplementationversion:{$ref:"#/$defs/semanticVersion"},mdbaseinstanceid:{$ref:"#/$defs/portableId"},correlationid:{$ref:"#/$defs/portableId"},causationid:{$ref:"#/$defs/portableId"}},propertyNames:{pattern:"^[a-z0-9]+$"},additionalProperties:{$ref:"#/$defs/extensionValue"}},actionRequest:{title:"mdbase action request",type:"object",required:["kind","profile_version","request_id","contract","caller","created_at","input"],properties:{kind:{const:"mdbase.action.request"},profile_version:{const:"0.1"},request_id:{$ref:"#/$defs/portableId"},contract:{$ref:"#/$defs/contractRequirement"},caller:{$ref:"#/$defs/implementationIdentity"},created_at:{type:"string",format:"date-time"},correlation_id:{$ref:"#/$defs/portableId"},causation_id:{$ref:"#/$defs/portableId"},subject:{type:"string",format:"uri-reference",minLength:1},idempotency_key:{type:"string",minLength:1,maxLength:512},deadline:{type:"string",format:"date-time"},requested_provider:{type:"object",properties:{application:{$ref:"#/$defs/portableId"},implementation:{$ref:"#/$defs/portableId"},instance_id:{$ref:"#/$defs/portableId"}},minProperties:1,additionalProperties:!1},authorization_context:{type:"string",format:"uri-reference",minLength:1},input:!0},additionalProperties:!1},actionInvocation:{title:"mdbase admitted action invocation",type:"object",required:["kind","profile_version","invocation_id","attempt_id","request_id","contract","caller","provider","provider_declaration_digest","handler_id","admitted_at","input"],properties:{kind:{const:"mdbase.action.invocation"},profile_version:{const:"0.1"},invocation_id:{$ref:"#/$defs/portableId"},attempt_id:{$ref:"#/$defs/portableId"},request_id:{$ref:"#/$defs/portableId"},contract:{$ref:"#/$defs/exactContract"},caller:{$ref:"#/$defs/implementationIdentity"},provider:{$ref:"#/$defs/implementationIdentity"},provider_declaration_digest:{$ref:"#/$defs/digest"},handler_id:{$ref:"#/$defs/portableId"},admitted_at:{type:"string",format:"date-time"},correlation_id:{$ref:"#/$defs/portableId"},causation_id:{$ref:"#/$defs/portableId"},subject:{type:"string",format:"uri-reference",minLength:1},idempotency_key:{type:"string",minLength:1,maxLength:512},deadline:{type:"string",format:"date-time"},authorization_context:{type:"string",format:"uri-reference",minLength:1},input:!0},additionalProperties:!1},portableError:{type:"object",required:["code","message"],properties:{code:{enum:["unknown_contract","unsupported_contract_version","contract_digest_conflict","invalid_event_data","invalid_action_input","invalid_action_output","no_provider","ambiguous_provider","requested_provider_unavailable","unauthorized","capability_denied","request_rejected","deadline_exceeded","cancellation_unsupported","cancelled","handler_failure","outcome_indeterminate","transport_unavailable","unsupported_transport_capability"]},message:{type:"string",minLength:1},details:!0,retryable:{type:"boolean"}},additionalProperties:!1},actionOutcome:{title:"mdbase action outcome",type:"object",required:["kind","profile_version","outcome_id","request_id","invocation_id","attempt_id","contract","provider","provider_declaration_digest","status","completed_at"],properties:{kind:{const:"mdbase.action.outcome"},profile_version:{const:"0.1"},outcome_id:{$ref:"#/$defs/portableId"},request_id:{$ref:"#/$defs/portableId"},invocation_id:{$ref:"#/$defs/portableId"},attempt_id:{$ref:"#/$defs/portableId"},contract:{$ref:"#/$defs/exactContract"},provider:{$ref:"#/$defs/implementationIdentity"},provider_declaration_digest:{$ref:"#/$defs/digest"},status:{enum:["succeeded","rejected","failed","cancelled","outcome_indeterminate"]},completed_at:{type:"string",format:"date-time"},output:!0,error:{$ref:"#/$defs/portableError"}},allOf:[{if:{properties:{status:{const:"succeeded"}},required:["status"]},then:{required:["output"],not:{required:["error"]}},else:{required:["error"],not:{required:["output"]}}}],additionalProperties:!1},actionCancellation:{title:"mdbase action cancellation request",type:"object",required:["kind","profile_version","cancellation_id","request_id","caller","requested_at"],properties:{kind:{const:"mdbase.action.cancel"},profile_version:{const:"0.1"},cancellation_id:{$ref:"#/$defs/portableId"},request_id:{$ref:"#/$defs/portableId"},caller:{$ref:"#/$defs/implementationIdentity"},requested_at:{type:"string",format:"date-time"},reason:{type:"string",maxLength:1024}},additionalProperties:!1},eventSourceDeclaration:{title:"mdbase event-source declaration",type:"object",required:["kind","profile_version","declaration_id","declaration_digest","source","contracts"],properties:{kind:{const:"mdbase.event-source"},profile_version:{const:"0.1"},declaration_id:{$ref:"#/$defs/portableId"},declaration_digest:{$ref:"#/$defs/digest"},source:{$ref:"#/$defs/implementationIdentity"},contracts:{type:"array",minItems:1,items:{type:"object",required:["requirement","resolved"],properties:{requirement:{$ref:"#/$defs/contractRequirement"},resolved:{$ref:"#/$defs/exactContract"},binding:!0,ordering:{type:"array",uniqueItems:!0,items:{enum:["none","source","subject"]}}},additionalProperties:!1}}},additionalProperties:!1},actionProviderDeclaration:{title:"mdbase action-provider declaration",type:"object",required:["kind","profile_version","declaration_id","declaration_digest","provider","handlers"],properties:{kind:{const:"mdbase.action-provider"},profile_version:{const:"0.1"},declaration_id:{$ref:"#/$defs/portableId"},declaration_digest:{$ref:"#/$defs/digest"},provider:{$ref:"#/$defs/implementationIdentity"},handlers:{type:"array",minItems:1,items:{type:"object",required:["handler_id","requirement","resolved"],properties:{handler_id:{$ref:"#/$defs/portableId"},requirement:{$ref:"#/$defs/contractRequirement"},resolved:{$ref:"#/$defs/exactContract"},binding:!0,idempotency:{type:"object",required:["mode"],properties:{mode:{enum:["none","request"]},retention_seconds:{type:"integer",minimum:1}},additionalProperties:!1},cancellation:{enum:["none","cooperative"]},max_concurrency:{type:"integer",minimum:1}},additionalProperties:!1}}},additionalProperties:!1},conformanceClaim:{title:"mdbase interoperability conformance claim",type:"object",required:["kind","profile_version","implementation","roles","transport"],properties:{kind:{const:"mdbase.interop.conformance"},profile_version:{const:"0.1"},implementation:{$ref:"#/$defs/implementationIdentity"},roles:{type:"array",minItems:1,uniqueItems:!0,items:{enum:["event_source","event_consumer","action_caller","action_provider","bridge"]}},transport:{$ref:"#/$defs/transportCapabilities"},evidence:{type:"array",items:{type:"object",required:["scenario","result"],properties:{scenario:{type:"string",minLength:1},result:{const:"pass"},uri:{type:"string",format:"uri-reference"}},additionalProperties:!1}}},additionalProperties:!1}}},event:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/event.schema.json",title:"mdbase CloudEvents event envelope",$ref:"profile.schema.json#/$defs/event"},actionRequest:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-request.schema.json",title:"mdbase action request",$ref:"profile.schema.json#/$defs/actionRequest"},actionInvocation:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-invocation.schema.json",title:"mdbase admitted action invocation",$ref:"profile.schema.json#/$defs/actionInvocation"},actionOutcome:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-outcome.schema.json",title:"mdbase action outcome",$ref:"profile.schema.json#/$defs/actionOutcome"},actionCancellation:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-cancellation.schema.json",title:"mdbase action cancellation request",$ref:"profile.schema.json#/$defs/actionCancellation"},eventSourceDeclaration:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/event-source-declaration.schema.json",title:"mdbase event-source declaration",$ref:"profile.schema.json#/$defs/eventSourceDeclaration"},actionProviderDeclaration:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-provider-declaration.schema.json",title:"mdbase action-provider declaration",$ref:"profile.schema.json#/$defs/actionProviderDeclaration"},conformanceClaim:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/conformance-claim.schema.json",title:"mdbase interoperability conformance claim",$ref:"profile.schema.json#/$defs/conformanceClaim"}};var XR=Sw.default;function $w(){return Object.fromEntries(Object.entries(qp).map(([r,e])=>[r,structuredClone(e)]))}function Bp(){let r=new _w.Ajv2020({allErrors:!0,strict:!1,validateFormats:!0});XR(r);let e=$w();r.addSchema(e.profile);for(let[t,n]of Object.entries(e))t!=="profile"&&r.addSchema(n);return r}function Br(r,e){let t=String(qp[e].$id),n=r.getSchema(t);if(!n)throw new Error(`Canonical interoperability schema is unavailable: ${e}`);return n}function bn(r){return(r??[]).map(e=>`${e.instancePath||"/"} ${e.message??e.keyword}`).join("; ")}function _r(r,e){if(!("value"in r))throw new O("contract_digest_conflict",`${e} must be resolved to an inline JSON Schema before runtime registration.`);return structuredClone(r.value)}function xw(r){let e={kind:r.kind,contract_type:r.contract_type,id:r.id,version:r.version};switch(r.contract_type){case"record":e.record_schema=_r(r.record_schema,"record_schema"),r.binding_schema&&(e.binding_schema=_r(r.binding_schema,"binding_schema"));break;case"event":e.data_schema=_r(r.data_schema,"data_schema"),r.source_schema&&(e.source_schema=_r(r.source_schema,"source_schema"));break;case"action":e.input_schema=_r(r.input_schema,"input_schema"),r.output_schema&&(e.output_schema=_r(r.output_schema,"output_schema")),r.error_schema&&(e.error_schema=_r(r.error_schema,"error_schema")),r.provider_schema&&(e.provider_schema=_r(r.provider_schema,"provider_schema")),r.behavior&&(e.behavior=structuredClone(r.behavior));break}return e}async function kc(r){return is(xw(r))}async function is(r){return`sha256:${await QR(Up(r))}`}function Ew(r,e){return{data:ns(r,e.data_schema,`${e.id} data_schema`),...e.source_schema?{source:ns(r,e.source_schema,`${e.id} source_schema`)}:{}}}function Aw(r,e){return{input:ns(r,e.input_schema,`${e.id} input_schema`),...e.output_schema?{output:ns(r,e.output_schema,`${e.id} output_schema`)}:{},...e.error_schema?{error:ns(r,e.error_schema,`${e.id} error_schema`)}:{},...e.provider_schema?{provider:ns(r,e.provider_schema,`${e.id} provider_schema`)}:{}}}function Pc(r,e,t,n){if(!(!r||r(e)))throw new O(t,`${n} failed JSON Schema validation: ${bn(r.errors)}`)}function ns(r,e,t){try{return r.compile(_r(e,t))}catch(n){throw new O("contract_digest_conflict",`${t} could not be compiled: ${n instanceof Error?n.message:String(n)}`)}}function Up(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(Up).join(",")}]`:`{${Object.entries(r).filter(([,t])=>t!==void 0).sort(([t],[n])=>tn?1:0).map(([t,n])=>`${JSON.stringify(t)}:${Up(n)}`).join(",")}}`}async function QR(r){let e=new TextEncoder().encode(r),t=await globalThis.crypto.subtle.digest("SHA-256",e);return[...new Uint8Array(t)].map(n=>n.toString(16).padStart(2,"0")).join("")}var Vr=Kn(g0(),1);var lh={delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},oN=new Set(["specversion","id","source","type","time","subject","datacontenttype","dataschema","data","mdbaseprofile","mdbasecontractversion","mdbasecontractdigest","mdbaseapplication","mdbaseimplementation","mdbaseimplementationversion","mdbaseinstanceid","correlationid","causationid"]),Mo=class{options;profileVersion="0.1";transport;ajv=Bp();contractValidator=Br(this.ajv,"contract");eventValidator=Br(this.ajv,"event");actionRequestValidator=Br(this.ajv,"actionRequest");actionInvocationValidator=Br(this.ajv,"actionInvocation");actionOutcomeValidator=Br(this.ajv,"actionOutcome");eventSourceDeclarationValidator=Br(this.ajv,"eventSourceDeclaration");actionProviderDeclarationValidator=Br(this.ajv,"actionProviderDeclaration");contracts=new Map;clients=new Map;eventSources=new Map;actionProviders=new Map;subscriptions=new Map;activeActions=new Map;completedActions=new Map;admissionLocks=new Map;recentEvents=new Map;authorize;now;idFactory;recentEventLimit;completedRequestLimit;nextSequence=0;disposed=!1;constructor(e={}){this.options=e,this.authorize=e.authorize??(()=>!1),this.now=e.now??(()=>new Date),this.idFactory=e.idFactory??(t=>{this.nextSequence+=1;let n=typeof globalThis.crypto?.randomUUID=="function"?globalThis.crypto.randomUUID():`${this.now().getTime().toString(36)}-${this.nextSequence.toString(36)}`;return`${t}_${n}`}),this.recentEventLimit=Math.max(1,e.recentEventLimit??1e3),this.completedRequestLimit=Math.max(1,e.completedRequestLimit??1e3),this.transport={...lh,...structuredClone(e.transport??{}),delivery:[...e.transport?.delivery??lh.delivery],ordering:[...e.transport?.ordering??lh.ordering]}}connect(e){this.assertActive(),aN(e);let t=this.idFactory("client"),n={identity:structuredClone(e),disposed:!1,sources:new Set,providers:new Set,subscriptions:new Set};return this.clients.set(t,n),{identity:structuredClone(e),registerEventSource:i=>this.registerEventSource(t,i),publishEvent:i=>this.publishEvent(t,i),subscribeEvents:(i,s)=>this.subscribeEvents(t,i,s),registerActionProvider:i=>this.registerActionProvider(t,i),invokeAction:i=>this.invokeAction(t,i),cancelAction:(i,s)=>this.cancelAction(t,i,s),dispose:()=>this.disposeClient(t)}}describe(){return this.assertActive(),{profile_version:"0.1",transport:structuredClone(this.transport),contracts:[...this.contracts.values()].map(({artifact:e,reference:t})=>({artifact:structuredClone(e),reference:structuredClone(t)})).sort((e,t)=>e.reference.id.localeCompare(t.reference.id)||e.reference.version.localeCompare(t.reference.version)),event_sources:[...this.eventSources.values()].map(({declaration:e})=>structuredClone(e)).sort((e,t)=>e.declaration_id.localeCompare(t.declaration_id)),action_providers:[...this.actionProviders.values()].map(({declaration:e})=>structuredClone(e)).sort((e,t)=>e.declaration_id.localeCompare(t.declaration_id))}}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of[...this.clients.keys()])await this.disposeClient(e,!0);this.contracts.clear(),this.recentEvents.clear(),this.completedActions.clear()}}async registerEventSource(e,t){let n=this.requireClient(e);if(t.contracts.length===0)throw new O("request_rejected","An event-source declaration must include a contract.");let i=`${e}:${t.declaration_id}`;if(this.eventSources.has(i))throw new O("request_rejected",`Event-source declaration ${t.declaration_id} is already registered.`);let s=new Map;for(let l of t.contracts){let u=await this.prepareEventContract(l.contract),d=b0(l.requirement,u.reference);if(v0(d,u.reference),await this.assertAuthorized({operation:"register_event_source",principal:n.identity,contract:u.reference}),u.sourceValidator&&!u.sourceValidator(l.binding??{}))throw new O("request_rejected",`${u.reference.id} source binding is invalid: ${bn(u.sourceValidator.errors)}`);let f=Bc(u.reference);if(s.has(f))throw new O("contract_digest_conflict",`Event contract ${f} is repeated by one declaration.`);s.set(f,{contract:u,requirement:d,...l.binding===void 0?{}:{binding:structuredClone(l.binding)},...l.ordering===void 0?{}:{ordering:[...l.ordering]}})}let o={kind:"mdbase.event-source",profile_version:"0.1",declaration_id:t.declaration_id,source:structuredClone(n.identity),contracts:[...s.values()].map(({contract:l,requirement:u,binding:d,ordering:f})=>({requirement:structuredClone(u),resolved:structuredClone(l.reference),...d===void 0?{}:{binding:d},...f===void 0?{}:{ordering:f}}))},a={...o,declaration_digest:await is(o)};wn(this.eventSourceDeclarationValidator,a,"request_rejected","Event-source declaration"),this.commitContracts([...s.values()].map(({contract:l})=>l)),this.eventSources.set(i,{id:i,clientId:e,declaration:structuredClone(a),contracts:new Map([...s.entries()].map(([l,u])=>[l,{contract:u.contract,...u.binding===void 0?{}:{binding:u.binding}}]))}),n.sources.add(i);let c=!0;return{declaration:structuredClone(a),dispose:()=>{c&&(c=!1,this.removeEventSource(i))}}}async publishEvent(e,t){let n=this.requireClient(e),i=Bc(t.contract),s=[...n.sources].map(m=>this.eventSources.get(m)).find(m=>m?.contracts.has(i));if(!s)throw new O("unknown_contract",`This client has not registered event contract ${t.contract.id} ${t.contract.version}.`);let o=s.contracts.get(i)?.contract;if(!o)throw new O("unknown_contract",`Event contract ${i} is unavailable.`);if(t.contract.digest&&t.contract.digest!==o.reference.digest)throw new O("contract_digest_conflict",`Event contract ${i} has a different digest.`);await this.assertAuthorized({operation:"publish_event",principal:n.identity,contract:o.reference,...t.subject===void 0?{}:{subject:t.subject}}),dh(t.data,"invalid_event_data",`Event ${o.reference.id} data`),Pc(o.dataValidator,t.data,"invalid_event_data",`Event ${o.reference.id} data`);let a=t.extensions??{};for(let m of Object.keys(a))if(oN.has(m))throw new O("request_rejected",`Event extension ${m} is reserved.`);let c={...structuredClone(a),specversion:"1.0",id:t.id??this.idFactory("evt"),source:cN(n.identity),type:o.reference.id,time:t.time??this.now().toISOString(),...t.subject===void 0?{}:{subject:t.subject},datacontenttype:"application/json",dataschema:S0(o.reference),data:structuredClone(t.data),mdbaseprofile:"0.1",mdbasecontractversion:o.reference.version,mdbasecontractdigest:o.reference.digest,mdbaseapplication:n.identity.application,mdbaseimplementation:n.identity.implementation,mdbaseimplementationversion:n.identity.version,...n.identity.instance_id===void 0?{}:{mdbaseinstanceid:n.identity.instance_id},...t.correlation_id===void 0?{}:{correlationid:t.correlation_id},...t.causation_id===void 0?{}:{causationid:t.causation_id}};wn(this.eventValidator,c,"invalid_event_data","Event envelope"),uh(this.transport,c),lN(c,o.reference);let l=`${c.source}\0${c.id}`,u=this.recentEvents.get(l);if(u){if(JSON.stringify(u)!==JSON.stringify(c))throw new O("contract_digest_conflict",`Event ${c.source} ${c.id} was reused with different content.`);return{event:structuredClone(u),deliveries:0,duplicate:!0}}this.recentEvents.set(l,structuredClone(c)),_0(this.recentEvents,this.recentEventLimit);let d=[...this.subscriptions.values()].filter(({subscription:m})=>Uc(m.contract,o.reference)),f=await Promise.allSettled(d.map(async m=>await this.isAuthorized({operation:"subscribe_event",principal:m.principal,contract:o.reference,...c.subject===void 0?{}:{subject:c.subject}})?(await m.handler(structuredClone(c)),!0):!1)),p=0;for(let m of f)m.status==="fulfilled"&&m.value?p+=1:m.status==="rejected"&&this.report({severity:"error",code:"event_consumer_failed",message:`An event consumer failed while handling ${c.type}.`,contract:o.reference,cause:m.reason});return{event:structuredClone(c),deliveries:p,duplicate:!1}}async subscribeEvents(e,t,n){let i=this.requireClient(e);fh(t.contract),fN(this.transport,t.require_transport),await this.assertAuthorized({operation:"subscribe_event",principal:i.identity,contract:t.contract});let s=this.idFactory("subscription");this.subscriptions.set(s,{id:s,clientId:e,principal:structuredClone(i.identity),subscription:structuredClone(t),handler:n}),i.subscriptions.add(s);let o=!0;return{dispose:()=>{o&&(o=!1,this.removeSubscription(s))}}}async registerActionProvider(e,t){let n=this.requireClient(e);if(t.handlers.length===0)throw new O("request_rejected","An action-provider declaration must include a handler.");let i=`${e}:${t.declaration_id}`;if(this.actionProviders.has(i))throw new O("request_rejected",`Action-provider declaration ${t.declaration_id} is already registered.`);let s=[],o=new Set;for(let d of t.handlers){if(o.has(d.handler_id))throw new O("request_rejected",`Handler ${d.handler_id} is repeated.`);o.add(d.handler_id);let f=await this.prepareActionContract(d.contract),p=b0(d.requirement,f.reference);if(v0(p,f.reference),await this.assertAuthorized({operation:"register_action_provider",principal:n.identity,contract:f.reference,provider:n.identity}),f.providerValidator&&!f.providerValidator(d.binding??{}))throw new O("request_rejected",`${f.reference.id} provider binding is invalid: ${bn(f.providerValidator.errors)}`);let m=d.contract.behavior?.idempotency??"none";if(d.idempotency?.mode==="request"&&m==="none")throw new O("request_rejected",`${f.reference.id} does not permit request deduplication.`);if(m==="required"&&d.idempotency?.mode!=="request")throw new O("request_rejected",`${f.reference.id} requires a provider with request deduplication.`);let h=d.contract.behavior?.cancellation??"none";if(d.cancellation==="cooperative"&&h!=="cooperative")throw new O("request_rejected",`${f.reference.id} does not declare cooperative cancellation.`);s.push({contract:f,declaration:{handler_id:d.handler_id,requirement:p,resolved:structuredClone(f.reference),...d.binding===void 0?{}:{binding:structuredClone(d.binding)},...d.idempotency===void 0?{}:{idempotency:structuredClone(d.idempotency)},...d.cancellation===void 0?{}:{cancellation:d.cancellation},...d.max_concurrency===void 0?{}:{max_concurrency:d.max_concurrency}},handler:d.handler})}let a={kind:"mdbase.action-provider",profile_version:"0.1",declaration_id:t.declaration_id,provider:structuredClone(n.identity),handlers:s.map(({declaration:d})=>structuredClone(d))},c={...a,declaration_digest:await is(a)};wn(this.actionProviderDeclarationValidator,c,"request_rejected","Action-provider declaration"),this.commitContracts(s.map(({contract:d})=>d));let l=s.map(({contract:d,declaration:f,handler:p})=>({registrationId:i,clientId:e,declaration:structuredClone(c),handlerDeclaration:structuredClone(f),contract:d,handler:p,active:0}));this.actionProviders.set(i,{id:i,clientId:e,declaration:structuredClone(c),handlers:l}),n.providers.add(i);let u=!0;return{declaration:structuredClone(c),dispose:()=>{u&&(u=!1,this.removeActionProvider(i))}}}async invokeAction(e,t){let n=this.requireClient(e);fh(t.contract);let i=t.request_id??this.idFactory("req");this.cleanCompletedActions(),dh(t.input,"invalid_action_input",`Action ${t.contract.id} input`);let s={kind:"mdbase.action.request",profile_version:"0.1",request_id:i,contract:structuredClone(t.contract),caller:structuredClone(n.identity),created_at:t.created_at??this.now().toISOString(),...t.correlation_id===void 0?{}:{correlation_id:t.correlation_id},...t.causation_id===void 0?{}:{causation_id:t.causation_id},...t.subject===void 0?{}:{subject:t.subject},...t.idempotency_key===void 0?{}:{idempotency_key:t.idempotency_key},...t.deadline===void 0?{}:{deadline:t.deadline},...t.requested_provider===void 0?{}:{requested_provider:structuredClone(t.requested_provider)},input:structuredClone(t.input)};wn(this.actionRequestValidator,s,"request_rejected","Action request"),uh(this.transport,s);let o=await this.acquireAdmission(i);try{let a=await is(dN(s)),c=this.activeActions.get(i);if(c){if(w0(e,i,a,c),c.handler.handlerDeclaration.idempotency?.mode!=="request")throw new O("request_rejected",`Action request ${i} is already active without deduplication.`);return structuredClone(await c.promise)}let l=this.completedActions.get(i);if(l){if(w0(e,i,a,l),!l.reusable)throw new O("request_rejected",`Action request ${i} was already completed without deduplication.`);return structuredClone(l.outcome)}if(s.deadline&&new Date(s.deadline).getTime()<=this.now().getTime())throw new O("deadline_exceeded",`Action request ${i} passed its deadline before admission.`);if(s.deadline&&!this.transport.deadlines)throw new O("unsupported_transport_capability","The active transport cannot enforce action deadlines.");let u=this.resolveActionCandidates(s.contract,s.requested_provider);u.length===0&&this.throwResolutionFailure(s.contract,s.requested_provider);let d=[];for(let E of u)await this.isAuthorized({operation:"invoke_action",principal:n.identity,contract:E.contract.reference,provider:E.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}})&&d.push(E);if(d.length===0)throw new O("unauthorized",`No authorized provider can execute ${s.contract.id}.`);if(d.length>1)throw new O("ambiguous_provider",`Action ${s.contract.id} has ${d.length} eligible providers; select one explicitly.`);let f=d[0];if(f.handlerDeclaration.max_concurrency!==void 0&&f.active>=f.handlerDeclaration.max_concurrency)throw new O("request_rejected",`Provider ${f.declaration.provider.implementation} is at capacity.`);if((f.contract.artifact.behavior?.idempotency??"none")==="required"&&!s.idempotency_key)throw new O("request_rejected",`${f.contract.reference.id} requires an idempotency key.`);Pc(f.contract.inputValidator,s.input,"invalid_action_input",`Action ${f.contract.reference.id} input`);let m={operation:"invoke_action",principal:n.identity,contract:f.contract.reference,provider:f.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}},h=await this.options.authorizationContext?.(m),y={kind:"mdbase.action.invocation",profile_version:"0.1",invocation_id:this.idFactory("inv"),attempt_id:this.idFactory("attempt"),request_id:i,contract:structuredClone(f.contract.reference),caller:structuredClone(n.identity),provider:structuredClone(f.declaration.provider),provider_declaration_digest:f.declaration.declaration_digest,handler_id:f.handlerDeclaration.handler_id,admitted_at:this.now().toISOString(),...s.correlation_id===void 0?{}:{correlation_id:s.correlation_id},...s.causation_id===void 0?{}:{causation_id:s.causation_id},...s.subject===void 0?{}:{subject:s.subject},...s.idempotency_key===void 0?{}:{idempotency_key:s.idempotency_key},...s.deadline===void 0?{}:{deadline:s.deadline},...h===void 0?{}:{authorization_context:h},input:structuredClone(s.input)};wn(this.actionInvocationValidator,y,"request_rejected","Action invocation"),await this.options.onInvocation?.(structuredClone(y));let g=new AbortController,b;if(y.deadline){let E=Math.max(0,new Date(y.deadline).getTime()-this.now().getTime());b=setTimeout(()=>g.abort(new O("deadline_exceeded",`Action request ${i} exceeded its deadline.`)),E)}f.active+=1;let v=this.executeAction(f,y,g).finally(()=>{b!==void 0&&clearTimeout(b),f.active=Math.max(0,f.active-1),this.activeActions.delete(i)});this.activeActions.set(i,{clientId:e,requestId:i,requestDigest:a,handler:f,invocation:y,controller:g,promise:v}),o();let S=await v,_=f.handlerDeclaration.idempotency?.retention_seconds??300;return this.completedActions.set(i,{clientId:e,requestDigest:a,outcome:structuredClone(S),reusable:f.handlerDeclaration.idempotency?.mode==="request",expiresAt:this.now().getTime()+_*1e3}),_0(this.completedActions,this.completedRequestLimit),structuredClone(S)}finally{o()}}async executeAction(e,t,n){try{let i=await e.handler(structuredClone(t.input),{invocation:structuredClone(t),signal:n.signal});if(n.signal.aborted){let o=n.signal.reason;return o instanceof O&&o.code==="deadline_exceeded"?this.failureOutcome(t,"failed",o.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}dh(i,"invalid_action_output",`Action ${e.contract.reference.id} output`),Pc(e.contract.outputValidator,i,"invalid_action_output",`Action ${e.contract.reference.id} output`);let s={kind:"mdbase.action.outcome",profile_version:"0.1",outcome_id:this.idFactory("outcome"),request_id:t.request_id,invocation_id:t.invocation_id,attempt_id:t.attempt_id,contract:structuredClone(t.contract),provider:structuredClone(t.provider),provider_declaration_digest:t.provider_declaration_digest,status:"succeeded",completed_at:this.now().toISOString(),output:structuredClone(i)};return wn(this.actionOutcomeValidator,s,"invalid_action_output","Action outcome"),uh(this.transport,s),s}catch(i){if(i instanceof xo)return e.contract.errorValidator&&!e.contract.errorValidator(i.error.details??{})?this.failureOutcome(t,"failed",{code:"handler_failure",message:`Provider returned invalid declared error details: ${bn(e.contract.errorValidator.errors)}`}):this.failureOutcome(t,i.status,i.error);if(i instanceof O)return this.failureOutcome(t,i.code==="cancelled"?"cancelled":i.code==="outcome_indeterminate"?"outcome_indeterminate":"failed",i.toPortableError());if(n.signal.aborted||pN(i)){let s=n.signal.reason;return s instanceof O&&s.code==="deadline_exceeded"?this.failureOutcome(t,"failed",s.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}return this.report({severity:"error",code:"action_handler_failed",message:`Provider ${t.provider.implementation} failed ${t.contract.id}.`,principal:t.provider,contract:t.contract,cause:i}),this.failureOutcome(t,"failed",{code:"handler_failure",message:"The selected provider failed while executing the action."})}}failureOutcome(e,t,n){let i={kind:"mdbase.action.outcome",profile_version:"0.1",outcome_id:this.idFactory("outcome"),request_id:e.request_id,invocation_id:e.invocation_id,attempt_id:e.attempt_id,contract:structuredClone(e.contract),provider:structuredClone(e.provider),provider_declaration_digest:e.provider_declaration_digest,status:t,completed_at:this.now().toISOString(),error:structuredClone(n)};return wn(this.actionOutcomeValidator,i,"invalid_action_output","Action outcome"),i}async cancelAction(e,t,n){let i=this.requireClient(e),s=this.admissionLocks.get(t);s&&await s;let o=this.activeActions.get(t);if(!o){let a=this.completedActions.get(t);if(a&&a.clientId!==e)throw new O("unauthorized",`Action request ${t} belongs to another caller.`);return a?structuredClone(a.outcome):null}if(o.clientId!==e)throw new O("unauthorized",`Action request ${t} belongs to another caller.`);if(await this.assertAuthorized({operation:"cancel_action",principal:i.identity,contract:o.invocation.contract,provider:o.invocation.provider,...o.invocation.subject===void 0?{}:{subject:o.invocation.subject}}),!this.transport.cancellation)throw new O("unsupported_transport_capability","The active transport cannot deliver cancellation.");if(o.handler.handlerDeclaration.cancellation!=="cooperative")throw new O("cancellation_unsupported",`Provider ${o.invocation.provider.implementation} does not support cancellation.`);return o.controller.abort(new O("cancelled",n?.trim()||`Action request ${t} was cancelled.`)),structuredClone(await o.promise)}resolveActionCandidates(e,t){let n=[...this.actionProviders.values()].flatMap(({handlers:s})=>s).filter(({contract:s,declaration:o})=>Uc(e,s.reference)&&uN(t,o.provider)),i=(0,Vr.maxSatisfying)([...new Set(n.map(({contract:s})=>s.reference.version))],e.version,{includePrerelease:!0});return i?n.filter(({contract:s})=>s.reference.version===i).sort((s,o)=>s.declaration.provider.application.localeCompare(o.declaration.provider.application)||s.declaration.provider.implementation.localeCompare(o.declaration.provider.implementation)||(s.declaration.provider.instance_id??"").localeCompare(o.declaration.provider.instance_id??"")||s.handlerDeclaration.handler_id.localeCompare(o.handlerDeclaration.handler_id)):[]}throwResolutionFailure(e,t){let n=[...this.contracts.values()].filter(i=>i.artifact.contract_type==="action"&&i.reference.id===e.id);throw n.length===0?new O("unknown_contract",`Action contract ${e.id} is unknown.`):n.some(({reference:i})=>Uc(e,i))?t?new O("requested_provider_unavailable",`The requested provider is unavailable for ${e.id}.`):new O("no_provider",`No provider is registered for ${e.id}.`):new O("unsupported_contract_version",`No ${e.id} artifact satisfies ${e.version}.`)}async prepareEventContract(e){if(this.assertContractArtifact(e),e.contract_type!=="event")throw new O("unknown_contract",`${e.id} is not an event contract.`);let t={id:e.id,version:e.version,digest:await kc(e)};this.assertNoContractConflict(t);let n=Ew(this.ajv,e);return{artifact:structuredClone(e),reference:t,dataValidator:n.data,...n.source===void 0?{}:{sourceValidator:n.source}}}async prepareActionContract(e){if(this.assertContractArtifact(e),e.contract_type!=="action")throw new O("unknown_contract",`${e.id} is not an action contract.`);let t={id:e.id,version:e.version,digest:await kc(e)};this.assertNoContractConflict(t);let n=Aw(this.ajv,e);return{artifact:structuredClone(e),reference:t,inputValidator:n.input,...n.output===void 0?{}:{outputValidator:n.output},...n.error===void 0?{}:{errorValidator:n.error},...n.provider===void 0?{}:{providerValidator:n.provider}}}assertContractArtifact(e){if(wn(this.contractValidator,e,"contract_digest_conflict",`Contract ${e.id||""}`),!(0,Vr.valid)(e.version))throw new O("unsupported_contract_version",`${e.id} version must be exact SemVer.`)}assertNoContractConflict(e){let t=this.contracts.get(Bc(e));if(t&&t.reference.digest!==e.digest)throw new O("contract_digest_conflict",`Contract ${e.id} ${e.version} conflicts with the registered artifact.`)}commitContracts(e){let t=new Map;for(let n of e){let i=Bc(n.reference),s=t.get(i)??this.contracts.get(i);if(s&&s.reference.digest!==n.reference.digest)throw new O("contract_digest_conflict",`Contract ${n.reference.id} ${n.reference.version} conflicts within the registration.`);t.set(i,n)}for(let[n,i]of t)this.contracts.has(n)||this.contracts.set(n,i)}async disposeClient(e,t=!1){let n=this.clients.get(e);if(!(!n||n.disposed)){n.disposed=!0;for(let i of[...n.subscriptions])this.removeSubscription(i);for(let i of[...n.sources])this.removeEventSource(i);for(let i of[...n.providers])this.removeActionProvider(i);for(let i of[...this.activeActions.values()])i.clientId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new O("cancelled","The caller unloaded.")),i.handler.clientId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new O("cancelled","The provider unloaded."));this.clients.delete(e),t||this.assertActive()}}removeEventSource(e){let t=this.eventSources.get(e);t&&(this.eventSources.delete(e),this.clients.get(t.clientId)?.sources.delete(e))}removeActionProvider(e){let t=this.actionProviders.get(e);if(t){this.actionProviders.delete(e),this.clients.get(t.clientId)?.providers.delete(e);for(let n of this.activeActions.values())n.handler.registrationId===e&&n.handler.handlerDeclaration.cancellation==="cooperative"&&n.controller.abort(new O("cancelled","The provider unloaded."))}}removeSubscription(e){let t=this.subscriptions.get(e);t&&(this.subscriptions.delete(e),this.clients.get(t.clientId)?.subscriptions.delete(e))}requireClient(e){this.assertActive();let t=this.clients.get(e);if(!t||t.disposed)throw new O("transport_unavailable","Interop client is disposed.");return t}assertActive(){if(this.disposed)throw new O("transport_unavailable","Interop bridge is disposed.")}async assertAuthorized(e){if(!await this.isAuthorized(e))throw new O("unauthorized",`${e.operation} is not authorized.`)}async isAuthorized(e){try{return await this.authorize(structuredClone(e))}catch(t){return this.report({severity:"error",code:"authorization_failed",message:`Authorization failed for ${e.operation}.`,principal:e.principal,cause:t}),!1}}cleanCompletedActions(){let e=this.now().getTime();for(let[t,n]of this.completedActions)n.expiresAt<=e&&this.completedActions.delete(t)}async acquireAdmission(e){let t=this.admissionLocks.get(e)??Promise.resolve(),n,i=new Promise(a=>{n=a}),s=t.then(()=>i);this.admissionLocks.set(e,s),await t;let o=!1;return()=>{o||(o=!0,n(),this.admissionLocks.get(e)===s&&this.admissionLocks.delete(e))}}report(e){this.options.onDiagnostic?.(structuredClone(e))}};function wn(r,e,t,n){if(!r(e))throw new O(t,`${n} is invalid: ${bn(r.errors)}`)}function aN(r){for(let[e,t]of Object.entries(r))if(t!==void 0&&(typeof t!="string"||t.length===0||!/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/u.test(t)))throw new O("request_rejected",`Implementation identity ${e} is invalid.`);if(!(0,Vr.valid)(r.version))throw new O("request_rejected","Implementation identity version must be exact SemVer.")}function fh(r){if(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u.test(r.id))throw new O("unknown_contract",`Contract ID ${r.id} is invalid.`);if(!(0,Vr.validRange)(r.version,{includePrerelease:!0}))throw new O("unsupported_contract_version",`Contract requirement ${r.version} is not a SemVer range.`);if(r.digest&&!/^sha256:[0-9a-f]{64}$/u.test(r.digest))throw new O("contract_digest_conflict","Contract digest is invalid.")}function b0(r,e){let t=r??{id:e.id,version:e.version,digest:e.digest};return fh(t),structuredClone(t)}function v0(r,e){if(!Uc(r,e))throw new O("unsupported_contract_version",`${e.id} ${e.version} does not satisfy its implementation requirement.`)}function Uc(r,e){return r.id===e.id&&(0,Vr.satisfies)(e.version,r.version,{includePrerelease:!0})&&(!r.digest||r.digest===e.digest)}function Bc(r){return`${r.id}@${r.version}`}function S0(r){return`urn:mdbase:contract:${r.id}:${r.version}:${r.digest}`}function cN(r){return`urn:mdbase:app:${[r.application,r.implementation,...r.instance_id?[r.instance_id]:[]].map(encodeURIComponent).join(":")}`}function lN(r,e){if(r.type!==e.id||r.mdbasecontractversion!==e.version||r.mdbasecontractdigest!==e.digest||r.dataschema!==S0(e))throw new O("contract_digest_conflict","Event contract evidence is inconsistent.")}function dN(r){let{created_at:e,...t}=r;return t}function w0(r,e,t,n){if(n.clientId!==r)throw new O("unauthorized",`Action request ${e} belongs to another caller.`);if(n.requestDigest!==t)throw new O("request_rejected",`Action request ${e} was reused with different content.`)}function dh(r,e,t){let n=new Set,i=(s,o)=>{if(!(s===null||typeof s=="boolean"||typeof s=="string")){if(typeof s=="number"){if(Number.isFinite(s))return;throw new O(e,`${t}${o} must be a finite JSON number.`)}if(typeof s!="object")throw new O(e,`${t}${o} is not a JSON value.`);if(n.has(s))throw new O(e,`${t}${o} contains a cycle.`);if(n.add(s),Array.isArray(s))s.forEach((a,c)=>i(a,`${o}/${c}`));else{let a=Object.getPrototypeOf(s);if(a!==Object.prototype&&a!==null)throw new O(e,`${t}${o} must be a plain JSON object.`);for(let[c,l]of Object.entries(s))i(l,`${o}/${c}`)}n.delete(s)}};i(r,"")}function uh(r,e){if(r.max_payload_bytes===void 0)return;let t=JSON.stringify(e),n=new TextEncoder().encode(t).byteLength;if(n>r.max_payload_bytes)throw new O("unsupported_transport_capability",`The portable envelope is ${n} bytes; the active transport allows ${r.max_payload_bytes}.`)}function uN(r,e){return r?(r.application===void 0||r.application===e.application)&&(r.implementation===void 0||r.implementation===e.implementation)&&(r.instance_id===void 0||r.instance_id===e.instance_id):!0}function fN(r,e){if(e){if(e.delivery?.some(t=>!r.delivery.includes(t)))throw new O("unsupported_transport_capability","The active transport lacks a required delivery capability.");if(e.ordering?.some(t=>!r.ordering.includes(t)))throw new O("unsupported_transport_capability","The active transport lacks a required ordering capability.");for(let t of["cancellation","deadlines","provider_discovery","request_deduplication","cross_process_identity"])if(e[t]===!0&&r[t]!==!0)throw new O("unsupported_transport_capability",`The active transport lacks ${t}.`);if(e.max_payload_bytes!==void 0&&(r.max_payload_bytes===void 0||r.max_payload_bytese;){let t=r.keys().next().value;if(t===void 0)return;r.delete(t)}}function pN(r){return r instanceof Error&&r.name==="AbortError"}var Vc=class{constructor(e,t){this.app=e;this.profileVersion="0.1";this.bridge=new Mo({authorize:()=>t(),transport:{delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},onDiagnostic:n=>{(n.severity==="error"?console.error:console.warn)(`[mdbase/interop] ${n.code}: ${n.message}`,n.cause??"")}}),this.transport=this.bridge.describe().transport}connect(e){let t=e.manifest?.id,n=e.manifest?.version;if(!t||!n)throw new Error("Only a loaded Obsidian plugin with manifest identity can connect to mdbase interop.");let i=this.app.plugins;if(!i||i.getPlugin(t)!==e)throw new Error(`Obsidian plugin ${t} is not the active loaded instance.`);return this.bridge.connect({application:t,implementation:`${t}.obsidian`,version:n})}describe(){return this.bridge.describe()}dispose(){return this.bridge.dispose()}};qt();var z=require("obsidian"),ix=Kn(gp(),1);var Hc=Symbol.for("yaml.alias"),zc=Symbol.for("yaml.document"),Zt=Symbol.for("yaml.map"),ph=Symbol.for("yaml.pair"),At=Symbol.for("yaml.scalar"),Hr=Symbol.for("yaml.seq"),nt=Symbol.for("yaml.node.type"),er=r=>!!r&&typeof r=="object"&&r[nt]===Hc,$r=r=>!!r&&typeof r=="object"&&r[nt]===zc,tr=r=>!!r&&typeof r=="object"&&r[nt]===Zt,te=r=>!!r&&typeof r=="object"&&r[nt]===ph,G=r=>!!r&&typeof r=="object"&&r[nt]===At,rr=r=>!!r&&typeof r=="object"&&r[nt]===Hr;function ae(r){if(r&&typeof r=="object")switch(r[nt]){case Zt:case Hr:return!0}return!1}function ne(r){if(r&&typeof r=="object")switch(r[nt]){case Hc:case Zt:case At:case Hr:return!0}return!1}var Kc=r=>(G(r)||ae(r))&&!!r.anchor;var gt=Symbol("break visit"),$0=Symbol("skip children"),xr=Symbol("remove node");function Er(r,e){let t=x0(e);$r(r)?as(null,r.contents,t,Object.freeze([r]))===xr&&(r.contents=null):as(null,r,t,Object.freeze([]))}Er.BREAK=gt;Er.SKIP=$0;Er.REMOVE=xr;function as(r,e,t,n){let i=E0(r,e,t,n);if(ne(i)||te(i))return A0(r,n,i),as(r,i,t,n);if(typeof i!="symbol"){if(ae(e)){n=Object.freeze(n.concat(e));for(let s=0;sr.replace(/[!,[\]{}]/g,e=>hN[e]),Ar=class r{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},r.defaultYaml,e),this.tags=Object.assign({},r.defaultTags,t)}clone(){let e=new r(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new r(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:r.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},r.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:r.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},r.defaultTags),this.atNextDocument=!1);let n=e.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[s,o]=n;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[s]=n;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return t(6,`Unsupported YAML version ${s}`,o),!1}}default:return t(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}let[,n,i]=e.match(/^(.*!)([^!]*)$/s);i||t(`The ${e} tag has no suffix`);let s=this.tags[n];if(s)try{return s+decodeURIComponent(i)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+mN(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),i;if(e&&n.length>0&&ne(e.contents)){let s={};Er(e.contents,(o,a)=>{ne(a)&&a.tag&&(s[a.tag]=!0)}),i=Object.keys(s)}else i=[];for(let[s,o]of n)s==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(o)))&&t.push(`%TAG ${s} ${o}`);return t.join(` -`)}};Ar.defaultYaml={explicit:!1,version:"1.2"};Ar.defaultTags={"!!":"tag:yaml.org,2002:"};function Gc(r){if(/[\x00-\x19\s,[\]{}]/.test(r)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(r)}`;throw new Error(t)}return!0}function hh(r){let e=new Set;return Er(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function mh(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function k0(r,e){let t=[],n=new Map,i=null;return{onAnchor:s=>{t.push(s),i??(i=hh(r));let o=mh(e,i);return i.add(o),o},setAnchors:()=>{for(let s of t){let o=n.get(s);if(typeof o=="object"&&o.anchor&&(G(o.node)||ae(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:n}}function _n(r,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,s=n.length;iRe(n,String(i),t));if(r&&typeof r.toJSON=="function"){if(!t||!Kc(r))return r.toJSON(e,t);let n={aliasCount:0,count:1,res:void 0};t.anchors.set(r,n),t.onCreate=s=>{n.res=s,delete t.onCreate};let i=r.toJSON(e,t);return t.onCreate&&t.onCreate(i),i}return typeof r=="bigint"&&!t?.keep?Number(r):r}var Sn=class{constructor(e){Object.defineProperty(this,nt,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:i,reviver:s}={}){if(!$r(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},a=Re(this,"",o);if(typeof i=="function")for(let{count:c,res:l}of o.anchors.values())i(l,c);return typeof s=="function"?_n(s,{"":a},"",a):a}};var zr=class extends Sn{constructor(e){super(Hc),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if(t?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],Er(e,{Node:(s,o)=>{(er(o)||Kc(o))&&n.push(o)}}),t&&(t.aliasResolveCache=n));let i;for(let s of n){if(s===this)break;s.anchor===this.source&&(i=s)}if(i&&t){let{anchors:s,doc:o,maxAliasCount:a}=t,c=s.get(i);if(c||(Re(i,null,t),c=s.get(i)),c?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(a>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=Jc(o,i,s)),c.count*c.aliasCount>a)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}}return i}toJSON(e,t){if(!t)return{source:this.source};let n=this.resolve(t.doc,t);if(!n){let i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(i)}return t.anchors.get(n).res}toString(e,t,n){let i=`*${this.source}`;if(e){if(Gc(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(e.implicitKey)return`${i} `}return i}};function Jc(r,e,t){if(er(e)){let n=e.resolve(r),i=t&&n&&t.get(n);return i?i.count*i.aliasCount:0}else if(ae(e)){let n=0;for(let i of e.items){let s=Jc(r,i,t);s>n&&(n=s)}return n}else if(te(e)){let n=Jc(r,e.key,t),i=Jc(r,e.value,t);return Math.max(n,i)}return 1}var Yc=r=>!r||typeof r!="function"&&typeof r!="object",F=class extends Sn{constructor(e){super(At),this.value=e}toJSON(e,t){return t?.keep?this.value:Re(this.value,e,t)}toString(){return String(this.value)}};F.BLOCK_FOLDED="BLOCK_FOLDED";F.BLOCK_LITERAL="BLOCK_LITERAL";F.PLAIN="PLAIN";F.QUOTE_DOUBLE="QUOTE_DOUBLE";F.QUOTE_SINGLE="QUOTE_SINGLE";var yN="tag:yaml.org,2002:";function gN(r,e,t){if(e){let n=t.filter(s=>s.tag===e),i=n.find(s=>!s.format)??n[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return t.find(n=>n.identify?.(r)&&!n.format)}function Kr(r,e,t){if($r(r)&&(r=r.contents),ne(r))return r;if(te(r)){let d=t.schema[Zt].createNode?.(t.schema,null,t);return d.items.push(r),d}(r instanceof String||r instanceof Number||r instanceof Boolean||typeof BigInt<"u"&&r instanceof BigInt)&&(r=r.valueOf());let{aliasDuplicateObjects:n,onAnchor:i,onTagObj:s,schema:o,sourceObjects:a}=t,c;if(n&&r&&typeof r=="object"){if(c=a.get(r),c)return c.anchor??(c.anchor=i(r)),new zr(c.anchor);c={anchor:null,node:null},a.set(r,c)}e?.startsWith("!!")&&(e=yN+e.slice(2));let l=gN(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let d=new F(r);return c&&(c.node=d),d}l=r instanceof Map?o[Zt]:Symbol.iterator in Object(r)?o[Hr]:o[Zt]}s&&(s(l),delete t.onTagObj);let u=l?.createNode?l.createNode(t.schema,r,t):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(t.schema,r,t):new F(r);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}function To(r,e,t){let n=t;for(let i=e.length-1;i>=0;--i){let s=e[i];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=n,n=o}else n=new Map([[s,n]])}return Kr(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:r,sourceObjects:new Map})}var ds=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,ls=class extends Sn{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(n=>ne(n)||te(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(ds(e))this.add(t);else{let[n,...i]=e,s=this.get(n,!0);if(ae(s))s.addIn(i,t);else if(s===void 0&&this.schema)this.set(n,To(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let i=this.get(t,!0);if(ae(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...i]=e,s=this.get(n,!0);return i.length===0?!t&&G(s)?s.value:s:ae(s)?s.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!te(t))return!1;let n=t.value;return n==null||e&&G(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let i=this.get(t,!0);return ae(i)?i.hasIn(n):!1}setIn(e,t){let[n,...i]=e;if(i.length===0)this.set(n,t);else{let s=this.get(n,!0);if(ae(s))s.setIn(i,t);else if(s===void 0&&this.schema)this.set(n,To(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};var P0=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function Vt(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var kr=(r,e,t)=>r.endsWith(` +${t.body}`,changed:!0}:{content:r,changed:!1}}function Sw(r){if(!r.field)return null;if(["unknown_field","missing_required"].includes(r.code))return/[.[\]]/.test(r.field)?null:[r.field];if(!["schema_additional_properties","schema_required"].includes(r.code))return null;let e=r.details?.instance_path,t=r.details?.property;return typeof e!="string"||typeof t!="string"?null:[...e===""?[]:e.slice(1).split("/").map(n=>n.replace(/~1/g,"/").replace(/~0/g,"~")),t]}function xw(r){return Sw(r)?["unknown_field","schema_additional_properties"].includes(r.code)?"Remove field":"Add placeholder":null}function QR(r,e){let t=Sw(e);if(!t?.length)return!1;let n=r;for(let a of t.slice(0,-1)){if(!n||typeof n!="object"||!Object.prototype.hasOwnProperty.call(n,a))return!1;n=n[a]}if(!n||typeof n!="object"||Array.isArray(n))return!1;let i=n,s=t[t.length-1],o=Object.prototype.hasOwnProperty.call(i,s);if(["unknown_field","schema_additional_properties"].includes(e.code)){if(!o)return!1;delete i[s]}else{if(o)return!1;Object.defineProperty(i,s,{value:"TODO",enumerable:!0,configurable:!0,writable:!0})}return!0}var L=require("obsidian");var O=class extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name="InteropError"}toPortableError(e){return{code:this.code,message:this.message,...this.details===void 0?{}:{details:this.details},...e===void 0?{}:{retryable:e}}}},Eo=class extends Error{status;error;constructor(e,t){super(t.message),this.status=e,this.error=t,this.name="ActionHandlerError"}};var $w=Kn(Qf(),1),Ew=Kn(cp(),1);var Up={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 ZR=Ew.default;function Aw(){return Object.fromEntries(Object.entries(Up).map(([r,e])=>[r,structuredClone(e)]))}function Vp(){let r=new $w.Ajv2020({allErrors:!0,strict:!1,validateFormats:!0});ZR(r);let e=Aw();r.addSchema(e.profile);for(let[t,n]of Object.entries(e))t!=="profile"&&r.addSchema(n);return r}function qr(r,e){let t=String(Up[e].$id),n=r.getSchema(t);if(!n)throw new Error(`Canonical interoperability schema is unavailable: ${e}`);return n}function bn(r){return(r??[]).map(e=>`${e.instancePath||"/"} ${e.message??e.keyword}`).join("; ")}function _r(r,e){if(!("value"in r))throw new O("contract_digest_conflict",`${e} must be resolved to an inline JSON Schema before runtime registration.`);return structuredClone(r.value)}function kw(r){let e={kind:r.kind,contract_type:r.contract_type,id:r.id,version:r.version};switch(r.contract_type){case"record":e.record_schema=_r(r.record_schema,"record_schema"),r.binding_schema&&(e.binding_schema=_r(r.binding_schema,"binding_schema"));break;case"event":e.data_schema=_r(r.data_schema,"data_schema"),r.source_schema&&(e.source_schema=_r(r.source_schema,"source_schema"));break;case"action":e.input_schema=_r(r.input_schema,"input_schema"),r.output_schema&&(e.output_schema=_r(r.output_schema,"output_schema")),r.error_schema&&(e.error_schema=_r(r.error_schema,"error_schema")),r.provider_schema&&(e.provider_schema=_r(r.provider_schema,"provider_schema")),r.behavior&&(e.behavior=structuredClone(r.behavior));break}return e}async function Pc(r){return is(kw(r))}async function is(r){return`sha256:${await eI(Hp(r))}`}function Pw(r,e){return{data:ns(r,e.data_schema,`${e.id} data_schema`),...e.source_schema?{source:ns(r,e.source_schema,`${e.id} source_schema`)}:{}}}function Mw(r,e){return{input:ns(r,e.input_schema,`${e.id} input_schema`),...e.output_schema?{output:ns(r,e.output_schema,`${e.id} output_schema`)}:{},...e.error_schema?{error:ns(r,e.error_schema,`${e.id} error_schema`)}:{},...e.provider_schema?{provider:ns(r,e.provider_schema,`${e.id} provider_schema`)}:{}}}function Mc(r,e,t,n){if(!(!r||r(e)))throw new O(t,`${n} failed JSON Schema validation: ${bn(r.errors)}`)}function ns(r,e,t){try{return r.compile(_r(e,t))}catch(n){throw new O("contract_digest_conflict",`${t} could not be compiled: ${n instanceof Error?n.message:String(n)}`)}}function Hp(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(Hp).join(",")}]`:`{${Object.entries(r).filter(([,t])=>t!==void 0).sort(([t],[n])=>tn?1:0).map(([t,n])=>`${JSON.stringify(t)}:${Hp(n)}`).join(",")}}`}async function eI(r){let e=new TextEncoder().encode(r),t=await globalThis.crypto.subtle.digest("SHA-256",e);return[...new Uint8Array(t)].map(n=>n.toString(16).padStart(2,"0")).join("")}var Ur=Kn(w0(),1);var uh={delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},cN=new Set(["specversion","id","source","type","time","subject","datacontenttype","dataschema","data","mdbaseprofile","mdbasecontractversion","mdbasecontractdigest","mdbaseapplication","mdbaseimplementation","mdbaseimplementationversion","mdbaseinstanceid","correlationid","causationid"]),To=class{options;profileVersion="0.1";transport;ajv=Vp();contractValidator=qr(this.ajv,"contract");eventValidator=qr(this.ajv,"event");actionRequestValidator=qr(this.ajv,"actionRequest");actionInvocationValidator=qr(this.ajv,"actionInvocation");actionOutcomeValidator=qr(this.ajv,"actionOutcome");eventSourceDeclarationValidator=qr(this.ajv,"eventSourceDeclaration");actionProviderDeclarationValidator=qr(this.ajv,"actionProviderDeclaration");contracts=new Map;clients=new Map;eventSources=new Map;actionProviders=new Map;subscriptions=new Map;activeActions=new Map;completedActions=new Map;admissionLocks=new Map;recentEvents=new Map;authorize;now;idFactory;recentEventLimit;completedRequestLimit;nextSequence=0;disposed=!1;constructor(e={}){this.options=e,this.authorize=e.authorize??(()=>!1),this.now=e.now??(()=>new Date),this.idFactory=e.idFactory??(t=>{this.nextSequence+=1;let n=typeof globalThis.crypto?.randomUUID=="function"?globalThis.crypto.randomUUID():`${this.now().getTime().toString(36)}-${this.nextSequence.toString(36)}`;return`${t}_${n}`}),this.recentEventLimit=Math.max(1,e.recentEventLimit??1e3),this.completedRequestLimit=Math.max(1,e.completedRequestLimit??1e3),this.transport={...uh,...structuredClone(e.transport??{}),delivery:[...e.transport?.delivery??uh.delivery],ordering:[...e.transport?.ordering??uh.ordering]}}connect(e){this.assertActive(),lN(e);let t=this.idFactory("client"),n={identity:structuredClone(e),disposed:!1,sources:new Set,providers:new Set,subscriptions:new Set};return this.clients.set(t,n),{identity:structuredClone(e),registerEventSource:i=>this.registerEventSource(t,i),publishEvent:i=>this.publishEvent(t,i),subscribeEvents:(i,s)=>this.subscribeEvents(t,i,s),registerActionProvider:i=>this.registerActionProvider(t,i),invokeAction:i=>this.invokeAction(t,i),cancelAction:(i,s)=>this.cancelAction(t,i,s),dispose:()=>this.disposeClient(t)}}describe(){return this.assertActive(),{profile_version:"0.1",transport:structuredClone(this.transport),contracts:[...this.contracts.values()].map(({artifact:e,reference:t})=>({artifact:structuredClone(e),reference:structuredClone(t)})).sort((e,t)=>e.reference.id.localeCompare(t.reference.id)||e.reference.version.localeCompare(t.reference.version)),event_sources:[...this.eventSources.values()].map(({declaration:e})=>structuredClone(e)).sort((e,t)=>e.declaration_id.localeCompare(t.declaration_id)),action_providers:[...this.actionProviders.values()].map(({declaration:e})=>structuredClone(e)).sort((e,t)=>e.declaration_id.localeCompare(t.declaration_id))}}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of[...this.clients.keys()])await this.disposeClient(e,!0);this.contracts.clear(),this.recentEvents.clear(),this.completedActions.clear()}}async registerEventSource(e,t){let n=this.requireClient(e);if(t.contracts.length===0)throw new O("request_rejected","An event-source declaration must include a contract.");let i=`${e}:${t.declaration_id}`;if(this.eventSources.has(i))throw new O("request_rejected",`Event-source declaration ${t.declaration_id} is already registered.`);let s=new Map;for(let l of t.contracts){let u=await this.prepareEventContract(l.contract),d=_0(l.requirement,u.reference);if(S0(d,u.reference),await this.assertAuthorized({operation:"register_event_source",principal:n.identity,contract:u.reference}),u.sourceValidator&&!u.sourceValidator(l.binding??{}))throw new O("request_rejected",`${u.reference.id} source binding is invalid: ${bn(u.sourceValidator.errors)}`);let f=Uc(u.reference);if(s.has(f))throw new O("contract_digest_conflict",`Event contract ${f} is repeated by one declaration.`);s.set(f,{contract:u,requirement:d,...l.binding===void 0?{}:{binding:structuredClone(l.binding)},...l.ordering===void 0?{}:{ordering:[...l.ordering]}})}let o={kind:"mdbase.event-source",profile_version:"0.1",declaration_id:t.declaration_id,source:structuredClone(n.identity),contracts:[...s.values()].map(({contract:l,requirement:u,binding:d,ordering:f})=>({requirement:structuredClone(u),resolved:structuredClone(l.reference),...d===void 0?{}:{binding:d},...f===void 0?{}:{ordering:f}}))},a={...o,declaration_digest:await is(o)};wn(this.eventSourceDeclarationValidator,a,"request_rejected","Event-source declaration"),this.commitContracts([...s.values()].map(({contract:l})=>l)),this.eventSources.set(i,{id:i,clientId:e,declaration:structuredClone(a),contracts:new Map([...s.entries()].map(([l,u])=>[l,{contract:u.contract,...u.binding===void 0?{}:{binding:u.binding}}]))}),n.sources.add(i);let c=!0;return{declaration:structuredClone(a),dispose:()=>{c&&(c=!1,this.removeEventSource(i))}}}async publishEvent(e,t){let n=this.requireClient(e),i=Uc(t.contract),s=[...n.sources].map(h=>this.eventSources.get(h)).find(h=>h?.contracts.has(i));if(!s)throw new O("unknown_contract",`This client has not registered event contract ${t.contract.id} ${t.contract.version}.`);let o=s.contracts.get(i)?.contract;if(!o)throw new O("unknown_contract",`Event contract ${i} is unavailable.`);if(t.contract.digest&&t.contract.digest!==o.reference.digest)throw new O("contract_digest_conflict",`Event contract ${i} has a different digest.`);await this.assertAuthorized({operation:"publish_event",principal:n.identity,contract:o.reference,...t.subject===void 0?{}:{subject:t.subject}}),fh(t.data,"invalid_event_data",`Event ${o.reference.id} data`),Mc(o.dataValidator,t.data,"invalid_event_data",`Event ${o.reference.id} data`);let a=t.extensions??{};for(let h of Object.keys(a))if(cN.has(h))throw new O("request_rejected",`Event extension ${h} is reserved.`);let c={...structuredClone(a),specversion:"1.0",id:t.id??this.idFactory("evt"),source:dN(n.identity),type:o.reference.id,time:t.time??this.now().toISOString(),...t.subject===void 0?{}:{subject:t.subject},datacontenttype:"application/json",dataschema:E0(o.reference),data:structuredClone(t.data),mdbaseprofile:"0.1",mdbasecontractversion:o.reference.version,mdbasecontractdigest:o.reference.digest,mdbaseapplication:n.identity.application,mdbaseimplementation:n.identity.implementation,mdbaseimplementationversion:n.identity.version,...n.identity.instance_id===void 0?{}:{mdbaseinstanceid:n.identity.instance_id},...t.correlation_id===void 0?{}:{correlationid:t.correlation_id},...t.causation_id===void 0?{}:{causationid:t.causation_id}};wn(this.eventValidator,c,"invalid_event_data","Event envelope"),ph(this.transport,c),uN(c,o.reference);let l=`${c.source}\0${c.id}`,u=this.recentEvents.get(l);if(u){if(JSON.stringify(u)!==JSON.stringify(c))throw new O("contract_digest_conflict",`Event ${c.source} ${c.id} was reused with different content.`);return{event:structuredClone(u),deliveries:0,duplicate:!0}}this.recentEvents.set(l,structuredClone(c)),$0(this.recentEvents,this.recentEventLimit);let d=[...this.subscriptions.values()].filter(({subscription:h})=>Vc(h.contract,o.reference)),f=await Promise.allSettled(d.map(async h=>await this.isAuthorized({operation:"subscribe_event",principal:h.principal,contract:o.reference,...c.subject===void 0?{}:{subject:c.subject}})?(await h.handler(structuredClone(c)),!0):!1)),p=0;for(let h of f)h.status==="fulfilled"&&h.value?p+=1:h.status==="rejected"&&this.report({severity:"error",code:"event_consumer_failed",message:`An event consumer failed while handling ${c.type}.`,contract:o.reference,cause:h.reason});return{event:structuredClone(c),deliveries:p,duplicate:!1}}async subscribeEvents(e,t,n){let i=this.requireClient(e);hh(t.contract),hN(this.transport,t.require_transport),await this.assertAuthorized({operation:"subscribe_event",principal:i.identity,contract:t.contract});let s=this.idFactory("subscription");this.subscriptions.set(s,{id:s,clientId:e,principal:structuredClone(i.identity),subscription:structuredClone(t),handler:n}),i.subscriptions.add(s);let o=!0;return{dispose:()=>{o&&(o=!1,this.removeSubscription(s))}}}async registerActionProvider(e,t){let n=this.requireClient(e);if(t.handlers.length===0)throw new O("request_rejected","An action-provider declaration must include a handler.");let i=`${e}:${t.declaration_id}`;if(this.actionProviders.has(i))throw new O("request_rejected",`Action-provider declaration ${t.declaration_id} is already registered.`);let s=[],o=new Set;for(let d of t.handlers){if(o.has(d.handler_id))throw new O("request_rejected",`Handler ${d.handler_id} is repeated.`);o.add(d.handler_id);let f=await this.prepareActionContract(d.contract),p=_0(d.requirement,f.reference);if(S0(p,f.reference),await this.assertAuthorized({operation:"register_action_provider",principal:n.identity,contract:f.reference,provider:n.identity}),f.providerValidator&&!f.providerValidator(d.binding??{}))throw new O("request_rejected",`${f.reference.id} provider binding is invalid: ${bn(f.providerValidator.errors)}`);let h=d.contract.behavior?.idempotency??"none";if(d.idempotency?.mode==="request"&&h==="none")throw new O("request_rejected",`${f.reference.id} does not permit request deduplication.`);if(h==="required"&&d.idempotency?.mode!=="request")throw new O("request_rejected",`${f.reference.id} requires a provider with request deduplication.`);let m=d.contract.behavior?.cancellation??"none";if(d.cancellation==="cooperative"&&m!=="cooperative")throw new O("request_rejected",`${f.reference.id} does not declare cooperative cancellation.`);s.push({contract:f,declaration:{handler_id:d.handler_id,requirement:p,resolved:structuredClone(f.reference),...d.binding===void 0?{}:{binding:structuredClone(d.binding)},...d.idempotency===void 0?{}:{idempotency:structuredClone(d.idempotency)},...d.cancellation===void 0?{}:{cancellation:d.cancellation},...d.max_concurrency===void 0?{}:{max_concurrency:d.max_concurrency}},handler:d.handler})}let a={kind:"mdbase.action-provider",profile_version:"0.1",declaration_id:t.declaration_id,provider:structuredClone(n.identity),handlers:s.map(({declaration:d})=>structuredClone(d))},c={...a,declaration_digest:await is(a)};wn(this.actionProviderDeclarationValidator,c,"request_rejected","Action-provider declaration"),this.commitContracts(s.map(({contract:d})=>d));let l=s.map(({contract:d,declaration:f,handler:p})=>({registrationId:i,clientId:e,declaration:structuredClone(c),handlerDeclaration:structuredClone(f),contract:d,handler:p,active:0}));this.actionProviders.set(i,{id:i,clientId:e,declaration:structuredClone(c),handlers:l}),n.providers.add(i);let u=!0;return{declaration:structuredClone(c),dispose:()=>{u&&(u=!1,this.removeActionProvider(i))}}}async invokeAction(e,t){let n=this.requireClient(e);hh(t.contract);let i=t.request_id??this.idFactory("req");this.cleanCompletedActions(),fh(t.input,"invalid_action_input",`Action ${t.contract.id} input`);let s={kind:"mdbase.action.request",profile_version:"0.1",request_id:i,contract:structuredClone(t.contract),caller:structuredClone(n.identity),created_at:t.created_at??this.now().toISOString(),...t.correlation_id===void 0?{}:{correlation_id:t.correlation_id},...t.causation_id===void 0?{}:{causation_id:t.causation_id},...t.subject===void 0?{}:{subject:t.subject},...t.idempotency_key===void 0?{}:{idempotency_key:t.idempotency_key},...t.deadline===void 0?{}:{deadline:t.deadline},...t.requested_provider===void 0?{}:{requested_provider:structuredClone(t.requested_provider)},input:structuredClone(t.input)};wn(this.actionRequestValidator,s,"request_rejected","Action request"),ph(this.transport,s);let o=await this.acquireAdmission(i);try{let a=await is(fN(s)),c=this.activeActions.get(i);if(c){if(x0(e,i,a,c),c.handler.handlerDeclaration.idempotency?.mode!=="request")throw new O("request_rejected",`Action request ${i} is already active without deduplication.`);return structuredClone(await c.promise)}let l=this.completedActions.get(i);if(l){if(x0(e,i,a,l),!l.reusable)throw new O("request_rejected",`Action request ${i} was already completed without deduplication.`);return structuredClone(l.outcome)}if(s.deadline&&new Date(s.deadline).getTime()<=this.now().getTime())throw new O("deadline_exceeded",`Action request ${i} passed its deadline before admission.`);if(s.deadline&&!this.transport.deadlines)throw new O("unsupported_transport_capability","The active transport cannot enforce action deadlines.");let u=this.resolveActionCandidates(s.contract,s.requested_provider);u.length===0&&this.throwResolutionFailure(s.contract,s.requested_provider);let d=[];for(let E of u)await this.isAuthorized({operation:"invoke_action",principal:n.identity,contract:E.contract.reference,provider:E.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}})&&d.push(E);if(d.length===0)throw new O("unauthorized",`No authorized provider can execute ${s.contract.id}.`);if(d.length>1)throw new O("ambiguous_provider",`Action ${s.contract.id} has ${d.length} eligible providers; select one explicitly.`);let f=d[0];if(f.handlerDeclaration.max_concurrency!==void 0&&f.active>=f.handlerDeclaration.max_concurrency)throw new O("request_rejected",`Provider ${f.declaration.provider.implementation} is at capacity.`);if((f.contract.artifact.behavior?.idempotency??"none")==="required"&&!s.idempotency_key)throw new O("request_rejected",`${f.contract.reference.id} requires an idempotency key.`);Mc(f.contract.inputValidator,s.input,"invalid_action_input",`Action ${f.contract.reference.id} input`);let h={operation:"invoke_action",principal:n.identity,contract:f.contract.reference,provider:f.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}},m=await this.options.authorizationContext?.(h),y={kind:"mdbase.action.invocation",profile_version:"0.1",invocation_id:this.idFactory("inv"),attempt_id:this.idFactory("attempt"),request_id:i,contract:structuredClone(f.contract.reference),caller:structuredClone(n.identity),provider:structuredClone(f.declaration.provider),provider_declaration_digest:f.declaration.declaration_digest,handler_id:f.handlerDeclaration.handler_id,admitted_at:this.now().toISOString(),...s.correlation_id===void 0?{}:{correlation_id:s.correlation_id},...s.causation_id===void 0?{}:{causation_id:s.causation_id},...s.subject===void 0?{}:{subject:s.subject},...s.idempotency_key===void 0?{}:{idempotency_key:s.idempotency_key},...s.deadline===void 0?{}:{deadline:s.deadline},...m===void 0?{}:{authorization_context:m},input:structuredClone(s.input)};wn(this.actionInvocationValidator,y,"request_rejected","Action invocation"),await this.options.onInvocation?.(structuredClone(y));let g=new AbortController,b;if(y.deadline){let E=Math.max(0,new Date(y.deadline).getTime()-this.now().getTime());b=setTimeout(()=>g.abort(new O("deadline_exceeded",`Action request ${i} exceeded its deadline.`)),E)}f.active+=1;let v=this.executeAction(f,y,g).finally(()=>{b!==void 0&&clearTimeout(b),f.active=Math.max(0,f.active-1),this.activeActions.delete(i)});this.activeActions.set(i,{clientId:e,requestId:i,requestDigest:a,handler:f,invocation:y,controller:g,promise:v}),o();let S=await v,_=f.handlerDeclaration.idempotency?.retention_seconds??300;return this.completedActions.set(i,{clientId:e,requestDigest:a,outcome:structuredClone(S),reusable:f.handlerDeclaration.idempotency?.mode==="request",expiresAt:this.now().getTime()+_*1e3}),$0(this.completedActions,this.completedRequestLimit),structuredClone(S)}finally{o()}}async executeAction(e,t,n){try{let i=await e.handler(structuredClone(t.input),{invocation:structuredClone(t),signal:n.signal});if(n.signal.aborted){let o=n.signal.reason;return o instanceof O&&o.code==="deadline_exceeded"?this.failureOutcome(t,"failed",o.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}fh(i,"invalid_action_output",`Action ${e.contract.reference.id} output`),Mc(e.contract.outputValidator,i,"invalid_action_output",`Action ${e.contract.reference.id} output`);let s={kind:"mdbase.action.outcome",profile_version:"0.1",outcome_id:this.idFactory("outcome"),request_id:t.request_id,invocation_id:t.invocation_id,attempt_id:t.attempt_id,contract:structuredClone(t.contract),provider:structuredClone(t.provider),provider_declaration_digest:t.provider_declaration_digest,status:"succeeded",completed_at:this.now().toISOString(),output:structuredClone(i)};return wn(this.actionOutcomeValidator,s,"invalid_action_output","Action outcome"),ph(this.transport,s),s}catch(i){if(i instanceof Eo)return e.contract.errorValidator&&!e.contract.errorValidator(i.error.details??{})?this.failureOutcome(t,"failed",{code:"handler_failure",message:`Provider returned invalid declared error details: ${bn(e.contract.errorValidator.errors)}`}):this.failureOutcome(t,i.status,i.error);if(i instanceof O)return this.failureOutcome(t,i.code==="cancelled"?"cancelled":i.code==="outcome_indeterminate"?"outcome_indeterminate":"failed",i.toPortableError());if(n.signal.aborted||mN(i)){let s=n.signal.reason;return s instanceof O&&s.code==="deadline_exceeded"?this.failureOutcome(t,"failed",s.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}return this.report({severity:"error",code:"action_handler_failed",message:`Provider ${t.provider.implementation} failed ${t.contract.id}.`,principal:t.provider,contract:t.contract,cause:i}),this.failureOutcome(t,"failed",{code:"handler_failure",message:"The selected provider failed while executing the action."})}}failureOutcome(e,t,n){let i={kind:"mdbase.action.outcome",profile_version:"0.1",outcome_id:this.idFactory("outcome"),request_id:e.request_id,invocation_id:e.invocation_id,attempt_id:e.attempt_id,contract:structuredClone(e.contract),provider:structuredClone(e.provider),provider_declaration_digest:e.provider_declaration_digest,status:t,completed_at:this.now().toISOString(),error:structuredClone(n)};return wn(this.actionOutcomeValidator,i,"invalid_action_output","Action outcome"),i}async cancelAction(e,t,n){let i=this.requireClient(e),s=this.admissionLocks.get(t);s&&await s;let o=this.activeActions.get(t);if(!o){let a=this.completedActions.get(t);if(a&&a.clientId!==e)throw new O("unauthorized",`Action request ${t} belongs to another caller.`);return a?structuredClone(a.outcome):null}if(o.clientId!==e)throw new O("unauthorized",`Action request ${t} belongs to another caller.`);if(await this.assertAuthorized({operation:"cancel_action",principal:i.identity,contract:o.invocation.contract,provider:o.invocation.provider,...o.invocation.subject===void 0?{}:{subject:o.invocation.subject}}),!this.transport.cancellation)throw new O("unsupported_transport_capability","The active transport cannot deliver cancellation.");if(o.handler.handlerDeclaration.cancellation!=="cooperative")throw new O("cancellation_unsupported",`Provider ${o.invocation.provider.implementation} does not support cancellation.`);return o.controller.abort(new O("cancelled",n?.trim()||`Action request ${t} was cancelled.`)),structuredClone(await o.promise)}resolveActionCandidates(e,t){let n=[...this.actionProviders.values()].flatMap(({handlers:s})=>s).filter(({contract:s,declaration:o})=>Vc(e,s.reference)&&pN(t,o.provider)),i=(0,Ur.maxSatisfying)([...new Set(n.map(({contract:s})=>s.reference.version))],e.version,{includePrerelease:!0});return i?n.filter(({contract:s})=>s.reference.version===i).sort((s,o)=>s.declaration.provider.application.localeCompare(o.declaration.provider.application)||s.declaration.provider.implementation.localeCompare(o.declaration.provider.implementation)||(s.declaration.provider.instance_id??"").localeCompare(o.declaration.provider.instance_id??"")||s.handlerDeclaration.handler_id.localeCompare(o.handlerDeclaration.handler_id)):[]}throwResolutionFailure(e,t){let n=[...this.contracts.values()].filter(i=>i.artifact.contract_type==="action"&&i.reference.id===e.id);throw n.length===0?new O("unknown_contract",`Action contract ${e.id} is unknown.`):n.some(({reference:i})=>Vc(e,i))?t?new O("requested_provider_unavailable",`The requested provider is unavailable for ${e.id}.`):new O("no_provider",`No provider is registered for ${e.id}.`):new O("unsupported_contract_version",`No ${e.id} artifact satisfies ${e.version}.`)}async prepareEventContract(e){if(this.assertContractArtifact(e),e.contract_type!=="event")throw new O("unknown_contract",`${e.id} is not an event contract.`);let t={id:e.id,version:e.version,digest:await Pc(e)};this.assertNoContractConflict(t);let n=Pw(this.ajv,e);return{artifact:structuredClone(e),reference:t,dataValidator:n.data,...n.source===void 0?{}:{sourceValidator:n.source}}}async prepareActionContract(e){if(this.assertContractArtifact(e),e.contract_type!=="action")throw new O("unknown_contract",`${e.id} is not an action contract.`);let t={id:e.id,version:e.version,digest:await Pc(e)};this.assertNoContractConflict(t);let n=Mw(this.ajv,e);return{artifact:structuredClone(e),reference:t,inputValidator:n.input,...n.output===void 0?{}:{outputValidator:n.output},...n.error===void 0?{}:{errorValidator:n.error},...n.provider===void 0?{}:{providerValidator:n.provider}}}assertContractArtifact(e){if(wn(this.contractValidator,e,"contract_digest_conflict",`Contract ${e.id||""}`),!(0,Ur.valid)(e.version))throw new O("unsupported_contract_version",`${e.id} version must be exact SemVer.`)}assertNoContractConflict(e){let t=this.contracts.get(Uc(e));if(t&&t.reference.digest!==e.digest)throw new O("contract_digest_conflict",`Contract ${e.id} ${e.version} conflicts with the registered artifact.`)}commitContracts(e){let t=new Map;for(let n of e){let i=Uc(n.reference),s=t.get(i)??this.contracts.get(i);if(s&&s.reference.digest!==n.reference.digest)throw new O("contract_digest_conflict",`Contract ${n.reference.id} ${n.reference.version} conflicts within the registration.`);t.set(i,n)}for(let[n,i]of t)this.contracts.has(n)||this.contracts.set(n,i)}async disposeClient(e,t=!1){let n=this.clients.get(e);if(!(!n||n.disposed)){n.disposed=!0;for(let i of[...n.subscriptions])this.removeSubscription(i);for(let i of[...n.sources])this.removeEventSource(i);for(let i of[...n.providers])this.removeActionProvider(i);for(let i of[...this.activeActions.values()])i.clientId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new O("cancelled","The caller unloaded.")),i.handler.clientId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new O("cancelled","The provider unloaded."));this.clients.delete(e),t||this.assertActive()}}removeEventSource(e){let t=this.eventSources.get(e);t&&(this.eventSources.delete(e),this.clients.get(t.clientId)?.sources.delete(e))}removeActionProvider(e){let t=this.actionProviders.get(e);if(t){this.actionProviders.delete(e),this.clients.get(t.clientId)?.providers.delete(e);for(let n of this.activeActions.values())n.handler.registrationId===e&&n.handler.handlerDeclaration.cancellation==="cooperative"&&n.controller.abort(new O("cancelled","The provider unloaded."))}}removeSubscription(e){let t=this.subscriptions.get(e);t&&(this.subscriptions.delete(e),this.clients.get(t.clientId)?.subscriptions.delete(e))}requireClient(e){this.assertActive();let t=this.clients.get(e);if(!t||t.disposed)throw new O("transport_unavailable","Interop client is disposed.");return t}assertActive(){if(this.disposed)throw new O("transport_unavailable","Interop bridge is disposed.")}async assertAuthorized(e){if(!await this.isAuthorized(e))throw new O("unauthorized",`${e.operation} is not authorized.`)}async isAuthorized(e){try{return await this.authorize(structuredClone(e))}catch(t){return this.report({severity:"error",code:"authorization_failed",message:`Authorization failed for ${e.operation}.`,principal:e.principal,cause:t}),!1}}cleanCompletedActions(){let e=this.now().getTime();for(let[t,n]of this.completedActions)n.expiresAt<=e&&this.completedActions.delete(t)}async acquireAdmission(e){let t=this.admissionLocks.get(e)??Promise.resolve(),n,i=new Promise(a=>{n=a}),s=t.then(()=>i);this.admissionLocks.set(e,s),await t;let o=!1;return()=>{o||(o=!0,n(),this.admissionLocks.get(e)===s&&this.admissionLocks.delete(e))}}report(e){this.options.onDiagnostic?.(structuredClone(e))}};function wn(r,e,t,n){if(!r(e))throw new O(t,`${n} is invalid: ${bn(r.errors)}`)}function lN(r){for(let[e,t]of Object.entries(r))if(t!==void 0&&(typeof t!="string"||t.length===0||!/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/u.test(t)))throw new O("request_rejected",`Implementation identity ${e} is invalid.`);if(!(0,Ur.valid)(r.version))throw new O("request_rejected","Implementation identity version must be exact SemVer.")}function hh(r){if(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u.test(r.id))throw new O("unknown_contract",`Contract ID ${r.id} is invalid.`);if(!(0,Ur.validRange)(r.version,{includePrerelease:!0}))throw new O("unsupported_contract_version",`Contract requirement ${r.version} is not a SemVer range.`);if(r.digest&&!/^sha256:[0-9a-f]{64}$/u.test(r.digest))throw new O("contract_digest_conflict","Contract digest is invalid.")}function _0(r,e){let t=r??{id:e.id,version:e.version,digest:e.digest};return hh(t),structuredClone(t)}function S0(r,e){if(!Vc(r,e))throw new O("unsupported_contract_version",`${e.id} ${e.version} does not satisfy its implementation requirement.`)}function Vc(r,e){return r.id===e.id&&(0,Ur.satisfies)(e.version,r.version,{includePrerelease:!0})&&(!r.digest||r.digest===e.digest)}function Uc(r){return`${r.id}@${r.version}`}function E0(r){return`urn:mdbase:contract:${r.id}:${r.version}:${r.digest}`}function dN(r){return`urn:mdbase:app:${[r.application,r.implementation,...r.instance_id?[r.instance_id]:[]].map(encodeURIComponent).join(":")}`}function uN(r,e){if(r.type!==e.id||r.mdbasecontractversion!==e.version||r.mdbasecontractdigest!==e.digest||r.dataschema!==E0(e))throw new O("contract_digest_conflict","Event contract evidence is inconsistent.")}function fN(r){let{created_at:e,...t}=r;return t}function x0(r,e,t,n){if(n.clientId!==r)throw new O("unauthorized",`Action request ${e} belongs to another caller.`);if(n.requestDigest!==t)throw new O("request_rejected",`Action request ${e} was reused with different content.`)}function fh(r,e,t){let n=new Set,i=(s,o)=>{if(!(s===null||typeof s=="boolean"||typeof s=="string")){if(typeof s=="number"){if(Number.isFinite(s))return;throw new O(e,`${t}${o} must be a finite JSON number.`)}if(typeof s!="object")throw new O(e,`${t}${o} is not a JSON value.`);if(n.has(s))throw new O(e,`${t}${o} contains a cycle.`);if(n.add(s),Array.isArray(s))s.forEach((a,c)=>i(a,`${o}/${c}`));else{let a=Object.getPrototypeOf(s);if(a!==Object.prototype&&a!==null)throw new O(e,`${t}${o} must be a plain JSON object.`);for(let[c,l]of Object.entries(s))i(l,`${o}/${c}`)}n.delete(s)}};i(r,"")}function ph(r,e){if(r.max_payload_bytes===void 0)return;let t=JSON.stringify(e),n=new TextEncoder().encode(t).byteLength;if(n>r.max_payload_bytes)throw new O("unsupported_transport_capability",`The portable envelope is ${n} bytes; the active transport allows ${r.max_payload_bytes}.`)}function pN(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 hN(r,e){if(e){if(e.delivery?.some(t=>!r.delivery.includes(t)))throw new O("unsupported_transport_capability","The active transport lacks a required delivery capability.");if(e.ordering?.some(t=>!r.ordering.includes(t)))throw new O("unsupported_transport_capability","The active transport lacks a required ordering capability.");for(let t of["cancellation","deadlines","provider_discovery","request_deduplication","cross_process_identity"])if(e[t]===!0&&r[t]!==!0)throw new O("unsupported_transport_capability",`The active transport lacks ${t}.`);if(e.max_payload_bytes!==void 0&&(r.max_payload_bytes===void 0||r.max_payload_bytese;){let t=r.keys().next().value;if(t===void 0)return;r.delete(t)}}function mN(r){return r instanceof Error&&r.name==="AbortError"}var Hc=class{constructor(e,t){this.app=e;this.profileVersion="0.1";this.bridge=new To({authorize:()=>t(),transport:{delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},onDiagnostic:n=>{(n.severity==="error"?console.error:console.warn)(`[mdbase/interop] ${n.code}: ${n.message}`,n.cause??"")}}),this.transport=this.bridge.describe().transport}connect(e){let t=e.manifest?.id,n=e.manifest?.version;if(!t||!n)throw new Error("Only a loaded Obsidian plugin with manifest identity can connect to mdbase interop.");let i=this.app.plugins;if(!i||i.getPlugin(t)!==e)throw new Error(`Obsidian plugin ${t} is not the active loaded instance.`);return this.bridge.connect({application:t,implementation:`${t}.obsidian`,version:n})}describe(){return this.bridge.describe()}dispose(){return this.bridge.dispose()}};qt();var J=require("obsidian"),a$=Kn(vp(),1);var zc=Symbol.for("yaml.alias"),Kc=Symbol.for("yaml.document"),er=Symbol.for("yaml.map"),mh=Symbol.for("yaml.pair"),At=Symbol.for("yaml.scalar"),Vr=Symbol.for("yaml.seq"),it=Symbol.for("yaml.node.type"),tr=r=>!!r&&typeof r=="object"&&r[it]===zc,xr=r=>!!r&&typeof r=="object"&&r[it]===Kc,rr=r=>!!r&&typeof r=="object"&&r[it]===er,te=r=>!!r&&typeof r=="object"&&r[it]===mh,W=r=>!!r&&typeof r=="object"&&r[it]===At,nr=r=>!!r&&typeof r=="object"&&r[it]===Vr;function ae(r){if(r&&typeof r=="object")switch(r[it]){case er:case Vr:return!0}return!1}function ne(r){if(r&&typeof r=="object")switch(r[it]){case zc:case er:case At:case Vr:return!0}return!1}var Wc=r=>(W(r)||ae(r))&&!!r.anchor;var gt=Symbol("break visit"),A0=Symbol("skip children"),$r=Symbol("remove node");function Er(r,e){let t=k0(e);xr(r)?as(null,r.contents,t,Object.freeze([r]))===$r&&(r.contents=null):as(null,r,t,Object.freeze([]))}Er.BREAK=gt;Er.SKIP=A0;Er.REMOVE=$r;function as(r,e,t,n){let i=P0(r,e,t,n);if(ne(i)||te(i))return M0(r,n,i),as(r,i,t,n);if(typeof i!="symbol"){if(ae(e)){n=Object.freeze(n.concat(e));for(let s=0;sr.replace(/[!,[\]{}]/g,e=>yN[e]),Ar=class r{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},r.defaultYaml,e),this.tags=Object.assign({},r.defaultTags,t)}clone(){let e=new r(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new r(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:r.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},r.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:r.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},r.defaultTags),this.atNextDocument=!1);let n=e.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[s,o]=n;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[s]=n;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return t(6,`Unsupported YAML version ${s}`,o),!1}}default:return t(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}let[,n,i]=e.match(/^(.*!)([^!]*)$/s);i||t(`The ${e} tag has no suffix`);let s=this.tags[n];if(s)try{return s+decodeURIComponent(i)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+gN(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),i;if(e&&n.length>0&&ne(e.contents)){let s={};Er(e.contents,(o,a)=>{ne(a)&&a.tag&&(s[a.tag]=!0)}),i=Object.keys(s)}else i=[];for(let[s,o]of n)s==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(o)))&&t.push(`%TAG ${s} ${o}`);return t.join(` +`)}};Ar.defaultYaml={explicit:!1,version:"1.2"};Ar.defaultTags={"!!":"tag:yaml.org,2002:"};function Jc(r){if(/[\x00-\x19\s,[\]{}]/.test(r)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(r)}`;throw new Error(t)}return!0}function yh(r){let e=new Set;return Er(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function gh(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function C0(r,e){let t=[],n=new Map,i=null;return{onAnchor:s=>{t.push(s),i??(i=yh(r));let o=gh(e,i);return i.add(o),o},setAnchors:()=>{for(let s of t){let o=n.get(s);if(typeof o=="object"&&o.anchor&&(W(o.node)||ae(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:n}}function _n(r,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,s=n.length;iRe(n,String(i),t));if(r&&typeof r.toJSON=="function"){if(!t||!Wc(r))return r.toJSON(e,t);let n={aliasCount:0,count:1,res:void 0};t.anchors.set(r,n),t.onCreate=s=>{n.res=s,delete t.onCreate};let i=r.toJSON(e,t);return t.onCreate&&t.onCreate(i),i}return typeof r=="bigint"&&!t?.keep?Number(r):r}var Sn=class{constructor(e){Object.defineProperty(this,it,{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(!xr(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},a=Re(this,"",o);if(typeof i=="function")for(let{count:c,res:l}of o.anchors.values())i(l,c);return typeof s=="function"?_n(s,{"":a},"",a):a}};var Hr=class extends Sn{constructor(e){super(zc),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if(t?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],Er(e,{Node:(s,o)=>{(tr(o)||Wc(o))&&n.push(o)}}),t&&(t.aliasResolveCache=n));let i;for(let s of n){if(s===this)break;s.anchor===this.source&&(i=s)}if(i&&t){let{anchors:s,doc:o,maxAliasCount:a}=t,c=s.get(i);if(c||(Re(i,null,t),c=s.get(i)),c?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(a>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=Yc(o,i,s)),c.count*c.aliasCount>a)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}}return i}toJSON(e,t){if(!t)return{source:this.source};let n=this.resolve(t.doc,t);if(!n){let i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(i)}return t.anchors.get(n).res}toString(e,t,n){let i=`*${this.source}`;if(e){if(Jc(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(e.implicitKey)return`${i} `}return i}};function Yc(r,e,t){if(tr(e)){let n=e.resolve(r),i=t&&n&&t.get(n);return i?i.count*i.aliasCount:0}else if(ae(e)){let n=0;for(let i of e.items){let s=Yc(r,i,t);s>n&&(n=s)}return n}else if(te(e)){let n=Yc(r,e.key,t),i=Yc(r,e.value,t);return Math.max(n,i)}return 1}var Xc=r=>!r||typeof r!="function"&&typeof r!="object",F=class extends Sn{constructor(e){super(At),this.value=e}toJSON(e,t){return t?.keep?this.value:Re(this.value,e,t)}toString(){return String(this.value)}};F.BLOCK_FOLDED="BLOCK_FOLDED";F.BLOCK_LITERAL="BLOCK_LITERAL";F.PLAIN="PLAIN";F.QUOTE_DOUBLE="QUOTE_DOUBLE";F.QUOTE_SINGLE="QUOTE_SINGLE";var bN="tag:yaml.org,2002:";function vN(r,e,t){if(e){let n=t.filter(s=>s.tag===e),i=n.find(s=>!s.format)??n[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return t.find(n=>n.identify?.(r)&&!n.format)}function zr(r,e,t){if(xr(r)&&(r=r.contents),ne(r))return r;if(te(r)){let d=t.schema[er].createNode?.(t.schema,null,t);return d.items.push(r),d}(r instanceof String||r instanceof Number||r instanceof Boolean||typeof BigInt<"u"&&r instanceof BigInt)&&(r=r.valueOf());let{aliasDuplicateObjects:n,onAnchor:i,onTagObj:s,schema:o,sourceObjects:a}=t,c;if(n&&r&&typeof r=="object"){if(c=a.get(r),c)return c.anchor??(c.anchor=i(r)),new Hr(c.anchor);c={anchor:null,node:null},a.set(r,c)}e?.startsWith("!!")&&(e=bN+e.slice(2));let l=vN(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let d=new F(r);return c&&(c.node=d),d}l=r instanceof Map?o[er]:Symbol.iterator in Object(r)?o[Vr]:o[er]}s&&(s(l),delete t.onTagObj);let u=l?.createNode?l.createNode(t.schema,r,t):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(t.schema,r,t):new F(r);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}function Ro(r,e,t){let n=t;for(let i=e.length-1;i>=0;--i){let s=e[i];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=n,n=o}else n=new Map([[s,n]])}return zr(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:r,sourceObjects:new Map})}var ds=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,ls=class extends Sn{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(n=>ne(n)||te(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(ds(e))this.add(t);else{let[n,...i]=e,s=this.get(n,!0);if(ae(s))s.addIn(i,t);else if(s===void 0&&this.schema)this.set(n,Ro(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let i=this.get(t,!0);if(ae(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...i]=e,s=this.get(n,!0);return i.length===0?!t&&W(s)?s.value:s:ae(s)?s.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!te(t))return!1;let n=t.value;return n==null||e&&W(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let i=this.get(t,!0);return ae(i)?i.hasIn(n):!1}setIn(e,t){let[n,...i]=e;if(i.length===0)this.set(n,t);else{let s=this.get(n,!0);if(ae(s))s.setIn(i,t);else if(s===void 0&&this.schema)this.set(n,Ro(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};var T0=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function Vt(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var kr=(r,e,t)=>r.endsWith(` `)?Vt(t,e):t.includes(` `)?` -`+Vt(t,e):(r.endsWith(" ")?"":" ")+t;var yh="flow",Xc="block",Ro="quoted";function Io(r,e,t="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return r;ii-Math.max(2,s)?l.push(0):d=i-n);let f,p,m=!1,h=-1,y=-1,g=-1;t===Xc&&(h=C0(r,h,e.length),h!==-1&&(d=h+c));for(let v;v=r[h+=1];){if(t===Ro&&v==="\\"){switch(y=h,r[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}g=h}if(v===` -`)t===Xc&&(h=C0(r,h,e.length)),d=h+e.length+c,f=void 0;else{if(v===" "&&p&&p!==" "&&p!==` -`&&p!==" "){let S=r[h+1];S&&S!==" "&&S!==` -`&&S!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(t===Ro){for(;p===" "||p===" ";)p=v,v=r[h+=1],m=!0;let S=h>g+1?h-2:y-1;if(u[S])return r;l.push(S),u[S]=!0,d=S+c,f=void 0}else m=!0}p=v}if(m&&a&&a(),l.length===0)return r;o&&o();let b=r.slice(0,l[0]);for(let v=0;v({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),el=r=>/^(%|---|\.\.\.)/m.test(r);function bN(r,e,t){if(!e||e<0)return!1;let n=e-t,i=r.length;if(i<=n)return!1;for(let s=0,o=0;sn)return!0;if(o=s+1,i-o<=n)return!1}return!0}function Oo(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,i=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(el(r)?" ":""),o="",a=0;for(let c=0,l=t[c];l;l=t[++c])if(l===" "&&t[c+1]==="\\"&&t[c+2]==="n"&&(o+=t.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(t[c+1]){case"u":{o+=t.slice(a,c);let u=t.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||t[c+2]==='"'||t.lengthi-Math.max(2,s)?l.push(0):d=i-n);let f,p,h=!1,m=-1,y=-1,g=-1;t===Qc&&(m=R0(r,m,e.length),m!==-1&&(d=m+c));for(let v;v=r[m+=1];){if(t===Io&&v==="\\"){switch(y=m,r[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}g=m}if(v===` +`)t===Qc&&(m=R0(r,m,e.length)),d=m+e.length+c,f=void 0;else{if(v===" "&&p&&p!==" "&&p!==` +`&&p!==" "){let S=r[m+1];S&&S!==" "&&S!==` +`&&S!==" "&&(f=m)}if(m>=d)if(f)l.push(f),d=f+c,f=void 0;else if(t===Io){for(;p===" "||p===" ";)p=v,v=r[m+=1],h=!0;let S=m>g+1?m-2:y-1;if(u[S])return r;l.push(S),u[S]=!0,d=S+c,f=void 0}else h=!0}p=v}if(h&&a&&a(),l.length===0)return r;o&&o();let b=r.slice(0,l[0]);for(let v=0;v({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),tl=r=>/^(%|---|\.\.\.)/m.test(r);function wN(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 Do(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,i=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(tl(r)?" ":""),o="",a=0;for(let c=0,l=t[c];l;l=t[++c])if(l===" "&&t[c+1]==="\\"&&t[c+2]==="n"&&(o+=t.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(t[c+1]){case"u":{o+=t.slice(a,c);let u=t.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||t[c+2]==='"'||t.length `;let d,f;for(f=t.length;f>0;--f){let _=t[f-1];if(_!==` -`&&_!==" "&&_!==" ")break}let p=t.substring(f),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(bh,`$&${l}`));let h=!1,y,g=-1;for(y=0;y{E=!0});let $=Io(`${b}${_}${p}`,l,Xc,k);if(!E)return`>${S} -${l}${$}`}return t=t.replace(/\n+/g,`$&${l}`),`|${S} -${l}${b}${t}${p}`}function vN(r,e,t,n){let{type:i,value:s}=r,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:u}=e;if(a&&s.includes(` +`&&_!==" "&&_!==" ")break}let p=t.substring(f),h=p.indexOf(` +`);h===-1?d="-":t===p||h!==p.length-1?(d="+",s&&s()):d="",p&&(t=t.slice(0,-p.length),p[p.length-1]===` +`&&(p=p.slice(0,-1)),p=p.replace(wh,`$&${l}`));let m=!1,y,g=-1;for(y=0;y{E=!0});let x=Oo(`${b}${_}${p}`,l,Qc,k);if(!E)return`>${S} +${l}${x}`}return t=t.replace(/\n+/g,`$&${l}`),`|${S} +${l}${b}${t}${p}`}function _N(r,e,t,n){let{type:i,value:s}=r,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:u}=e;if(a&&s.includes(` `)||u&&/[[\]{},]/.test(s))return us(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||u||!s.includes(` -`)?us(s,e):Qc(r,e,t,n);if(!a&&!u&&i!==F.PLAIN&&s.includes(` -`))return Qc(r,e,t,n);if(el(s)){if(c==="")return e.forceBlockIndent=!0,Qc(r,e,t,n);if(a&&c===l)return us(s,e)}let d=s.replace(/\n+/g,`$& -${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:m}=e.doc.schema;if(m.some(f)||p?.some(f))return us(s,e)}return a?d:Io(d,c,yh,Zc(e,!1))}function ci(r,e,t,n){let{implicitKey:i,inFlow:s}=e,o=typeof r.value=="string"?r:Object.assign({},r,{value:String(r.value)}),{type:a}=r;a!==F.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=F.QUOTE_DOUBLE);let c=u=>{switch(u){case F.BLOCK_FOLDED:case F.BLOCK_LITERAL:return i||s?us(o.value,e):Qc(o,e,t,n);case F.QUOTE_DOUBLE:return Oo(o.value,e);case F.QUOTE_SINGLE:return gh(o.value,e);case F.PLAIN:return vN(o,e,t,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:u,defaultStringType:d}=e.options,f=i&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}function tl(r,e){let t=Object.assign({blockQuote:!0,commentString:P0,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},r.schema.toStringOptions,e),n;switch(t.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:r,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:n,options:t}}function wN(r,e){if(e.tag){let i=r.filter(s=>s.tag===e.tag);if(i.length>0)return i.find(s=>s.format===e.format)??i[0]}let t,n;if(G(e)){n=e.value;let i=r.filter(s=>s.identify?.(n));if(i.length>1){let s=i.filter(o=>o.test);s.length>0&&(i=s)}t=i.find(s=>s.format===e.format)??i.find(s=>!s.format)}else n=e,t=r.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!t){let i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return t}function _N(r,e,{anchors:t,doc:n}){if(!n.directives)return"";let i=[],s=(G(r)||ae(r))&&r.anchor;s&&Gc(s)&&(t.add(s),i.push(`&${s}`));let o=r.tag??(e.default?null:e.tag);return o&&i.push(n.directives.tagString(o)),i.join(" ")}function Wr(r,e,t,n){if(te(r))return r.toString(e,t,n);if(er(r)){if(e.doc.directives)return r.toString(e);if(e.resolvedAliases?.has(r))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(r):e.resolvedAliases=new Set([r]),r=r.resolve(e.doc)}let i,s=ne(r)?r:e.doc.createNode(r,{onTagObj:c=>i=c});i??(i=wN(e.doc.schema.tags,s));let o=_N(s,i,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof i.stringify=="function"?i.stringify(s,e,t,n):G(s)?ci(s,e,t,n):s.toString(e,t,n);return o?G(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} -${e.indent}${a}`:a}function M0({key:r,value:e},t,n,i){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=t,f=ne(r)&&r.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(ae(r)||!ne(r)&&typeof r=="object"){let k="With simple keys, collection cannot be used as a key value";throw new Error(k)}}let p=!d&&(!r||f&&e==null&&!t.inFlow||ae(r)||(G(r)?r.type===F.BLOCK_FOLDED||r.type===F.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(d||!s),indent:a+c});let m=!1,h=!1,y=Wr(r,t,()=>m=!0,()=>h=!0);if(!p&&!t.inFlow&&y.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(t.inFlow){if(s||e==null)return m&&n&&n(),y===""?"?":p?`? ${y}`:y}else if(s&&!d||e==null&&p)return y=`? ${y}`,f&&!m?y+=kr(y,t.indent,l(f)):h&&i&&i(),y;m&&(f=null),p?(f&&(y+=kr(y,t.indent,l(f))),y=`? ${y} -${a}:`):(y=`${y}:`,f&&(y+=kr(y,t.indent,l(f))));let g,b,v;ne(e)?(g=!!e.spaceBefore,b=e.commentBefore,v=e.comment):(g=!1,b=null,v=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!f&&G(e)&&(t.indentAtStart=y.length+1),h=!1,!u&&c.length>=2&&!t.inFlow&&!p&&rr(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let S=!1,_=Wr(e,t,()=>S=!0,()=>h=!0),E=" ";if(f||g||b){if(E=g?` +`)?us(s,e):Zc(r,e,t,n);if(!a&&!u&&i!==F.PLAIN&&s.includes(` +`))return Zc(r,e,t,n);if(tl(s)){if(c==="")return e.forceBlockIndent=!0,Zc(r,e,t,n);if(a&&c===l)return us(s,e)}let d=s.replace(/\n+/g,`$& +${c}`);if(o){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(d),{compat:p,tags:h}=e.doc.schema;if(h.some(f)||p?.some(f))return us(s,e)}return a?d:Oo(d,c,bh,el(e,!1))}function ci(r,e,t,n){let{implicitKey:i,inFlow:s}=e,o=typeof r.value=="string"?r:Object.assign({},r,{value:String(r.value)}),{type:a}=r;a!==F.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=F.QUOTE_DOUBLE);let c=u=>{switch(u){case F.BLOCK_FOLDED:case F.BLOCK_LITERAL:return i||s?us(o.value,e):Zc(o,e,t,n);case F.QUOTE_DOUBLE:return Do(o.value,e);case F.QUOTE_SINGLE:return vh(o.value,e);case F.PLAIN:return _N(o,e,t,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:u,defaultStringType:d}=e.options,f=i&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}function rl(r,e){let t=Object.assign({blockQuote:!0,commentString:T0,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 SN(r,e){if(e.tag){let i=r.filter(s=>s.tag===e.tag);if(i.length>0)return i.find(s=>s.format===e.format)??i[0]}let t,n;if(W(e)){n=e.value;let i=r.filter(s=>s.identify?.(n));if(i.length>1){let s=i.filter(o=>o.test);s.length>0&&(i=s)}t=i.find(s=>s.format===e.format)??i.find(s=>!s.format)}else n=e,t=r.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!t){let i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return t}function xN(r,e,{anchors:t,doc:n}){if(!n.directives)return"";let i=[],s=(W(r)||ae(r))&&r.anchor;s&&Jc(s)&&(t.add(s),i.push(`&${s}`));let o=r.tag??(e.default?null:e.tag);return o&&i.push(n.directives.tagString(o)),i.join(" ")}function Kr(r,e,t,n){if(te(r))return r.toString(e,t,n);if(tr(r)){if(e.doc.directives)return r.toString(e);if(e.resolvedAliases?.has(r))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(r):e.resolvedAliases=new Set([r]),r=r.resolve(e.doc)}let i,s=ne(r)?r:e.doc.createNode(r,{onTagObj:c=>i=c});i??(i=SN(e.doc.schema.tags,s));let o=xN(s,i,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof i.stringify=="function"?i.stringify(s,e,t,n):W(s)?ci(s,e,t,n):s.toString(e,t,n);return o?W(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} +${e.indent}${a}`:a}function I0({key:r,value:e},t,n,i){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=t,f=ne(r)&&r.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(ae(r)||!ne(r)&&typeof r=="object"){let k="With simple keys, collection cannot be used as a key value";throw new Error(k)}}let p=!d&&(!r||f&&e==null&&!t.inFlow||ae(r)||(W(r)?r.type===F.BLOCK_FOLDED||r.type===F.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(d||!s),indent:a+c});let h=!1,m=!1,y=Kr(r,t,()=>h=!0,()=>m=!0);if(!p&&!t.inFlow&&y.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(t.inFlow){if(s||e==null)return h&&n&&n(),y===""?"?":p?`? ${y}`:y}else if(s&&!d||e==null&&p)return y=`? ${y}`,f&&!h?y+=kr(y,t.indent,l(f)):m&&i&&i(),y;h&&(f=null),p?(f&&(y+=kr(y,t.indent,l(f))),y=`? ${y} +${a}:`):(y=`${y}:`,f&&(y+=kr(y,t.indent,l(f))));let g,b,v;ne(e)?(g=!!e.spaceBefore,b=e.commentBefore,v=e.comment):(g=!1,b=null,v=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!f&&W(e)&&(t.indentAtStart=y.length+1),m=!1,!u&&c.length>=2&&!t.inFlow&&!p&&nr(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let S=!1,_=Kr(e,t,()=>S=!0,()=>m=!0),E=" ";if(f||g||b){if(E=g?` `:"",b){let k=l(b);E+=` ${Vt(k,t.indent)}`}_===""&&!t.inFlow?E===` `&&v&&(E=` `):E+=` -${t.indent}`}else if(!p&&ae(e)){let k=_[0],$=_.indexOf(` -`),M=$!==-1,x=t.inFlow??e.flow??e.items.length===0;if(M||!x){let q=!1;if(M&&(k==="&"||k==="!")){let T=_.indexOf(" ");k==="&"&&T!==-1&&T<$&&_[T+1]==="!"&&(T=_.indexOf(" ",T+1)),(T===-1||$r===nl||typeof r=="symbol"&&r.description===nl,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new F(Symbol(nl)),{addToJSMap:wh}),stringify:()=>nl},T0=(r,e)=>(nr.identify(e)||G(e)&&(!e.type||e.type===F.PLAIN)&&nr.identify(e.value))&&r?.doc.schema.tags.some(t=>t.tag===nr.tag&&t.default);function wh(r,e,t){let n=R0(r,t);if(rr(n))for(let i of n.items)vh(r,e,i);else if(Array.isArray(n))for(let i of n)vh(r,e,i);else vh(r,e,n)}function vh(r,e,t){let n=R0(r,t);if(!tr(n))throw new Error("Merge sources must be maps or map aliases");let i=n.toJSON(null,r,Map);for(let[s,o]of i)e instanceof Map?e.has(s)||e.set(s,o):e instanceof Set?e.add(s):Object.prototype.hasOwnProperty.call(e,s)||Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function R0(r,e){return r&&er(e)?e.resolve(r.doc,r):e}function il(r,e,{key:t,value:n}){if(ne(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(T0(r,t))wh(r,e,n);else{let i=Re(t,"",r);if(e instanceof Map)e.set(i,Re(n,i,r));else if(e instanceof Set)e.add(i);else{let s=SN(t,i,r),o=Re(n,s,r);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function SN(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(ne(r)&&t?.doc){let n=tl(t.doc,{});n.anchors=new Set;for(let s of t.anchors.keys())n.anchors.add(s.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=r.toString(n);if(!t.mapKeyWarned){let s=JSON.stringify(i);s.length>40&&(s=s.substring(0,36)+'..."'),rl(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return i}return JSON.stringify(e)}function fs(r,e,t){let n=Kr(r,void 0,t),i=Kr(e,void 0,t);return new _e(n,i)}var _e=class r{constructor(e,t=null){Object.defineProperty(this,nt,{value:ph}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return ne(t)&&(t=t.clone(e)),ne(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return il(t,n,this)}toString(e,t,n){return e?.doc?M0(this,e,t,n):JSON.stringify(this)}};function ol(r,e,t){return(e.inFlow??r.flow?xN:$N)(r,e,t)}function $N({comment:r,items:e},t,{blockItemPrefix:n,flowChars:i,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=t,u=Object.assign({},t,{indent:s,type:null}),d=!1,f=[];for(let m=0;my=null,()=>d=!0);y&&(g+=kr(g,s,l(y))),d&&y&&(d=!1),f.push(n+g)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let m=1;mr===il||typeof r=="symbol"&&r.description===il,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new F(Symbol(il)),{addToJSMap:Sh}),stringify:()=>il},O0=(r,e)=>(ir.identify(e)||W(e)&&(!e.type||e.type===F.PLAIN)&&ir.identify(e.value))&&r?.doc.schema.tags.some(t=>t.tag===ir.tag&&t.default);function Sh(r,e,t){let n=D0(r,t);if(nr(n))for(let i of n.items)_h(r,e,i);else if(Array.isArray(n))for(let i of n)_h(r,e,i);else _h(r,e,n)}function _h(r,e,t){let n=D0(r,t);if(!rr(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 D0(r,e){return r&&tr(e)?e.resolve(r.doc,r):e}function sl(r,e,{key:t,value:n}){if(ne(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(O0(r,t))Sh(r,e,n);else{let i=Re(t,"",r);if(e instanceof Map)e.set(i,Re(n,i,r));else if(e instanceof Set)e.add(i);else{let s=$N(t,i,r),o=Re(n,s,r);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function $N(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(ne(r)&&t?.doc){let n=rl(t.doc,{});n.anchors=new Set;for(let s of t.anchors.keys())n.anchors.add(s.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=r.toString(n);if(!t.mapKeyWarned){let s=JSON.stringify(i);s.length>40&&(s=s.substring(0,36)+'..."'),nl(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return i}return JSON.stringify(e)}function fs(r,e,t){let n=zr(r,void 0,t),i=zr(e,void 0,t);return new _e(n,i)}var _e=class r{constructor(e,t=null){Object.defineProperty(this,it,{value:mh}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return ne(t)&&(t=t.clone(e)),ne(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return sl(t,n,this)}toString(e,t,n){return e?.doc?I0(this,e,t,n):JSON.stringify(this)}};function al(r,e,t){return(e.inFlow??r.flow?AN:EN)(r,e,t)}function EN({comment:r,items:e},t,{blockItemPrefix:n,flowChars:i,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=t,u=Object.assign({},t,{indent:s,type:null}),d=!1,f=[];for(let h=0;hy=null,()=>d=!0);y&&(g+=kr(g,s,l(y))),d&&y&&(d=!1),f.push(n+g)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let h=1;hy=null);l||(l=d.length>u||g.includes(` -`)),m0&&(l||(l=d.reduce((b,v)=>b+v.length+2,2)+(g.length+2)>e.options.lineWidth)),l&&(g+=",")),y&&(g+=kr(g,n,a(y))),d.push(g),u=d.length}let{start:f,end:p}=t;if(d.length===0)return f+p;if(!l){let m=d.reduce((h,y)=>h+y.length+2,2);l=e.options.lineWidth>0&&m>e.options.lineWidth}if(l){let m=f;for(let h of d)m+=h?` -${s}${i}${h}`:` -`;return`${m} -${i}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function sl({indent:r,options:{commentString:e}},t,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let s=Vt(e(n),r);t.push(s.trimStart())}}function $n(r,e){let t=G(e)?e.value:e;for(let n of r)if(te(n)&&(n.key===e||n.key===t||G(n.key)&&n.key.value===t))return n}var Ee=class extends ls{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Zt,e),this.items=[]}static from(e,t,n){let{keepUndefined:i,replacer:s}=n,o=new this(e),a=(c,l)=>{if(typeof s=="function")l=s.call(t,c,l);else if(Array.isArray(s)&&!s.includes(c))return;(l!==void 0||i)&&o.items.push(fs(c,l,n))};if(t instanceof Map)for(let[c,l]of t)a(c,l);else if(t&&typeof t=="object")for(let c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){let n;te(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new _e(e,e?.value):n=new _e(e.key,e.value);let i=$n(this.items,n.key),s=this.schema?.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);G(i.value)&&Yc(n.value)?i.value.value=n.value:i.value=n.value}else if(s){let o=this.items.findIndex(a=>s(n,a)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){let t=$n(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let i=$n(this.items,e)?.value;return(!t&&G(i)?i.value:i)??void 0}has(e){return!!$n(this.items,e)}set(e,t){this.add(new _e(e,t),!0)}toJSON(e,t,n){let i=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(i);for(let s of this.items)il(t,i,s);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(let i of this.items)if(!te(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),ol(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};var ir={collection:"map",default:!0,nodeClass:Ee,tag:"tag:yaml.org,2002:map",resolve(r,e){return tr(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>Ee.from(r,e,t)};var We=class extends ls{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Hr,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=al(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=al(e);if(typeof n!="number")return;let i=this.items[n];return!t&&G(i)?i.value:i}has(e){let t=al(e);return typeof t=="number"&&t=0?e:null}var sr={collection:"seq",default:!0,nodeClass:We,tag:"tag:yaml.org,2002:seq",resolve(r,e){return rr(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>We.from(r,e,t)};var xn={identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify(r,e,t,n){return e=Object.assign({actualString:!0},e),ci(r,e,t,n)}};var li={identify:r=>r==null,createNode:()=>new F(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new F(null),stringify:({source:r},e)=>typeof r=="string"&&li.test.test(r)?r:e.options.nullStr};var Do={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new F(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&Do.test.test(r)){let n=r[0]==="t"||r[0]==="T";if(e===n)return r}return e?t.options.trueStr:t.options.falseStr}};function Ge({format:r,minFractionDigits:e,tag:t,value:n}){if(typeof n=="bigint")return String(n);let i=typeof n=="number"?n:Number(n);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let s=Object.is(n,-0)?"-0":JSON.stringify(n);if(!r&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let a=e-(s.length-o-1);for(;a-- >0;)s+="0"}return s}var cl={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ge},ll={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():Ge(r)}},dl={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(r){let e=new F(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:Ge};var ul=r=>typeof r=="bigint"||Number.isInteger(r),_h=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function I0(r,e,t){let{value:n}=r;return ul(n)&&n>=0?t+n.toString(e):Ge(r)}var fl={identify:r=>ul(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>_h(r,2,8,t),stringify:r=>I0(r,8,"0o")},pl={identify:ul,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>_h(r,0,10,t),stringify:Ge},hl={identify:r=>ul(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>_h(r,2,16,t),stringify:r=>I0(r,16,"0x")};var O0=[ir,sr,xn,li,Do,fl,pl,hl,cl,ll,dl];function D0(r){return typeof r=="bigint"||Number.isInteger(r)}var ml=({value:r})=>JSON.stringify(r),EN=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:ml},{identify:r=>r==null,createNode:()=>new F(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:ml},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:ml},{identify:D0,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(r,e,{intAsBigInt:t})=>t?BigInt(r):parseInt(r,10),stringify:({value:r})=>D0(r)?r.toString():JSON.stringify(r)},{identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:r=>parseFloat(r),stringify:ml}],AN={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},N0=[ir,sr].concat(EN,AN);var No={identify:r=>r instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(r,e){if(typeof atob=="function"){let t=atob(r.replace(/[\n\r]/g,"")),n=new Uint8Array(t.length);for(let i=0;i1&&e("Each pair must have its own sequence indicator");let i=n.items[0]||new _e(new F(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore} +`+Vt(l(r),c),a&&a()):d&&o&&o(),p}function AN({items:r},e,{flowChars:t,itemIndent:n}){let{indent:i,indentStep:s,flowCollectionPadding:o,options:{commentString:a}}=e;n+=s;let c=Object.assign({},e,{indent:n,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let h=0;hy=null);l||(l=d.length>u||g.includes(` +`)),h0&&(l||(l=d.reduce((b,v)=>b+v.length+2,2)+(g.length+2)>e.options.lineWidth)),l&&(g+=",")),y&&(g+=kr(g,n,a(y))),d.push(g),u=d.length}let{start:f,end:p}=t;if(d.length===0)return f+p;if(!l){let h=d.reduce((m,y)=>m+y.length+2,2);l=e.options.lineWidth>0&&h>e.options.lineWidth}if(l){let h=f;for(let m of d)h+=m?` +${s}${i}${m}`:` +`;return`${h} +${i}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function ol({indent:r,options:{commentString:e}},t,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let s=Vt(e(n),r);t.push(s.trimStart())}}function xn(r,e){let t=W(e)?e.value:e;for(let n of r)if(te(n)&&(n.key===e||n.key===t||W(n.key)&&n.key.value===t))return n}var Ee=class extends ls{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(er,e),this.items=[]}static from(e,t,n){let{keepUndefined:i,replacer:s}=n,o=new this(e),a=(c,l)=>{if(typeof s=="function")l=s.call(t,c,l);else if(Array.isArray(s)&&!s.includes(c))return;(l!==void 0||i)&&o.items.push(fs(c,l,n))};if(t instanceof Map)for(let[c,l]of t)a(c,l);else if(t&&typeof t=="object")for(let c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){let n;te(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new _e(e,e?.value):n=new _e(e.key,e.value);let i=xn(this.items,n.key),s=this.schema?.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);W(i.value)&&Xc(n.value)?i.value.value=n.value:i.value=n.value}else if(s){let o=this.items.findIndex(a=>s(n,a)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){let t=xn(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let i=xn(this.items,e)?.value;return(!t&&W(i)?i.value:i)??void 0}has(e){return!!xn(this.items,e)}set(e,t){this.add(new _e(e,t),!0)}toJSON(e,t,n){let i=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(i);for(let s of this.items)sl(t,i,s);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(let i of this.items)if(!te(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),al(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};var sr={collection:"map",default:!0,nodeClass:Ee,tag:"tag:yaml.org,2002:map",resolve(r,e){return rr(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>Ee.from(r,e,t)};var We=class extends ls{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Vr,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=cl(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=cl(e);if(typeof n!="number")return;let i=this.items[n];return!t&&W(i)?i.value:i}has(e){let t=cl(e);return typeof t=="number"&&t=0?e:null}var or={collection:"seq",default:!0,nodeClass:We,tag:"tag:yaml.org,2002:seq",resolve(r,e){return nr(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>We.from(r,e,t)};var $n={identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify(r,e,t,n){return e=Object.assign({actualString:!0},e),ci(r,e,t,n)}};var li={identify:r=>r==null,createNode:()=>new F(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new F(null),stringify:({source:r},e)=>typeof r=="string"&&li.test.test(r)?r:e.options.nullStr};var No={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&&No.test.test(r)){let n=r[0]==="t"||r[0]==="T";if(e===n)return r}return e?t.options.trueStr:t.options.falseStr}};function Ge({format:r,minFractionDigits:e,tag:t,value:n}){if(typeof n=="bigint")return String(n);let i=typeof n=="number"?n:Number(n);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let s=Object.is(n,-0)?"-0":JSON.stringify(n);if(!r&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let a=e-(s.length-o-1);for(;a-- >0;)s+="0"}return s}var ll={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ge},dl={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():Ge(r)}},ul={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(r){let e=new F(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:Ge};var fl=r=>typeof r=="bigint"||Number.isInteger(r),xh=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function N0(r,e,t){let{value:n}=r;return fl(n)&&n>=0?t+n.toString(e):Ge(r)}var pl={identify:r=>fl(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>xh(r,2,8,t),stringify:r=>N0(r,8,"0o")},hl={identify:fl,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>xh(r,0,10,t),stringify:Ge},ml={identify:r=>fl(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>xh(r,2,16,t),stringify:r=>N0(r,16,"0x")};var L0=[sr,or,$n,li,No,pl,hl,ml,ll,dl,ul];function F0(r){return typeof r=="bigint"||Number.isInteger(r)}var yl=({value:r})=>JSON.stringify(r),kN=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:yl},{identify:r=>r==null,createNode:()=>new F(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:yl},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:yl},{identify:F0,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})=>F0(r)?r.toString():JSON.stringify(r)},{identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:r=>parseFloat(r),stringify:yl}],PN={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},j0=[sr,or].concat(kN,PN);var Lo={identify:r=>r instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(r,e){if(typeof atob=="function"){let t=atob(r.replace(/[\n\r]/g,"")),n=new Uint8Array(t.length);for(let i=0;i1&&e("Each pair must have its own sequence indicator");let i=n.items[0]||new _e(new F(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore} ${i.key.commentBefore}`:n.commentBefore),n.comment){let s=i.value??i.key;s.comment=s.comment?`${n.comment} -${s.comment}`:n.comment}n=i}r.items[t]=te(n)?n:new _e(n)}}else e("Expected a sequence for this tag");return r}function $h(r,e,t){let{replacer:n}=t,i=new We(r);i.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;i.items.push(fs(a,c,t))}return i}var Lo={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Sh,createNode:$h};var ps=class r extends We{constructor(){super(),this.add=Ee.prototype.add.bind(this),this.delete=Ee.prototype.delete.bind(this),this.get=Ee.prototype.get.bind(this),this.has=Ee.prototype.has.bind(this),this.set=Ee.prototype.set.bind(this),this.tag=r.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let i of this.items){let s,o;if(te(i)?(s=Re(i.key,"",t),o=Re(i.value,s,t)):s=Re(i,"",t),n.has(s))throw new Error("Ordered maps must not include duplicate keys");n.set(s,o)}return n}static from(e,t,n){let i=$h(e,t,n),s=new this;return s.items=i.items,s}};ps.tag="tag:yaml.org,2002:omap";var Fo={collection:"seq",identify:r=>r instanceof Map,nodeClass:ps,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Sh(r,e),n=[];for(let{key:i}of t.items)G(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new ps,t)},createNode:(r,e,t)=>ps.from(r,e,t)};function L0({value:r,source:e},t){return e&&(r?xh:Eh).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var xh={identify:r=>r===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new F(!0),stringify:L0},Eh={identify:r=>r===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new F(!1),stringify:L0};var F0={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ge},j0={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r.replace(/_/g,"")),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():Ge(r)}},q0={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(r){let e=new F(parseFloat(r.replace(/_/g,""))),t=r.indexOf(".");if(t!==-1){let n=r.substring(t+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:Ge};var jo=r=>typeof r=="bigint"||Number.isInteger(r);function yl(r,e,t,{intAsBigInt:n}){let i=r[0];if((i==="-"||i==="+")&&(e+=1),r=r.substring(e).replace(/_/g,""),n){switch(t){case 2:r=`0b${r}`;break;case 8:r=`0o${r}`;break;case 16:r=`0x${r}`;break}let o=BigInt(r);return i==="-"?BigInt(-1)*o:o}let s=parseInt(r,t);return i==="-"?-1*s:s}function Ah(r,e,t){let{value:n}=r;if(jo(n)){let i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return Ge(r)}var B0={identify:jo,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>yl(r,2,2,t),stringify:r=>Ah(r,2,"0b")},U0={identify:jo,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>yl(r,1,8,t),stringify:r=>Ah(r,8,"0")},V0={identify:jo,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>yl(r,0,10,t),stringify:Ge},H0={identify:jo,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>yl(r,2,16,t),stringify:r=>Ah(r,16,"0x")};var hs=class r extends Ee{constructor(e){super(e),this.tag=r.tag}add(e){let t;te(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new _e(e.key,null):t=new _e(e,null),$n(this.items,t.key)||this.items.push(t)}get(e,t){let n=$n(this.items,e);return!t&&te(n)?G(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=$n(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new _e(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){let{replacer:i}=n,s=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof i=="function"&&(o=i.call(t,o,o)),s.items.push(fs(o,null,n));return s}};hs.tag="tag:yaml.org,2002:set";var qo={collection:"map",identify:r=>r instanceof Set,nodeClass:hs,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>hs.from(r,e,t),resolve(r,e){if(tr(r)){if(r.hasAllNullValues(!0))return Object.assign(new hs,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};function kh(r,e){let t=r[0],n=t==="-"||t==="+"?r.substring(1):r,i=o=>e?BigInt(o):Number(o),s=n.replace(/_/g,"").split(":").reduce((o,a)=>o*i(60)+i(a),i(0));return t==="-"?i(-1)*s:s}function z0(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Ge(r);let n="";e<0&&(n="-",e*=t(-1));let i=t(60),s=[e%i];return e<60?s.unshift(0):(e=(e-s[0])/i,s.unshift(e%i),e>=60&&(e=(e-s[0])/i,s.unshift(e))),n+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var gl={identify:r=>typeof r=="bigint"||Number.isInteger(r),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(r,e,{intAsBigInt:t})=>kh(r,t),stringify:z0},bl={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:r=>kh(r,!1),stringify:z0},ms={identify:r=>r instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(r){let e=r.match(ms.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,n,i,s,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,n-1,i,s||0,o||0,a||0,c),u=e[8];if(u&&u!=="Z"){let d=kh(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:r})=>r?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};var Ph=[ir,sr,xn,li,xh,Eh,B0,U0,V0,H0,F0,j0,q0,No,nr,Fo,Lo,qo,gl,bl,ms];var K0=new Map([["core",O0],["failsafe",[ir,sr,xn]],["json",N0],["yaml11",Ph],["yaml-1.1",Ph]]),W0={binary:No,bool:Do,float:dl,floatExp:ll,floatNaN:cl,floatTime:bl,int:pl,intHex:hl,intOct:fl,intTime:gl,map:ir,merge:nr,null:li,omap:Fo,pairs:Lo,seq:sr,set:qo,timestamp:ms},G0={"tag:yaml.org,2002:binary":No,"tag:yaml.org,2002:merge":nr,"tag:yaml.org,2002:omap":Fo,"tag:yaml.org,2002:pairs":Lo,"tag:yaml.org,2002:set":qo,"tag:yaml.org,2002:timestamp":ms};function vl(r,e,t){let n=K0.get(e);if(n&&!r)return t&&!n.includes(nr)?n.concat(nr):n.slice();let i=n;if(!i)if(Array.isArray(r))i=[];else{let s=Array.from(K0.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(r))for(let s of r)i=i.concat(s);else typeof r=="function"&&(i=r(i.slice()));return t&&(i=i.concat(nr)),i.reduce((s,o)=>{let a=typeof o=="string"?W0[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(W0).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}var kN=(r,e)=>r.keye.key?1:0,Bo=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?vl(e,"compat"):e?vl(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?G0:{},this.tags=vl(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,Zt,{value:ir}),Object.defineProperty(this,At,{value:xn}),Object.defineProperty(this,Hr,{value:sr}),this.sortMapEntries=typeof o=="function"?o:o===!0?kN:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function J0(r,e){let t=[],n=e.directives===!0;if(e.directives!==!1&&r.directives){let c=r.directives.toString(r);c?(t.push(c),n=!0):r.directives.docStart&&(n=!0)}n&&t.push("---");let i=tl(r,e),{commentString:s}=i.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=s(r.commentBefore);t.unshift(Vt(c,""))}let o=!1,a=null;if(r.contents){if(ne(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let u=s(r.contents.commentBefore);t.push(Vt(u,""))}i.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=Wr(r.contents,i,()=>a=null,c);a&&(l+=kr(l,"",s(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(Wr(r.contents,i));if(r.directives?.docEnd)if(r.comment){let c=s(r.comment);c.includes(` +${s.comment}`:n.comment}n=i}r.items[t]=te(n)?n:new _e(n)}}else e("Expected a sequence for this tag");return r}function Eh(r,e,t){let{replacer:n}=t,i=new We(r);i.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;i.items.push(fs(a,c,t))}return i}var Fo={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:$h,createNode:Eh};var ps=class r extends We{constructor(){super(),this.add=Ee.prototype.add.bind(this),this.delete=Ee.prototype.delete.bind(this),this.get=Ee.prototype.get.bind(this),this.has=Ee.prototype.has.bind(this),this.set=Ee.prototype.set.bind(this),this.tag=r.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let i of this.items){let s,o;if(te(i)?(s=Re(i.key,"",t),o=Re(i.value,s,t)):s=Re(i,"",t),n.has(s))throw new Error("Ordered maps must not include duplicate keys");n.set(s,o)}return n}static from(e,t,n){let i=Eh(e,t,n),s=new this;return s.items=i.items,s}};ps.tag="tag:yaml.org,2002:omap";var jo={collection:"seq",identify:r=>r instanceof Map,nodeClass:ps,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=$h(r,e),n=[];for(let{key:i}of t.items)W(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new ps,t)},createNode:(r,e,t)=>ps.from(r,e,t)};function q0({value:r,source:e},t){return e&&(r?Ah:kh).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Ah={identify:r=>r===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new F(!0),stringify:q0},kh={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:q0};var B0={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ge},U0={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r.replace(/_/g,"")),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():Ge(r)}},V0={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(r){let e=new F(parseFloat(r.replace(/_/g,""))),t=r.indexOf(".");if(t!==-1){let n=r.substring(t+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:Ge};var qo=r=>typeof r=="bigint"||Number.isInteger(r);function gl(r,e,t,{intAsBigInt:n}){let i=r[0];if((i==="-"||i==="+")&&(e+=1),r=r.substring(e).replace(/_/g,""),n){switch(t){case 2:r=`0b${r}`;break;case 8:r=`0o${r}`;break;case 16:r=`0x${r}`;break}let o=BigInt(r);return i==="-"?BigInt(-1)*o:o}let s=parseInt(r,t);return i==="-"?-1*s:s}function Ph(r,e,t){let{value:n}=r;if(qo(n)){let i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return Ge(r)}var H0={identify:qo,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>gl(r,2,2,t),stringify:r=>Ph(r,2,"0b")},z0={identify:qo,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>gl(r,1,8,t),stringify:r=>Ph(r,8,"0")},K0={identify:qo,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>gl(r,0,10,t),stringify:Ge},W0={identify:qo,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>gl(r,2,16,t),stringify:r=>Ph(r,16,"0x")};var hs=class r extends Ee{constructor(e){super(e),this.tag=r.tag}add(e){let t;te(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new _e(e.key,null):t=new _e(e,null),xn(this.items,t.key)||this.items.push(t)}get(e,t){let n=xn(this.items,e);return!t&&te(n)?W(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=xn(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new _e(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){let{replacer:i}=n,s=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof i=="function"&&(o=i.call(t,o,o)),s.items.push(fs(o,null,n));return s}};hs.tag="tag:yaml.org,2002:set";var Bo={collection:"map",identify:r=>r instanceof Set,nodeClass:hs,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>hs.from(r,e,t),resolve(r,e){if(rr(r)){if(r.hasAllNullValues(!0))return Object.assign(new hs,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};function Mh(r,e){let t=r[0],n=t==="-"||t==="+"?r.substring(1):r,i=o=>e?BigInt(o):Number(o),s=n.replace(/_/g,"").split(":").reduce((o,a)=>o*i(60)+i(a),i(0));return t==="-"?i(-1)*s:s}function G0(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Ge(r);let n="";e<0&&(n="-",e*=t(-1));let i=t(60),s=[e%i];return e<60?s.unshift(0):(e=(e-s[0])/i,s.unshift(e%i),e>=60&&(e=(e-s[0])/i,s.unshift(e))),n+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var bl={identify:r=>typeof r=="bigint"||Number.isInteger(r),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(r,e,{intAsBigInt:t})=>Mh(r,t),stringify:G0},vl={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:r=>Mh(r,!1),stringify:G0},ms={identify:r=>r instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(r){let e=r.match(ms.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,n,i,s,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,n-1,i,s||0,o||0,a||0,c),u=e[8];if(u&&u!=="Z"){let d=Mh(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:r})=>r?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};var Ch=[sr,or,$n,li,Ah,kh,H0,z0,K0,W0,B0,U0,V0,Lo,ir,jo,Fo,Bo,bl,vl,ms];var J0=new Map([["core",L0],["failsafe",[sr,or,$n]],["json",j0],["yaml11",Ch],["yaml-1.1",Ch]]),Y0={binary:Lo,bool:No,float:ul,floatExp:dl,floatNaN:ll,floatTime:vl,int:hl,intHex:ml,intOct:pl,intTime:bl,map:sr,merge:ir,null:li,omap:jo,pairs:Fo,seq:or,set:Bo,timestamp:ms},X0={"tag:yaml.org,2002:binary":Lo,"tag:yaml.org,2002:merge":ir,"tag:yaml.org,2002:omap":jo,"tag:yaml.org,2002:pairs":Fo,"tag:yaml.org,2002:set":Bo,"tag:yaml.org,2002:timestamp":ms};function wl(r,e,t){let n=J0.get(e);if(n&&!r)return t&&!n.includes(ir)?n.concat(ir):n.slice();let i=n;if(!i)if(Array.isArray(r))i=[];else{let s=Array.from(J0.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(ir)),i.reduce((s,o)=>{let a=typeof o=="string"?Y0[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Y0).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 MN=(r,e)=>r.keye.key?1:0,Uo=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?wl(e,"compat"):e?wl(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?X0:{},this.tags=wl(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,er,{value:sr}),Object.defineProperty(this,At,{value:$n}),Object.defineProperty(this,Vr,{value:or}),this.sortMapEntries=typeof o=="function"?o:o===!0?MN:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function Q0(r,e){let t=[],n=e.directives===!0;if(e.directives!==!1&&r.directives){let c=r.directives.toString(r);c?(t.push(c),n=!0):r.directives.docStart&&(n=!0)}n&&t.push("---");let i=rl(r,e),{commentString:s}=i.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=s(r.commentBefore);t.unshift(Vt(c,""))}let o=!1,a=null;if(r.contents){if(ne(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let u=s(r.contents.commentBefore);t.push(Vt(u,""))}i.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=Kr(r.contents,i,()=>a=null,c);a&&(l+=kr(l,"",s(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(Kr(r.contents,i));if(r.directives?.docEnd)if(r.comment){let c=s(r.comment);c.includes(` `)?(t.push("..."),t.push(Vt(c,""))):t.push(`... ${c}`)}else t.push("...");else{let c=r.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(Vt(s(c),"")))}return t.join(` `)+` -`}var En=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,nt,{value:zc});let i=null;typeof t=="function"||Array.isArray(t)?i=t:n===void 0&&t&&(n=t,t=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=s;let{version:o}=s;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Ar({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let e=Object.create(r.prototype,{[nt]:{value:zc}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=ne(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){ys(this.contents)&&this.contents.add(e)}addIn(e,t){ys(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=hh(this);e.anchor=!t||n.has(t)?mh(t||"a",n):t}return new zr(e.anchor)}createNode(e,t,n){let i;if(typeof t=="function")e=t.call({"":e},"",e),i=t;else if(Array.isArray(t)){let y=b=>typeof b=="number"||b instanceof String||b instanceof Number,g=t.filter(y).map(String);g.length>0&&(t=t.concat(g)),i=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:u}=n??{},{onAnchor:d,setAnchors:f,sourceObjects:p}=k0(this,o||"a"),m={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:p},h=Kr(e,u,m);return a&&ae(h)&&(h.flow=!0),f(),h}createPair(e,t,n={}){let i=this.createNode(e,null,n),s=this.createNode(t,null,n);return new _e(i,s)}delete(e){return ys(this.contents)?this.contents.delete(e):!1}deleteIn(e){return ds(e)?this.contents==null?!1:(this.contents=null,!0):ys(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return ae(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return ds(e)?!t&&G(this.contents)?this.contents.value:this.contents:ae(this.contents)?this.contents.getIn(e,t):void 0}has(e){return ae(this.contents)?this.contents.has(e):!1}hasIn(e){return ds(e)?this.contents!==void 0:ae(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=To(this.schema,[e],t):ys(this.contents)&&this.contents.set(e,t)}setIn(e,t){ds(e)?this.contents=t:this.contents==null?this.contents=To(this.schema,Array.from(e),t):ys(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let n;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Ar({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Ar({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let i=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new Bo(Object.assign(n,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:i,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},c=Re(this.contents,t??"",a);if(typeof s=="function")for(let{count:l,res:u}of a.anchors.values())s(u,l);return typeof o=="function"?_n(o,{"":c},"",c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return J0(this,e)}};function ys(r){if(ae(r))return!0;throw new Error("Expected a YAML collection as document contents")}var Uo=class extends Error{constructor(e,t,n,i){super(),this.name=e,this.code=n,this.message=i,this.pos=t}},or=class extends Uo{constructor(e,t,n){super("YAMLParseError",e,t,n)}},Vo=class extends Uo{constructor(e,t,n){super("YAMLWarning",e,t,n)}},Ch=(r,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:n,col:i}=t.linePos[0];t.message+=` at line ${n}, column ${i}`;let s=i-1,o=r.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="\u2026"+o.substring(a),s-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,s))){let a=r.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026 +`}var En=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,it,{value:Kc});let i=null;typeof t=="function"||Array.isArray(t)?i=t:n===void 0&&t&&(n=t,t=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=s;let{version:o}=s;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Ar({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let e=Object.create(r.prototype,{[it]:{value:Kc}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=ne(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){ys(this.contents)&&this.contents.add(e)}addIn(e,t){ys(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=yh(this);e.anchor=!t||n.has(t)?gh(t||"a",n):t}return new Hr(e.anchor)}createNode(e,t,n){let i;if(typeof t=="function")e=t.call({"":e},"",e),i=t;else if(Array.isArray(t)){let y=b=>typeof b=="number"||b instanceof String||b instanceof Number,g=t.filter(y).map(String);g.length>0&&(t=t.concat(g)),i=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:u}=n??{},{onAnchor:d,setAnchors:f,sourceObjects:p}=C0(this,o||"a"),h={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:p},m=zr(e,u,h);return a&&ae(m)&&(m.flow=!0),f(),m}createPair(e,t,n={}){let i=this.createNode(e,null,n),s=this.createNode(t,null,n);return new _e(i,s)}delete(e){return ys(this.contents)?this.contents.delete(e):!1}deleteIn(e){return ds(e)?this.contents==null?!1:(this.contents=null,!0):ys(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return ae(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return ds(e)?!t&&W(this.contents)?this.contents.value:this.contents:ae(this.contents)?this.contents.getIn(e,t):void 0}has(e){return ae(this.contents)?this.contents.has(e):!1}hasIn(e){return ds(e)?this.contents!==void 0:ae(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Ro(this.schema,[e],t):ys(this.contents)&&this.contents.set(e,t)}setIn(e,t){ds(e)?this.contents=t:this.contents==null?this.contents=Ro(this.schema,Array.from(e),t):ys(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let n;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Ar({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Ar({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let i=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new Uo(Object.assign(n,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:i,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},c=Re(this.contents,t??"",a);if(typeof s=="function")for(let{count:l,res:u}of a.anchors.values())s(u,l);return typeof o=="function"?_n(o,{"":c},"",c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return Q0(this,e)}};function ys(r){if(ae(r))return!0;throw new Error("Expected a YAML collection as document contents")}var Vo=class extends Error{constructor(e,t,n,i){super(),this.name=e,this.code=n,this.message=i,this.pos=t}},ar=class extends Vo{constructor(e,t,n){super("YAMLParseError",e,t,n)}},Ho=class extends Vo{constructor(e,t,n){super("YAMLWarning",e,t,n)}},Th=(r,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:n,col:i}=t.linePos[0];t.message+=` at line ${n}, column ${i}`;let s=i-1,o=r.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="\u2026"+o.substring(a),s-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,s))){let a=r.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026 `),o=a+o}if(/[^ ]/.test(o)){let a=1,c=t.linePos[1];c?.line===n&&c.col>i&&(a=Math.max(1,Math.min(c.col-i,80-s)));let l=" ".repeat(s)+"^".repeat(a);t.message+=`: ${o} ${l} -`}};function Pr(r,{flow:e,indicator:t,next:n,offset:i,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,u=a,d="",f="",p=!1,m=!1,h=null,y=null,g=null,b=null,v=null,S=null,_=null;for(let $ of r)switch(m&&($.type!=="space"&&$.type!=="newline"&&$.type!=="comma"&&s($.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!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?.type!=="flow-collection")&&$.source.includes(" ")&&(h=$),u=!0;break;case"comment":{u||s($,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let M=$.source.substring(1)||" ";d?d+=f+M:d=M,f="",l=!1;break}case"newline":l?d?d+=$.source:(!S||t!=="seq-item-ind")&&(c=!0):f+=$.source,l=!0,p=!0,(y||g)&&(b=$),u=!0;break;case"anchor":y&&s($,"MULTIPLE_ANCHORS","A node can have at most one anchor"),$.source.endsWith(":")&&s($.offset+$.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=$,_??(_=$.offset),l=!1,u=!1,m=!0;break;case"tag":{g&&s($,"MULTIPLE_TAGS","A node can have at most one tag"),g=$,_??(_=$.offset),l=!1,u=!1,m=!0;break}case t:(y||g)&&s($,"BAD_PROP_ORDER",`Anchors and tags must be after the ${$.source} indicator`),S&&s($,"UNEXPECTED_TOKEN",`Unexpected ${$.source} in ${e??"collection"}`),S=$,l=t==="seq-item-ind"||t==="explicit-key-ind",u=!1;break;case"comma":if(e){v&&s($,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),v=$,l=!1,u=!1;break}default:s($,"UNEXPECTED_TOKEN",`Unexpected ${$.type} token`),l=!1,u=!1}let E=r[r.length-1],k=E?E.offset+E.source.length:i;return 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?.type==="block-map"||n?.type==="block-seq")&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:v,found:S,spaceBefore:c,comment:d,hasNewline:p,anchor:y,tag:g,newlineAfterProp:b,end:k,start:_??k}}function An(r){if(!r)return null;switch(r.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(r.source.includes(` -`))return!0;if(r.end){for(let e of r.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of r.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(An(e.key)||An(e.value))return!0}return!1;default:return!0}}function Ho(r,e,t){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===r&&(n.source==="]"||n.source==="}")&&An(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function wl(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let i=typeof n=="function"?n:(s,o)=>s===o||G(s)&&G(o)&&s.value===o.value;return e.some(s=>i(s.key,t))}var Y0="All mapping items must start at the same column";function X0({composeNode:r,composeEmptyNode:e},t,n,i,s){let o=s?.nodeClass??Ee,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let u of n.items){let{start:d,key:f,sep:p,value:m}=u,h=Pr(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),y=!h.found;if(y){if(f&&(f.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==n.indent&&i(c,"BAD_INDENT",Y0)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(a.comment?a.comment+=` -`+h.comment:a.comment=h.comment);continue}(h.newlineAfterProp||An(f))&&i(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==n.indent&&i(c,"BAD_INDENT",Y0);t.atKey=!0;let g=h.end,b=f?r(t,f,h,i):e(t,g,d,null,h,i);t.schema.compat&&Ho(n.indent,f,i),t.atKey=!1,wl(t,a.items,b)&&i(g,"DUPLICATE_KEY","Map keys must be unique");let v=Pr(p??[],{indicator:"map-value-ind",next:m,offset:b.range[2],onError:i,parentIndent:n.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=v.end,v.found){y&&(m?.type==="block-map"&&!v.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&h.startr&&(r.type==="block-map"||r.type==="block-seq");function Z0({composeNode:r,composeEmptyNode:e},t,n,i,s){let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?Ee:We),l=new c(t.schema);l.flow=!0;let u=t.atRoot;u&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let d=n.offset+n.start.source.length;for(let y=0;y0){let y=Cr(m,h,t.options.strict,i);y.comment&&(l.comment?l.comment+=` -`+y.comment:l.comment=y.comment),l.range=[n.offset,h,y.offset]}else l.range=[n.offset,h,h];return l}function Rh(r,e,t,n,i,s){let o=t.type==="block-map"?X0(r,e,t,n,s):t.type==="block-seq"?Q0(r,e,t,n,s):Z0(r,e,t,n,s),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function eS(r,e,t,n,i){let s=n.tag,o=s?e.directives.tagName(s.source,f=>i(s,"TAG_RESOLVE_FAILED",f)):null;if(t.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=n,m=f&&s?f.offset>s.offset?f:s:f??s;m&&(!p||p.offsetf.tag===o&&f.collection===a);if(!c){let f=e.schema.knownTags[o];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?i(s,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Rh(r,e,t,i,o)}let l=Rh(r,e,t,i,o,c),u=c.resolve?.(l,f=>i(s,"TAG_RESOLVE_FAILED",f),e.options)??l,d=ne(u)?u:new F(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}function Ih(r,e,t){let n=e.offset,i=PN(e,r.options.strict,t);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};let s=i.mode===">"?F.BLOCK_FOLDED:F.BLOCK_LITERAL,o=e.source?CN(e.source):[],a=o.length;for(let h=o.length-1;h>=0;--h){let y=o[h][1];if(y===""||y==="\r")a=h;else break}if(a===0){let h=i.chomp==="+"&&o.length>0?` -`.repeat(Math.max(1,o.length-1)):"",y=n+i.length;return e.source&&(y+=e.source.length),{value:h,type:s,comment:i.comment,range:[n,y,y]}}let c=e.indent+i.indent,l=e.offset+i.length,u=0;for(let h=0;hc&&(c=y.length);else{y.length=a;--h)o[h][0].length>c&&(a=h+1);let d="",f="",p=!1;for(let h=0;hs===o||W(s)&&W(o)&&s.value===o.value;return e.some(s=>i(s.key,t))}var Z0="All mapping items must start at the same column";function eS({composeNode:r,composeEmptyNode:e},t,n,i,s){let o=s?.nodeClass??Ee,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let u of n.items){let{start:d,key:f,sep:p,value:h}=u,m=Pr(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),y=!m.found;if(y){if(f&&(f.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==n.indent&&i(c,"BAD_INDENT",Z0)),!m.anchor&&!m.tag&&!p){l=m.end,m.comment&&(a.comment?a.comment+=` +`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||An(f))&&i(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==n.indent&&i(c,"BAD_INDENT",Z0);t.atKey=!0;let g=m.end,b=f?r(t,f,m,i):e(t,g,d,null,m,i);t.schema.compat&&zo(n.indent,f,i),t.atKey=!1,_l(t,a.items,b)&&i(g,"DUPLICATE_KEY","Map keys must be unique");let v=Pr(p??[],{indicator:"map-value-ind",next:h,offset:b.range[2],onError:i,parentIndent:n.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=v.end,v.found){y&&(h?.type==="block-map"&&!v.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&m.startr&&(r.type==="block-map"||r.type==="block-seq");function rS({composeNode:r,composeEmptyNode:e},t,n,i,s){let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?Ee:We),l=new c(t.schema);l.flow=!0;let u=t.atRoot;u&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let d=n.offset+n.start.source.length;for(let y=0;y0){let y=Mr(h,m,t.options.strict,i);y.comment&&(l.comment?l.comment+=` +`+y.comment:l.comment=y.comment),l.range=[n.offset,m,y.offset]}else l.range=[n.offset,m,m];return l}function Oh(r,e,t,n,i,s){let o=t.type==="block-map"?eS(r,e,t,n,s):t.type==="block-seq"?tS(r,e,t,n,s):rS(r,e,t,n,s),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function nS(r,e,t,n,i){let s=n.tag,o=s?e.directives.tagName(s.source,f=>i(s,"TAG_RESOLVE_FAILED",f)):null;if(t.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=n,h=f&&s?f.offset>s.offset?f:s:f??s;h&&(!p||p.offsetf.tag===o&&f.collection===a);if(!c){let f=e.schema.knownTags[o];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?i(s,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Oh(r,e,t,i,o)}let l=Oh(r,e,t,i,o,c),u=c.resolve?.(l,f=>i(s,"TAG_RESOLVE_FAILED",f),e.options)??l,d=ne(u)?u:new F(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}function Dh(r,e,t){let n=e.offset,i=CN(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?TN(e.source):[],a=o.length;for(let m=o.length-1;m>=0;--m){let y=o[m][1];if(y===""||y==="\r")a=m;else break}if(a===0){let m=i.chomp==="+"&&o.length>0?` +`.repeat(Math.max(1,o.length-1)):"",y=n+i.length;return e.source&&(y+=e.source.length),{value:m,type:s,comment:i.comment,range:[n,y,y]}}let c=e.indent+i.indent,l=e.offset+i.length,u=0;for(let m=0;mc&&(c=y.length);else{y.length=a;--m)o[m][0].length>c&&(a=m+1);let d="",f="",p=!1;for(let m=0;mc||g[0]===" "?(f===" "?f=` `:!p&&f===` `&&(f=` @@ -105,98 +105,98 @@ ${l} `,p=!0):g===""?f===` `?d+=` `:f=` -`:(d+=f+g,f=" ",p=!1)}switch(i.chomp){case"-":break;case"+":for(let h=a;ht(n+f,p,m);switch(i){case"scalar":a=F.PLAIN,c=MN(s,l);break;case"single-quoted-scalar":a=F.QUOTE_SINGLE,c=TN(s,l);break;case"double-quoted-scalar":a=F.QUOTE_DOUBLE,c=RN(s,l);break;default:return t(r,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[n,n+s.length,n+s.length]}}let u=n+s.length,d=Cr(o,u,e,t);return{value:c,type:a,comment:d.comment,range:[n,u,d.offset]}}function MN(r,e){let t="";switch(r[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${r[0]}`;break}case"@":case"`":{t=`reserved character ${r[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),tS(r)}function TN(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),tS(r.slice(1,-1)).replace(/''/g,"'")}function tS(r){let e=/(.*?)\r?\n/sy,t=e.exec(r);if(!t)return r;let n,i;try{n=new RegExp("(?t(n+f,p,h);switch(i){case"scalar":a=F.PLAIN,c=RN(s,l);break;case"single-quoted-scalar":a=F.QUOTE_SINGLE,c=IN(s,l);break;case"double-quoted-scalar":a=F.QUOTE_DOUBLE,c=ON(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=Mr(o,u,e,t);return{value:c,type:a,comment:d.comment,range:[n,u,d.offset]}}function RN(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}`),iS(r)}function IN(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),iS(r.slice(1,-1)).replace(/''/g,"'")}function iS(r){let e=/(.*?)\r?\n/sy,t=e.exec(r);if(!t)return r;let n,i;try{n=new RegExp("(?s?r.slice(s,n+1):i)}else t+=i}return(r[r.length-1]!=='"'||r.length===1)&&e(r.length,"MISSING_CHAR",'Missing closing "quote'),t}function IN(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 DN(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 ON={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:` -`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function DN(r,e,t,n){let i=r.substr(e,t),o=i.length===t&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(o)}catch{let a=r.substr(e-2,t+2);return n(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}function Dh(r,e,t,n){let{value:i,type:s,comment:o,range:a}=e.type==="block-scalar"?Ih(r,e,n):Oh(e,r.options.strict,n),c=t?r.directives.tagName(t.source,d=>n(t,"TAG_RESOLVE_FAILED",d)):null,l;r.options.stringKeys&&r.atKey?l=r.schema[At]:c?l=NN(r.schema,i,c,t,n):e.type==="scalar"?l=LN(r,i,e,n):l=r.schema[At];let u;try{let d=l.resolve(i,f=>n(t??e,"TAG_RESOLVE_FAILED",f),r.options);u=G(d)?d:new F(d)}catch(d){let f=d instanceof Error?d.message:String(d);n(t??e,"TAG_RESOLVE_FAILED",f),u=new F(i)}return u.range=a,u.source=i,s&&(u.type=s),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function NN(r,e,t,n,i){if(t==="!")return r[At];let s=[];for(let a of r.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;let o=r.knownTags[t];return o&&!o.collection?(r.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),r[At])}function LN({atKey:r,directives:e,schema:t},n,i,s){let o=t.tags.find(a=>(a.default===!0||r&&a.default==="key")&&a.test?.test(n))||t[At];if(t.compat){let a=t.compat.find(c=>c.default&&c.test?.test(n))??t[At];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),u=`Value may be parsed as either ${c} or ${l}`;s(i,"TAG_RESOLVE_FAILED",u,!0)}}return o}function rS(r,e,t){if(e){t??(t=e.length);for(let n=t-1;n>=0;--n){let i=e[n];switch(i.type){case"space":case"comment":case"newline":r-=i.source.length;continue}for(i=e[++n];i?.type==="space";)r+=i.source.length,i=e[++n];break}}return r}var FN={composeNode:Nh,composeEmptyNode:_l};function Nh(r,e,t,n){let i=r.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=t,l,u=!0;switch(e.type){case"alias":l=jN(r,e,n),(a||c)&&n(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Dh(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=eS(FN,r,e,t,n),a&&(l.anchor=a.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);n(e,"RESOURCE_EXHAUSTION",f)}break;default:{let d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=_l(r,e.offset,void 0,null,t,n)),a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&r.options.stringKeys&&(!G(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),r.options.keepSourceTokens&&u&&(l.srcToken=e),l}function _l(r,e,t,n,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){let u={type:"scalar",offset:rS(e,t,n),indent:-1,source:""},d=Dh(r,u,a,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(d.spaceBefore=!0),s&&(d.comment=s,d.range[2]=c),d}function jN({options:r},{offset:e,source:t,end:n},i){let s=new zr(t.substring(1));s.source===""&&i(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&i(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+t.length,a=Cr(n,o,r.strict,i);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}function nS(r,e,{offset:t,start:n,value:i,end:s},o){let a=Object.assign({_directives:e},r),c=new En(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Pr(n,{indicator:"doc-start",next:i??s?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?Nh(l,i,u,o):_l(l,u.end,n,null,u,o);let d=c.contents.range[2],f=Cr(s,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[t,d,f.offset],c}function zo(r){if(typeof r=="number")return[r,r+1];if(Array.isArray(r))return r.length===2?r:[r[0],r[1]];let{offset:e,source:t}=r;return[e,e+(typeof t=="string"?t.length:1)]}function iS(r){let e="",t=!1,n=!1;for(let i=0;in(t,"TAG_RESOLVE_FAILED",d)):null,l;r.options.stringKeys&&r.atKey?l=r.schema[At]:c?l=FN(r.schema,i,c,t,n):e.type==="scalar"?l=jN(r,i,e,n):l=r.schema[At];let u;try{let d=l.resolve(i,f=>n(t??e,"TAG_RESOLVE_FAILED",f),r.options);u=W(d)?d:new F(d)}catch(d){let f=d instanceof Error?d.message:String(d);n(t??e,"TAG_RESOLVE_FAILED",f),u=new F(i)}return u.range=a,u.source=i,s&&(u.type=s),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function FN(r,e,t,n,i){if(t==="!")return r[At];let s=[];for(let a of r.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;let o=r.knownTags[t];return o&&!o.collection?(r.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),r[At])}function jN({atKey:r,directives:e,schema:t},n,i,s){let o=t.tags.find(a=>(a.default===!0||r&&a.default==="key")&&a.test?.test(n))||t[At];if(t.compat){let a=t.compat.find(c=>c.default&&c.test?.test(n))??t[At];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),u=`Value may be parsed as either ${c} or ${l}`;s(i,"TAG_RESOLVE_FAILED",u,!0)}}return o}function sS(r,e,t){if(e){t??(t=e.length);for(let n=t-1;n>=0;--n){let i=e[n];switch(i.type){case"space":case"comment":case"newline":r-=i.source.length;continue}for(i=e[++n];i?.type==="space";)r+=i.source.length,i=e[++n];break}}return r}var qN={composeNode:Fh,composeEmptyNode:Sl};function Fh(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=BN(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=Lh(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=nS(qN,r,e,t,n),a&&(l.anchor=a.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);n(e,"RESOURCE_EXHAUSTION",f)}break;default:{let d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=Sl(r,e.offset,void 0,null,t,n)),a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&r.options.stringKeys&&(!W(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),r.options.keepSourceTokens&&u&&(l.srcToken=e),l}function Sl(r,e,t,n,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){let u={type:"scalar",offset:sS(e,t,n),indent:-1,source:""},d=Lh(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 BN({options:r},{offset:e,source:t,end:n},i){let s=new Hr(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=Mr(n,o,r.strict,i);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}function oS(r,e,{offset:t,start:n,value:i,end:s},o){let a=Object.assign({_directives:e},r),c=new En(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Pr(n,{indicator:"doc-start",next:i??s?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?Fh(l,i,u,o):Sl(l,u.end,n,null,u,o);let d=c.contents.range[2],f=Mr(s,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[t,d,f.offset],c}function Ko(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 aS(r){let e="",t=!1,n=!1;for(let i=0;i{let o=zo(t);s?this.warnings.push(new Vo(o,n,i)):this.errors.push(new or(o,n,i))},this.directives=new Ar({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:i}=iS(this.prelude);if(n){let s=e.contents;if(t)e.comment=e.comment?`${e.comment} +`)+(s.substring(1)||" "),t=!0,n=!1;break;case"%":r[i+1]?.[0]!=="#"&&(i+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}var Wo=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,i,s)=>{let o=Ko(t);s?this.warnings.push(new Ho(o,n,i)):this.errors.push(new ar(o,n,i))},this.directives=new Ar({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:i}=aS(this.prelude);if(n){let s=e.contents;if(t)e.comment=e.comment?`${e.comment} ${n}`:n;else if(i||e.directives.docStart||!s)e.commentBefore=n;else if(ae(s)&&!s.flow&&s.items.length>0){let o=s.items[0];te(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${n} ${a}`:n}else{let o=s.commentBefore;s.commentBefore=o?`${n} -${o}`:n}}if(t){for(let s=0;s{let s=zo(e);s[0]+=t,this.onError(s,"BAD_DIRECTIVE",n,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=nS(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new or(zo(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){let n="Unexpected doc-end without preceding document";this.errors.push(new or(zo(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=Cr(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let n=this.doc.comment;this.doc.comment=n?`${n} -${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new or(zo(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let n=Object.assign({_directives:this.directives},this.options),i=new En(void 0,n);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,t,t],this.decorate(i,!1),yield i}}};var Lh=Symbol("break visit"),qN=Symbol("skip children"),sS=Symbol("remove item");function di(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),oS(Object.freeze([]),r,e)}di.BREAK=Lh;di.SKIP=qN;di.REMOVE=sS;di.itemAtPath=(r,e)=>{let t=r;for(let[n,i]of e){let s=t?.[n];if(s&&"items"in s)t=s.items[i];else return}return t};di.parentCollection=(r,e)=>{let t=di.itemAtPath(r,e.slice(0,-1)),n=e[e.length-1][0],i=t?.[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function oS(r,e,t){let n=t(e,r);if(typeof n=="symbol")return n;for(let i of["key","value"]){let s=e[i];if(s&&"items"in s){for(let o=0;o{let s=Ko(e);s[0]+=t,this.onError(s,"BAD_DIRECTIVE",n,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=oS(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 ar(Ko(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 ar(Ko(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=Mr(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 ar(Ko(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 jh=Symbol("break visit"),UN=Symbol("skip children"),cS=Symbol("remove item");function di(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),lS(Object.freeze([]),r,e)}di.BREAK=jh;di.SKIP=UN;di.REMOVE=cS;di.itemAtPath=(r,e)=>{let t=r;for(let[n,i]of e){let s=t?.[n];if(s&&"items"in s)t=s.items[i];else return}return t};di.parentCollection=(r,e)=>{let t=di.itemAtPath(r,e.slice(0,-1)),n=e[e.length-1][0],i=t?.[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function lS(r,e,t){let n=t(e,r);if(typeof n=="symbol")return n;for(let i of["key","value"]){let s=e[i];if(s&&"items"in s){for(let o=0;o":return"block-scalar-header"}return null}function ar(r){switch(r){case void 0:case" ":case` -`:case"\r":case" ":return!0;default:return!1}}var cS=new Set("0123456789ABCDEFabcdef"),UN=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),$l=new Set(",[]{}"),VN=new Set(` ,[]{} -\r `),Bh=r=>!r||VN.has(r),Wo=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===` +`: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 cr(r){switch(r){case void 0:case" ":case` +`:case"\r":case" ":return!0;default:return!1}}var uS=new Set("0123456789ABCDEFabcdef"),HN=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),$l=new Set(",[]{}"),zN=new Set(` ,[]{} +\r `),Vh=r=>!r||zN.has(r),Go=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===` `?!0:t==="\r"?this.buffer[e+1]===` `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===" ";)t=this.buffer[++n+e];if(t==="\r"){let i=this.buffer[n+e+1];if(i===` `||!i&&!this.atEnd)return e+n+1}return t===` -`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&ar(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&ethis.indentValue&&!ar(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&ar(t)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Bh),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let i=this.getLine();if(i===null)return this.setNext("flow");if((n!==-1&&n=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&cr(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&ethis.indentValue&&!cr(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===":")&&cr(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(Vh),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let i=this.getLine();if(i===null)return this.setNext("flow");if((n!==-1&&n"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>ar(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,n;e:for(let s=this.pos;n=this.buffer[s];++s)switch(n){case" ":t+=1;break;case` +`,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=>cr(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 Sl,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,i;for(;i=this.buffer[++n];)if(i===":"){let s=this.buffer[n+1];if(ar(s)||e&&$l.has(s))break;t=n}else if(ar(i)){let s=this.buffer[n+1];if(i==="\r"&&(s===` +`&&s>=this.pos&&s+1+t>a)e=s;else break}while(!0);return yield xl,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,i;for(;i=this.buffer[++n];)if(i===":"){let s=this.buffer[n+1];if(cr(s)||e&&$l.has(s))break;t=n}else if(cr(i)){let s=this.buffer[n+1];if(i==="\r"&&(s===` `?(n+=1,i=` `,s=this.buffer[n+1]):t=n),s==="#"||e&&$l.has(s))break;if(i===` -`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&$l.has(i))break;t=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield Sl,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Bh),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,n=this.charAt(1);if(ar(n)||t&&$l.has(n)){t?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!ar(t)&&t!==">";)t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if(UN.has(t))t=this.buffer[++e];else if(t==="%"&&cS.has(this.buffer[e+1])&&cS.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` +`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&$l.has(i))break;t=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield xl,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Vh),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,n=this.charAt(1);if(cr(n)||t&&$l.has(n)){t?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!cr(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(HN.has(t))t=this.buffer[++e];else if(t==="%"&&uS.has(this.buffer[e+1])&&uS.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===` -`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===" "||e&&n===" ");let i=t-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=t),i}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};var Go=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t>1;this.lineStarts[s]=0;)switch(r[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;r[++e]?.type==="space";);return r.splice(e,r.length)}function El(r,e){if(e.length<1e5)Array.prototype.push.apply(r,e);else for(let t=0;t0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let n=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in n?n.indent:0:t.type==="flow-collection"&&n.type==="document"&&(t.indent=0),t.type==="flow-collection"&&dS(t),n.type){case"document":n.value=t;break;case"block-scalar":n.props.push(t);break;case"block-map":{let i=n.items[n.items.length-1];if(i.value){n.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=t;else{Object.assign(i,{key:t,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{let i=n.items[n.items.length-1];i.value?n.items.push({start:[],value:t}):i.value=t;break}case"flow-collection":{let i=n.items[n.items.length-1];!i||i.value?n.items.push({start:[],key:t,sep:[]}):i.sep?i.value=t:Object.assign(i,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){let i=t.items[t.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&lS(i.start)===-1&&(t.indent===0||i.start.every(s=>s.type!=="comment"||s.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 Jo=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t>1;this.lineStarts[s]=0;)switch(r[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;r[++e]?.type==="space";);return r.splice(e,r.length)}function Al(r,e){if(e.length<1e5)Array.prototype.push.apply(r,e);else for(let t=0;t0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let n=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in n?n.indent:0:t.type==="flow-collection"&&n.type==="document"&&(t.indent=0),t.type==="flow-collection"&&pS(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&&fS(i.start)===-1&&(t.indent===0||i.start.every(s=>s.type!=="comment"||s.indent=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,i=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",s=[];if(i&&t.sep&&!t.value){let o=[];for(let a=0;ae.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(s=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||t.value?(s.push(this.sourceToken),e.items.push({start:s}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):i||t.value?(s.push(this.sourceToken),e.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(kn(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(uS(t.key)&&!kn(t.sep,"newline")){let o=gs(t.start),a=t.key,c=t.sep;c.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else s.length>0?t.sep=t.sep.concat(s,this.sourceToken):t.sep.push(this.sourceToken);else if(kn(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=gs(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||i?e.items.push({start:s,key:null,sep:[this.sourceToken]}):kn(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);i||t.value?(e.items.push({start:s,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!kn(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&e.items.push({start:s});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){El(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||kn(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:i,sep:[]}):t.sep?this.stack.push(i):Object.assign(t,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let i=xl(n),s=gs(i);dS(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(` +`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.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]?.value?.end;if(Array.isArray(i)){Al(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,i=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",s=[];if(i&&t.sep&&!t.value){let o=[];for(let a=0;ae.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(s=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||t.value?(s.push(this.sourceToken),e.items.push({start:s}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):i||t.value?(s.push(this.sourceToken),e.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(kn(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(hS(t.key)&&!kn(t.sep,"newline")){let o=gs(t.start),a=t.key,c=t.sep;c.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else s.length>0?t.sep=t.sep.concat(s,this.sourceToken):t.sep.push(this.sourceToken);else if(kn(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=gs(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||i?e.items.push({start:s,key:null,sep:[this.sourceToken]}):kn(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);i||t.value?(e.items.push({start:s,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!kn(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&e.items.push({start:s});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){Al(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||kn(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:i,sep:[]}):t.sep?this.stack.push(i):Object.assign(t,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let i=El(n),s=gs(i);pS(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(` `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(` -`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=xl(e),n=gs(t);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=xl(e),n=gs(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};function HN(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new Go||null,prettyErrors:e}}function fS(r,e={}){let{lineCounter:t,prettyErrors:n}=HN(e),i=new Jo(t?.addNewLine),s=new Ko(e),o=null;for(let a of s.compose(i.parse(r),!0,r.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new or(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(Ch(r,t)),o.warnings.forEach(Ch(r,t))),o}function ui(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let i=fS(r,t);if(!i)return null;if(i.warnings.forEach(s=>rl(i.options.logLevel,s)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:n},t))}var WN=r=>r/2**32|0,GN=r=>r>>>0;function pS(r,e,t,n){let i=WN(t),s=GN(t);r.setUint32(e,n?s:i,n),r.setUint32(e+4,n?i:s,n)}function hS(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}var Uh=r=>r?`"${r}" `:"";function JN(r,e=""){if(typeof r!="number")throw new TypeError(Uh(e)+"expected number, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError(Uh(e)+"expected integer >= 0, got "+r);return r}function Al(r,e,t=""){if(hS(r)&&(e===void 0||r.length===e))return r;e!==void 0&&JN(e,"length");let n=hS(r),i=e!==void 0?` of length ${e}`:"",s=n?`length=${r.length}`:`type=${typeof r}`,o=Uh(t)+"expected Uint8Array"+i+", got "+s;throw n?new RangeError(o):new TypeError(o)}var YN=(r,e)=>{if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof r)},mS=(r,e)=>{YN(r,e);let t=Object.getPrototypeOf(r);if(t!==Object.prototype&&t!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(r,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function Vh(r,e=!0){if(r.destroyed)throw new Error("hash was destroyed");if(e&&r.finished)throw new Error("digest() was already called")}function yS(r,e){Al(r,void 0,"output");let t=e.outputLen;if(!(r.length>=t))throw new RangeError('"output" expected length >= '+t)}function bs(...r){for(let e=0;e>>e}function Pl(r,e){return r<>>32-e>>>0}var XN=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",QN=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function De(r){if(Al(r),XN)return r.toHex();let e="";for(let t=0;t= '+t)}function bs(...r){for(let e=0;e>>e}function Ml(r,e){return r<>>32-e>>>0}var ZN=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",eL=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Ne(r){if(kl(r),ZN)return r.toHex();let e="";for(let t=0;to.command!=="advance_checkpoint");t.kind==="rebuild"&&n.push("Mirror rebuild"),t.kind==="initial"&&i.some(o=>["put_remote","move_remote","delete_remote","delete_local"].includes(o.command))&&n.push("First sync"),t.summary.blocking_issues>0&&!i.length&&n.push("Blocking issues");let s=i.filter(o=>o.command==="delete_remote").length;return s>e.maxDeletions&&n.push(`${s} deletions`),{safe:n.length===0,reasons:n}}var Fx=require("obsidian");var Pm=3e4,D2=64*1024;function Mm(r){return Pm+Math.ceil(r/D2)*1e3}var As=class extends w{constructor(e,t){super(e,t),this.name="NetworkError"}},In=class extends w{constructor(t,n,i,s){super(t,n);this.status=i;this.retryAfterMs=s;this.name="HttpStatusError"}},Am=new Set([408,425,429,500,502,503,504]),N2=new Set(["network_unreachable","network_timeout","authority_unavailable","mirror_enrollment_unreachable","authority_adoption_unreachable"]);function ks(r){if(r instanceof In)return Am.has(r.status);if(r&&typeof r=="object"){let e=r.status;if(typeof e=="number"&&Am.has(e))return!0;let t=r.code;if(typeof t=="string"&&N2.has(t))return!0}return!1}function L2(r){return Am.has(r)}var F2={attempts:4,baseDelayMs:500,maxDelayMs:3e4,sleep:U2,random:Math.random};function Cm(r,e,t){let n=Math.min(e.maxDelayMs,e.baseDelayMs*2**r),i=Math.round(n/2+e.random()*n/2);return t===void 0?i:Math.min(Math.max(i,t),6e4)}function jx(r,e=F2){return async t=>{for(let n=0;;n+=1){V2(t.signal);let i;try{let s=await r(t);if(!L2(s.status)||n+1>=e.attempts)return s;i=aa(s.headers)}catch(s){if(H2(s)&&t.signal?.aborted||!ks(s)||n+1>=e.attempts)throw s}await e.sleep(Cm(n,e,i),t.signal)}}}function qx(r=j2()){return r?e=>q2(e,r.fetch,r.AbortController,r.headers):e=>B2(e)}function j2(){try{if(typeof require!="function")return null;let r=require("electron").remote,e=r?.net?.fetch,t=r?.getGlobal?.("AbortController"),n=r?.getGlobal?.("Object");return!e||!r?.net||typeof t!="function"||!n?null:{fetch:e.bind(r.net),AbortController:t,headers:i=>n.fromEntries(i)}}catch{return null}}async function q2(r,e,t=AbortController,n=i=>Object.fromEntries(i)){let{signal:i,dispose:s}=Bx(r.signal,r.timeoutMs??Pm),o=new t,a=()=>o.abort();i.aborted?a():i.addEventListener("abort",a,{once:!0});try{let c={...r.headers??{}};r.contentType&&!Object.keys(c).some(f=>f.toLowerCase()==="content-type")&&(c["content-type"]=r.contentType);let l,u;try{l=await e(r.url,{method:r.method,headers:c,body:r.body,signal:o.signal}),u=await l.arrayBuffer()}catch(f){throw km(f,r.signal,i)}let d=new TextDecoder().decode(u);if(r.throw!==!1&&l.status>=400)throw new In(`http_${l.status}`,`Request failed with status ${l.status}`,l.status);return{status:l.status,headers:n(l.headers),arrayBuffer:u,json:z2(d),text:d}}finally{i.removeEventListener("abort",a),s()}}async function B2(r,e=t=>(0,Fx.requestUrl)(t)){let{signal:t,timeoutMs:n,...i}=r,{signal:s,dispose:o}=Bx(t,n??Pm);try{return await new Promise((a,c)=>{let l=()=>c(km(s.reason,t,s));if(s.aborted)return l();s.addEventListener("abort",l,{once:!0}),e(i).then(a,u=>c(km(u,t,s))).finally(()=>s.removeEventListener("abort",l))})}finally{o()}}function aa(r){if(!r)return;let e=Object.entries(r).find(([i])=>i.toLowerCase()==="retry-after")?.[1];if(!e)return;let t=Number(e);if(Number.isFinite(t)&&t>=0)return t*1e3;let n=Date.parse(e);if(Number.isFinite(n))return Math.max(0,n-Date.now())}function U2(r,e){return new Promise((t,n)=>{if(e?.aborted)return n(oa());let i=window.setTimeout(()=>{e?.removeEventListener("abort",s),t()},r),s=()=>{window.clearTimeout(i),n(oa())};e?.addEventListener("abort",s,{once:!0})})}function V2(r){if(r?.aborted)throw oa()}function oa(){return new DOMException("Synchronization stopped.","AbortError")}function H2(r){return r instanceof DOMException&&r.name==="AbortError"}function Bx(r,e){let t=new AbortController,n=()=>t.abort(oa());r?.aborted?n():r?.addEventListener("abort",n,{once:!0});let i=window.setTimeout(()=>t.abort(new As("network_timeout","Connect did not respond in time.")),e);return{signal:t.signal,dispose:()=>{window.clearTimeout(i),r?.removeEventListener("abort",n)}}}function km(r,e,t){if(e?.aborted)return oa();if(t.aborted)return t.reason instanceof As?t.reason:new As("network_timeout","Connect did not respond in time.");if(r instanceof w)return r;let n=r&&typeof r=="object"?r.status:void 0;if(typeof n=="number")return new In(`http_${n}`,`Request failed with status ${n}`,n);let i=r instanceof Error&&r.message?` (${r.message})`:"";return new As("network_unreachable",`Connect could not be reached${i}.`)}function z2(r){if(!r.trim())return null;try{return JSON.parse(r)}catch{return null}}var Hx={maxAgeDays:90,maxFiles:5e3,maxRuns:1e3};function ld(r,e,t=new Date().toISOString()){return{id:crypto.randomUUID(),collectionId:r,startedAt:t,finishedAt:t,outcome:"event",files:[],...e}}function zx(r){return r.summary!==void 0}function Kx(r,e,t){if(r.command==="advance_checkpoint")return null;let n=Em(r),i=r.command==="move_local"||r.command==="move_remote"?r.source.path:void 0;return{path:n.path,...i&&i!==n.path?{fromPath:i}:{},kind:n.kind,direction:n.direction,action:n.action,status:e.status,at:t,...e.failure?.message?{message:e.failure.message}:{}}}var ad=class{constructor(e,t){this.inner=e;this.onReceipt=t;this.seen=new Map}read(){return this.inner.read()}async write(e){await this.inner.write(e);let t=e.batch;if(!t)return;let n=t.plan.fingerprint,i=this.seen.get(n);if(i===void 0){this.seen.set(n,{receipts:t.receipts.length,actions:new Map(t.plan.actions.map(o=>[o.action_id,o]))});return}let s=i.receipts;i.receipts=t.receipts.length;for(let o of t.receipts.slice(s)){let a=i.actions.get(o.action_id);a&&this.onReceipt(a,o)}}};function Wx(r){if(r.summary!==void 0)return r.summary;let e=i=>r.files.filter(s=>s.direction===i&&s.status==="completed").length;return[[e("download"),"downloaded"],[e("upload"),"uploaded"],[r.files.filter(i=>i.direction==="attention"||i.status==="conflicted").length,"conflicts"],[r.files.filter(i=>i.status==="rejected").length,"rejected"]].filter(([i])=>i>0).map(([i,s])=>`${i} ${s}`).join(" \xB7 ")||"No file changes"}function Gx(r,e){return r.flatMap(t=>t.summary!==void 0?t.path===e?[{run:t,file:K2(t)}]:[]:t.files.filter(n=>n.path===e||n.fromPath===e).map(n=>({run:t,file:n}))).sort((t,n)=>n.file.at.localeCompare(t.file.at))}function K2(r){return{path:r.path??"",kind:"document",direction:"attention",action:"review",status:"completed",at:r.finishedAt,...r.message?{message:r.message}:{}}}function Jx(r,e){let t=e.trim().toLowerCase();return t?r.flatMap(n=>{if(n.summary!==void 0)return n.path?.toLowerCase().includes(t)?[n]:[];let i=n.files.filter(s=>s.path.toLowerCase().includes(t)||s.fromPath?.toLowerCase().includes(t));return i.length?[{...n,files:i}]:[]}):[...r]}function Ux(r,e=Hx,t=Date.now()){let n=t-e.maxAgeDays*864e5,i=r.filter(a=>Date.parse(a.finishedAt)>=n),s=i.reduce((a,c)=>a+c.files.length,0),o=0;for(;(s>e.maxFiles||i.length-o>e.maxRuns)&&ot.finishedAt.localeCompare(n.finishedAt))}function G2(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;return typeof e.id=="string"&&typeof e.collectionId=="string"&&typeof e.startedAt=="string"&&typeof e.finishedAt=="string"&&typeof e.outcome=="string"&&Array.isArray(e.files)&&e.files.every(t=>!!t&&typeof t.path=="string"&&typeof t.at=="string")}var cd=class{constructor(e,t,n=Hx){this.adapter=e;this.path=t;this.limits=n;this.runs=[];this.writes=Promise.resolve()}async load(){await this.enqueue(async()=>{let e=await this.adapter.exists(this.path)?await this.adapter.read(this.path):"",t=Ux(W2(e),this.limits),n=Vx(t);e!==n&&await this.adapter.write(this.path,n),this.runs=t})}list(e){return this.runs.filter(t=>e===void 0||t.collectionId===e)}append(e){return this.enqueue(async()=>{let t=Ux([...this.runs,e],this.limits);t.length!==this.runs.length+1||!await this.adapter.exists(this.path)?await this.rewrite(t):await this.adapter.append(this.path,`${JSON.stringify(e)} +`),this.runs=t})}acknowledge(e){return this.enqueue(async()=>{let t=this.runs.map(n=>n.id===e?{...n,needsAcknowledgement:!1}:n);await this.rewrite(t),this.runs=t})}clear(){return this.enqueue(async()=>{let e=this.runs.filter(t=>t.needsAcknowledgement);await this.rewrite(e),this.runs=e})}rewrite(e){return this.adapter.write(this.path,Vx(e))}enqueue(e){return this.writes=this.writes.then(e,e),this.writes}};function Vx(r){return r.map(e=>`${JSON.stringify(e)} +`).join("")}var J2={create:"created",update:"updated",rename:"renamed",delete:"deleted",replace:"replaced",fix:"conflict",review:"needs review"};function Yx(r){let e=r.direction==="attention"?"Conflict recorded":`${r.direction==="download"?"Download":"Upload"} \xB7 ${J2[r.action]}`;return r.status==="completed"?e:`${e} \xB7 ${r.status}`}function Ps(r,e=new Date){let t=new Date(r);if(!Number.isFinite(t.getTime()))return r;let n=t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}),i=a=>new Date(a.getFullYear(),a.getMonth(),a.getDate()).getTime(),s=Math.round((i(e)-i(t))/864e5);return s===0?`Today ${n}`:s===1?`Yesterday ${n}`:`${t.toLocaleDateString(void 0,{day:"numeric",month:"short",...t.getFullYear()===e.getFullYear()?{}:{year:"numeric"}})} ${n}`}function Y2(r,e){let t=Object.create(null);for(let s=0;su));d++);if(di(c,"a")),Xx(e,t).forEach(c=>i(c,"b")),n.sort((c,l)=>c.oStart-l.oStart);let s=[],o=0;function a(c){c>o&&(s.push({stable:!0,buffer:"o",bufferStart:o,bufferLength:c-o,bufferContent:e.slice(o,c)}),o=c)}for(;n.length;){let c=n.shift(),l=c.oStart,u=c.oStart+c.oLength,d=[c];for(a(l);n.length;){let f=n[0],p=f.oStart;if(p>u)break;u=Math.max(u,p+f.oLength),d.push(n.shift())}if(d.length===1){if(c.abLength>0){let f=c.ab==="a"?r:t;s.push({stable:!0,buffer:c.ab,bufferStart:c.abStart,bufferLength:c.abLength,bufferContent:f.slice(c.abStart,c.abStart+c.abLength)})}}else{let f={a:[r.length,-1,e.length,-1],b:[t.length,-1,e.length,-1]};for(;d.length;){c=d.shift();let b=c.oStart,v=b+c.oLength,S=c.abStart,_=S+c.abLength,E=f[c.ab];E[0]=Math.min(S,E[0]),E[1]=Math.max(_,E[1]),E[2]=Math.min(b,E[2]),E[3]=Math.max(v,E[3])}let p=f.a[0]+(l-f.a[2]),h=f.a[1]+(u-f.a[3]),m=f.b[0]+(l-f.b[2]),y=f.b[1]+(u-f.b[3]),g={stable:!1,aStart:p,aLength:h-p,aContent:r.slice(p,h),oStart:l,oLength:u-l,oContent:e.slice(l,u),bStart:m,bLength:y-m,bContent:t.slice(m,y)};s.push(g)}o=u}return a(e.length),s}function Qx(r,e,t,n){n=Object.assign({excludeFalseConflicts:!0,stringSeparator:/\s+/},n),typeof r=="string"&&(r=r.split(n.stringSeparator)),typeof e=="string"&&(e=e.split(n.stringSeparator)),typeof t=="string"&&(t=t.split(n.stringSeparator));let s=[],o=X2(r,e,t),a=[];function c(){a.length&&s.push({ok:a}),a=[]}function l(u,d){if(u.length!==d.length)return!1;for(let f=0;f{u.stable?a.push(...u.bufferContent):n.excludeFalseConflicts&&l(u.aContent,u.bContent)?a.push(...u.aContent):(c(),s.push({conflict:{a:u.aContent,aIndex:u.aStart,o:u.oContent,oIndex:u.oStart,b:u.bContent,bIndex:u.bStart}}))}),c(),s}function Zx(r,e,t,n){if(e===t||t===r)return{clean:!0,text:e};if(e===r)return{clean:!0,text:t};let i=[Tm(r),Tm(e),Tm(t)];if(i.every(d=>d===null)){let d=Om(r,e,t);return d===null?{clean:!1,reason:"The line edits could not be merged safely."}:{clean:!0,text:d}}let[s,o,a]=i;if(!s||!o||!a||s.open!==o.open||o.open!==a.open)return{clean:!1,reason:"Only one version has frontmatter."};let c=e$(s.close,o.close,a.close);if(c===null)return{clean:!1,reason:"Both versions changed the frontmatter fence."};let l=Q2(s.frontmatter,o.frontmatter,a.frontmatter);if(l===null)return{clean:!1,reason:"Both versions changed the same field."};let u=Om(s.body,o.body,a.body);return u===null?{clean:!1,reason:"The line edits could not be merged safely."}:l.length&&!n(l.join(` `)+` `)?{clean:!1,reason:"The combined frontmatter would not be valid YAML."}:{clean:!0,text:[o.open,...l,c].join(` -`)+u}}function Pm(r){let e=r.split(` +`)+u}}function Tm(r){let e=r.split(` `);if(e[0]?.replace(/^\uFEFF/,"").replace(/\r$/,"")!=="---")return null;let t=e.findIndex((i,s)=>s>0&&i.replace(/\r$/,"")==="---");if(t<0)return null;let n=e.slice(0,t+1).join(` -`);return{open:e[0],frontmatter:e.slice(1,t),close:e[t],body:r.slice(n.length)}}function Tm(r,e,t){if(e===t||t===r)return e;if(e===r)return t;let n=r.split(` +`);return{open:e[0],frontmatter:e.slice(1,t),close:e[t],body:r.slice(n.length)}}function Om(r,e,t){if(e===t||t===r)return e;if(e===r)return t;let n=r.split(` `),i=e.split(` `),s=t.split(` -`);if(n.length*(i.length+s.length)>4e6)return null;let a=J$(i,n,s,{excludeFalseConflicts:!0}),c=[];for(let l of a){if(l.conflict)return null;for(let u of l.ok??[])c.push(u)}return c.join(` -`)}var Cm="\0preamble";function Mm(r){let e=[Cm],t=new Map([[Cm,[]]]),n=Cm;for(let i of r){let s=/^([^\s#-][^:]*):(?:\s|$)/u.exec(i)?.[1];if(s!==void 0){if(t.has(s))return null;n=s,e.push(s),t.set(s,[i])}else t.get(n)?.push(i)}return{order:e,blocks:new Map([...t].filter(([,i])=>i.length>0).map(([i,s])=>[i,s.join(` -`)]))}}function Y2(r,e,t){let n=Mm(r),i=Mm(e),s=Mm(t),o=(l,u)=>{let d=new Set(l.order.filter(f=>u.blocks.has(f)));return l.order.filter(f=>d.has(f)).join(` +`),o=0;for(;oo&&c>o&&l>o&&n[a-1]===i[c-1]&&n[a-1]===s[l-1];)a-=1,c-=1,l-=1;if((a-o)*(c+l-2*o)>4e6)return null;let d=Qx(i.slice(o,c),n.slice(o,a),s.slice(o,l),{excludeFalseConflicts:!0}),f=[];for(let p of d){if(p.conflict)return null;for(let h of p.ok??[])f.push(h)}return n.slice(0,o).concat(f,n.slice(a)).join(` +`)}var Rm="\0preamble";function Im(r){let e=[Rm],t=new Map([[Rm,[]]]),n=Rm;for(let i of r){let s=/^([^\s#-][^:]*):(?:\s|$)/u.exec(i)?.[1];if(s!==void 0){if(t.has(s))return null;n=s,e.push(s),t.set(s,[i])}else t.get(n)?.push(i)}return{order:e,blocks:new Map([...t].filter(([,i])=>i.length>0).map(([i,s])=>[i,s.join(` +`)]))}}function Q2(r,e,t){let n=Im(r),i=Im(e),s=Im(t),o=(l,u)=>{let d=new Set(l.order.filter(f=>u.blocks.has(f)));return l.order.filter(f=>d.has(f)).join(` `)!==u.order.filter(f=>d.has(f)).join(` -`)};if(!n||!i||!s||o(n,i)||o(n,s))return Tm(r.join(` +`)};if(!n||!i||!s||o(n,i)||o(n,s)||o(i,s))return Om(r.join(` `),e.join(` `),t.join(` `))?.split(` -`)??null;let a=new Map;for(let l of new Set([...i.order,...s.order,...n.order])){let u=X$(n.blocks.get(l),i.blocks.get(l),s.blocks.get(l));if(u===null)return null;u!==void 0&&a.set(l,u)}let c=i.order.filter(l=>a.has(l));for(let[l,u]of s.order.entries()){if(!a.has(u)||c.includes(u))continue;let d=s.order.slice(0,l).reverse().find(f=>c.includes(f));c.splice(d===void 0?0:c.indexOf(d)+1,0,u)}return c.flatMap(l=>(a.get(l)??"").split(` -`))}function X$(r,e,t){return e===t?e:e===r?t:t===r?e:null}function $i(r){return[...r.normalize("NFC")].map(e=>e.toLowerCase()).join("").normalize("NFC")}function Rm(r){let e=new Map;for(let t of r){let n=$i(t),i=e.get(n)??[];i.push(t),e.set(n,i)}return[...e.values()].filter(t=>t.length>1)}function Q$(r,e,t){let n=new Set([...e].map($i)),i=[],s=[];for(let o of[...r].sort((a,c)=>a[0]c[0]?1:0)){let a=[...o].sort();if(a.some(c=>t.has(c))||new Set(a).size!==a.length){s.push(a);continue}for(let c of a.slice(1)){let l=c.lastIndexOf("/"),u=c.lastIndexOf("."),d=u>l+1?c.slice(u):"",f=d?c.slice(0,-d.length):c,p=2,m;do m=`${f} (${p++})${d}`;while(n.has($i(m)));n.add($i(m)),i.push({from:c,to:m})}}return{renames:i,manual:s}}function X2(r){try{let e=(0,z.parseYaml)(r);return e===null||typeof e=="object"&&!Array.isArray(e)}catch{return!1}}var On=".mdbase/connect-role.json",ca=".mdbase/authority-adoption.json",la=".mdbase/authority-adoption-snapshot.json",Q2="mdbase-obsidian-connect",Dn="mirrors",Z2="mdbase-obsidian-connect-blobs",Nn="manifests",Ln="chunks",ld=1024*1024,eF=32*1024*1024,Z$=2e3;function xi(r){if(!Number.isSafeInteger(r)||r<0||r>eF)throw new w("file_too_large","Binary sync supports files up to 32 MiB on this device. Exclude this file's folder to continue.")}var tF="mdbase-connect-access-",rF="mdbase-connect-refresh-",nF="mdbase-connect-adoption-",iF=300*1e3,sF=[".git",".trash",".mdbase"],oF=new Set([".git",".mdbase",".trash","node_modules","_contracts","_schemas","_types","_views"]),Im=["image","audio","video","pdf","other"],ua=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function at(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function fr(r){let e=r?.file_classes??[];if(e.some(s=>!Im.includes(s))||new Set(e).size!==e.length)throw new w("invalid_file_materialization","Selected file media classes must be valid and unique.");let t=[...e].sort((s,o)=>Im.indexOf(s)-Im.indexOf(o)),n=r?.excluded_folders??[];if(n.some(s=>typeof s!="string"||!s.trim()))throw new w("invalid_file_materialization","Excluded folders cannot be empty.");let i=n.map(s=>yn(s.trim())).sort((s,o)=>s.toLocaleLowerCase().localeCompare(o.toLocaleLowerCase()));if(i.length>100)throw new w("invalid_file_materialization","File sync supports at most 100 excluded folders.");if(new Set(i.map(s=>s.toLocaleLowerCase())).size!==i.length)throw new w("invalid_file_materialization","Excluded folders must be unique on portable filesystems.");for(let s of i)da(s,!0);return{file_classes:t,excluded_folders:i}}function sx(r){let e=r.includes(".")?r.slice(r.lastIndexOf(".")+1).toLowerCase():"";return["avif","bmp","gif","jpeg","jpg","png","svg","webp"].includes(e)?"image":["flac","m4a","mp3","oga","ogg","opus","wav"].includes(e)?"audio":["3gp","mkv","mov","mp4","webm"].includes(e)?"video":e==="pdf"?"pdf":"other"}function ex(r){if(r.conflicts.length)throw new w("authority_import_path_conflict",`${r.conflicts.length} filename conflicts prevent uploading. Review the paths in Sync and rename the conflicting files before retrying. Nothing was renamed or excluded.`)}function aF(r,e,t=sx(e)){if(!r.file_classes.includes(t))return!1;let n=(0,z.normalizePath)(e);return!r.excluded_folders.some(i=>n===i||n.startsWith(`${i}/`))}var cF=/\.(?:md|base)$/,ox=/\.(?:md|base)$/i;function da(r,e=!1){let t=yn(r),n=t.split("/");if(t.length>1024||!e&&ox.test(t)||n.some(i=>i.startsWith(".")||oF.has(i.toLowerCase())||/[<>"|?*]/u.test(i)||/^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/iu.test(i)))throw new w("invalid_file_path",`Collection file path ${t} is hidden, reserved, or non-portable.`);return t}async function dd(r){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",r));return{size:r.byteLength,content_digest:`sha256:${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}`}}async function Dm(r){let e=[],t=0;for await(let s of r){if(!(s instanceof Uint8Array))throw new w("file_integrity_failed","A binary stream returned an invalid chunk.");s.byteLength&&(t+=s.byteLength,xi(t),e.push(Uint8Array.from(s)))}let n=new Uint8Array(t),i=0;for(let s of e)n.set(s,i),i+=s.byteLength;return n.buffer}function tx(r){let e=r.includes(".")?r.slice(r.lastIndexOf(".")+1).toLowerCase():"";return{avif:"image/avif",gif:"image/gif",jpeg:"image/jpeg",jpg:"image/jpeg",png:"image/png",svg:"image/svg+xml",webp:"image/webp",flac:"audio/flac",m4a:"audio/mp4",mp3:"audio/mpeg",ogg:"audio/ogg",opus:"audio/opus",wav:"audio/wav",mov:"video/quicktime",mp4:"video/mp4",webm:"video/webm",pdf:"application/pdf"}[e]}async function lF(r,e){if(r!==void 0){if(!e)return JSON.stringify(r);if(r instanceof ArrayBuffer)return r;if(ArrayBuffer.isView(r))return Uint8Array.from(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)).buffer;if(r instanceof Blob)return r.arrayBuffer();throw new w("invalid_file_upload","The adoption upload body was not binary data.")}}function ud(r,e){if(e!=null)return e;if(!r.trim())return{};try{return JSON.parse(r)}catch{return{}}}var hd=L$(F$());function dF(){return async r=>{if(r.signal?.aborted)throw new DOMException("Enrollment cancelled.","AbortError");let e=await hd({url:r.url,method:r.method,headers:r.headers,body:r.body===void 0?void 0:JSON.stringify(r.body),contentType:r.body===void 0?void 0:"application/json",throw:!1,signal:r.signal});if(r.signal?.aborted)throw new DOMException("Enrollment cancelled.","AbortError");return{status:e.status,body:ud(e.text,e.json),retryAfterMs:aa(e.headers)}}}function uF(){return async r=>{if(r.signal?.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");let e=await lF(r.body,r.rawBody),t=await hd({url:r.url,method:r.method,headers:r.headers,body:e,contentType:e===void 0||r.rawBody?void 0:"application/json",throw:!1,signal:r.signal});if(r.signal?.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");return{status:t.status,body:ud(t.text,t.json),retryAfterMs:aa(t.headers),headers:t.headers}}}var Nm=class{constructor(e,t,n=hd,i,s){this.send=n;this.onFileProgress=i;this.signal=s;this.credentials=typeof t=="string"?{token:()=>Promise.resolve(t)}:t;let o;try{o=new URL(e)}catch{throw new w("invalid_sync_url","Sync URL must be an absolute authority endpoint.")}if(!(o.protocol==="https:"||o.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(o.hostname))||o.username||o.password||o.search||o.hash||!/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/sync\/?$/i.test(o.pathname))throw new w("invalid_sync_url","Sync URL must identify one authority sync endpoint.");this.syncUrl=o.href.replace(/\/$/,""),this.filesUrl=this.syncUrl.replace(/\/sync$/u,"/files")}openSession(){return this.request("POST","sessions")}snapshot(e,t){let n=new URLSearchParams({snapshot_id:e});return t&&n.set("page",t),this.request("GET",`snapshot?${n.toString()}`)}fileSnapshot(e,t){let n=new URLSearchParams({snapshot_id:e});return t&&n.set("page",t),this.request("GET",`files/snapshot?${n.toString()}`)}async*downloadFile(e){xi(e.size);let t=crypto.randomUUID();try{let n=0;this.onFileProgress?.({direction:"download",path:e.path,transferredBytes:n,totalBytes:e.size});let i=await this.fileRequest("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:t,file_id:e.file_id,revision:e.revision});if(i.protocol_version!==1||i.type!=="file_transfer"||i.transfer_id!==t||i.direction!=="download"||i.protection!=="transport_tls"||i.total_size!==e.size||i.strategy.kind!=="object_ranges"||!Number.isSafeInteger(i.strategy.part_size)||i.strategy.part_size<=0)throw new w("invalid_sync_response","The authority returned an incompatible file download session.");let s=Math.ceil(e.size/i.strategy.part_size);for(let o=0;o=300)throw this.responseError(c,"file_download_failed");let l=rx(c.headers,"content-length");if(l!==void 0&&Number(l)!==a||c.arrayBuffer.byteLength!==a)throw new w("file_integrity_failed","Hosted authority returned a file part with the wrong length.");n+=a,this.onFileProgress?.({direction:"download",path:e.path,transferredBytes:n,totalBytes:e.size}),a&&(yield new Uint8Array(c.arrayBuffer))}}finally{await this.fileRequest("DELETE",`transfers/${encodeURIComponent(t)}`).catch(()=>{})}}async uploadFile(e,t){xi(e.size);let n=await this.fileRequest("POST","uploads",e);if(n.protocol_version!==1||n.type!=="file_transfer"||n.transfer_id!==e.transfer_id||n.direction!=="upload"||n.protection!=="transport_tls"||n.total_size!==e.size||!["object_put","object_multipart"].includes(n.strategy.kind))throw new w("invalid_sync_response","Authority returned an incompatible file upload session.");let i=n.strategy.kind==="object_multipart"?n.strategy.part_size:Math.max(1,e.size);if(!Number.isSafeInteger(i)||i<=0)throw new w("invalid_sync_response","Authority returned an invalid upload part size.");let s=new Lm(t),o=Math.max(1,Math.ceil(e.size/i));if(n.received.some(d=>!Number.isSafeInteger(d)||d<0||d>=o)||new Set(n.received).size!==n.received.length)throw new w("invalid_sync_response","Authority returned invalid upload progress.");let a=n.uploaded_parts??[];if(a.some((d,f)=>!Number.isSafeInteger(d.part_number)||d.part_number<1||d.part_number>o||!d.etag||d.etag.length>255||f>0&&a[f-1].part_number>=d.part_number)||(n.strategy.kind==="object_multipart"?a.length!==n.received.length||a.some((d,f)=>d.part_number-1!==n.received[f]):a.length!==0))throw new w("invalid_sync_response","Authority returned invalid uploaded part receipts.");let c=n.received.reduce((d,f)=>{let p=f*i;return d+Math.min(i,Math.max(0,e.size-p))},0);if(this.onFileProgress?.({direction:"upload",path:e.path,transferredBytes:c,totalBytes:e.size}),n.received.length===o)return this.commitUpload(e.transfer_id,a);let l=new Set(n.received),u=Array.from({length:o},()=>{});for(let d of a)u[d.part_number-1]=d;for(let d=0;d=300)throw new In(y.status===429||y.status>=500?"authority_unavailable":"file_upload_failed",`Object storage returned HTTP ${y.status}.`,y.status);if(c+=p,this.onFileProgress?.({direction:"upload",path:e.path,transferredBytes:c,totalBytes:e.size}),n.strategy.kind==="object_multipart"){let g=rx(y.headers,"etag");if(!g)throw new w("invalid_sync_response","Object storage omitted a multipart ETag.");u[d]={part_number:d+1,etag:g}}}return await s.expectEnd(),this.commitUpload(e.transfer_id,u.filter(d=>d!==void 0))}async commitUpload(e,t){let n=await this.fileRequest("POST",`uploads/${encodeURIComponent(e)}/commit`,{protocol_version:1,type:"commit_file_upload",transfer_id:e,parts:t});if(n.protocol_version!==1||n.type!=="file_upload_committed"||n.transfer_id!==e)throw new w("invalid_sync_response","Authority returned an invalid file upload receipt.");return n}async moveFile(e){let t=await this.fileRequest("POST",`${encodeURIComponent(e.file_id)}/move`,e);if(t.protocol_version!==1||t.type!=="file_moved"||t.mutation_id!==e.mutation_id)throw new w("invalid_sync_response","Authority returned an invalid file move receipt.");return t}async deleteFile(e){let t=await this.fileRequest("POST",`${encodeURIComponent(e.file_id)}/delete`,e);if(t.protocol_version!==1||t.type!=="file_deleted"||t.mutation_id!==e.mutation_id||t.file_id!==e.file_id)throw new w("invalid_sync_response","Authority returned an invalid file delete receipt.");return t}changes(e,t=200){let n=new URLSearchParams({after:String(e),limit:String(t)});return this.request("GET",`changes?${n.toString()}`)}mutate(e){return this.request("POST","mutations",e)}async request(e,t,n){return this.requestAt(this.syncUrl,e,t,n)}async fileRequest(e,t,n){return this.requestAt(this.filesUrl,e,t,n)}async requestAt(e,t,n,i){let s=await this.authorized({url:`${e}/${n}`,method:t,body:i===void 0?void 0:JSON.stringify(i),contentType:i===void 0?void 0:"application/json",throw:!1}),o=ud(s.text,s.json);if(s.status<200||s.status>=300)throw this.responseError(s,"sync_failed");return o}async authorized(e){let t=s=>this.send({...e,headers:{authorization:`Bearer ${s}`},signal:this.signal}),n=await this.credentials.token(),i=await t(n);return i.status!==401||!this.credentials.renew?i:t(await this.credentials.renew(n))}responseError(e,t){let n=ud(e.text,e.json),i=at(n)&&at(n.error)?n.error:{},s=typeof i.code=="string"?i.code:e.status===401?"mirror_access_rejected":e.status===429||e.status>=500?"authority_unavailable":t;return new In(s,typeof i.message=="string"?i.message:`Sync request failed (${e.status}).`,e.status,aa(e.headers))}},Lm=class{constructor(e){this.remainder=new Uint8Array;this.iterator=e[Symbol.asyncIterator]()}async read(e){let t=new Uint8Array(new ArrayBuffer(e)),n=0;for(;n!["authorization","cookie","host","proxy-authorization","content-length"].includes(e.toLowerCase())))}function rx(r,e){return Object.entries(r).find(([n])=>n.toLowerCase()===e.toLowerCase())?.[1]}function ax(r){return[r.configDir||".obsidian",...sF].map(t=>(0,z.normalizePath)(t).replace(/\/+$/,""))}function Or(r,e){let t=yn(e);if(ax(r).some(n=>t===n||t.startsWith(`${n}/`)))throw new w("unsafe_mirror_path",`The collection authority attempted to write a reserved path: ${t}`);return t}function fe(r){if(r?.aborted)throw new DOMException("Synchronization cancelled.","AbortError")}function St(r,e){return r??new Error(`IndexedDB ${e} failed without an error detail.`)}function mF(r,e){let t=async a=>{fe(e);let c=await a();return fe(e),c},n=async function*(a){fe(e);for await(let c of a)fe(e),yield c,fe(e);fe(e)},i=r.uploadFile?.bind(r),s=r.moveFile?.bind(r),o=r.deleteFile?.bind(r);return{openSession:()=>t(()=>r.openSession()),snapshot:(a,c)=>t(()=>r.snapshot(a,c)),fileSnapshot:(a,c)=>t(()=>r.fileSnapshot(a,c)),downloadFile:a=>n(r.downloadFile(a)),...i?{uploadFile:(a,c)=>t(()=>i(a,n(c)))}:{},...s?{moveFile:a=>t(()=>s(a))}:{},...o?{deleteFile:a=>t(()=>o(a))}:{},changes:(a,c)=>t(()=>r.changes(a,c)),mutate:a=>t(()=>r.mutate(a))}}async function Ps(r,e){let t=(0,z.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let n="";for(let i of t.split("/")){n=n?`${n}/${i}`:i;let s=r.getAbstractFileByPath(n);if(!(s instanceof z.TFolder)){if(s)throw new w("mirror_path_collision",`A file blocks the mirror folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}var Fm=class{constructor(e,t=s=>e.delete(s,!0),n=()=>{},i=()=>{}){this.vault=e;this.trashFile=t;this.assertActive=n;this.observeWrite=i}async exists(e){let t=Or(this.vault,e);return this.vault.getAbstractFileByPath(t)!==null||await this.vault.adapter.exists(t)}async read(e){let t=await this.readText(e);if(t===null||typeof t=="string")return t;throw new w(t.code,t.reason)}async readText(e){let t=Or(this.vault,e);if(this.vault.getAbstractFileByPath(t)instanceof z.TFolder)throw new w("mirror_path_collision",`Expected a file at ${t}.`);let i;try{i=await this.vault.adapter.readBinary(t)}catch{try{if(!await this.vault.adapter.exists(t))return null}catch{}throw new w("file_read_failed",`Could not read ${t}.`)}try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(i)}catch{return{kind:"invalid",code:"invalid_utf8",reason:"File is not valid UTF-8.",revision:(await dd(i)).content_digest}}}async pathKind(e){let t=Or(this.vault,e);return(await this.vault.adapter.stat(t))?.type??null}async write(e,t,n){let i=Or(this.vault,e),s=n;if(s===void 0){let l=await this.readText(i);s=typeof l=="string"||l===null?l:void 0}let o=()=>new w("sync_plan_stale",`${i} changed before it could be written. Review sync again.`),a=i.lastIndexOf("/");a>=0&&await Ps(this.vault,i.slice(0,a));let c=this.vault.getAbstractFileByPath(i);if(c instanceof z.TFolder)throw new w("mirror_path_collision",`A folder blocks the mirror file ${i}.`);if(this.assertActive(),this.observeWrite(i),c instanceof z.TFile&&s===void 0)await this.vault.modify(c,t);else if(c instanceof z.TFile)await this.vault.process(c,l=>{if(this.assertActive(),l!==s&&l!==t)throw o();return t});else{if(s!==null)throw o();await this.vault.create(i,t)}}async move(e,t){let n=Or(this.vault,e),i=Or(this.vault,t),s=this.vault.getAbstractFileByPath(n);if(!(s instanceof z.TFile))throw new w("mirror_path_collision",`Expected a file at ${n}.`);if(this.vault.getAbstractFileByPath(i)!==null||await this.vault.adapter.exists(i))throw new w("mirror_path_collision",`A file or folder blocks the mirror path ${i}.`);let o=i.lastIndexOf("/");o>=0&&await Ps(this.vault,i.slice(0,o)),this.assertActive(),this.observeWrite(n),this.observeWrite(i),await this.vault.rename(s,i)}async remove(e){let t=Or(this.vault,e),n=this.vault.getAbstractFileByPath(t);if(n!=null){if(!(n instanceof z.TFile))throw new w("mirror_path_collision",`Expected a file at ${t}.`);this.assertActive(),this.observeWrite(t),await this.trashFile(n)}}async listMarkdown(e){return pd(this.vault).map(t=>(0,z.normalizePath)(t.path)).filter(t=>cF.test(t)&&!e.has(t)).filter(t=>!ax(this.vault).some(n=>t===n||t.startsWith(`${n}/`))).sort()}async inspectBinary(e){let t=da(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof z.TFile))throw new w("mirror_path_collision",`Expected a file at ${t}.`);xi(n.stat.size);let i=await this.vault.readBinary(n);return xi(i.byteLength),dd(i)}async writeBinary(e,t,n){let i=da(e),s=n===void 0?await this.inspectBinary(i):n,o=await Dm(t),a=i.lastIndexOf("/");a>=0&&await Ps(this.vault,i.slice(0,a));let c=await this.inspectBinary(i);if(c?.content_digest!==s?.content_digest||c?.size!==s?.size)throw new w("sync_plan_stale",`${i} changed before it could be written. Review sync again.`);let l=this.vault.getAbstractFileByPath(i);if(l instanceof z.TFolder)throw new w("mirror_path_collision",`A folder blocks the mirror file ${i}.`);this.assertActive(),this.observeWrite(i),l instanceof z.TFile?await this.vault.modifyBinary(l,o):await this.vault.createBinary(i,o)}async listBinary(e){return pd(this.vault).map(t=>(0,z.normalizePath)(t.path)).filter(t=>!ox.test(t)&&!e.has(t)).filter(t=>{try{return da(t),!0}catch{return!1}}).sort()}async readBinary(e){let t=da(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof z.TFile))throw new w("mirror_path_collision",`Expected a file at ${t}.`);xi(n.stat.size);let i=new Uint8Array(await this.vault.readBinary(n));return xi(i.byteLength),(async function*(){for(let s=0;s{}),a}n&&n.stage!==i&&await this.removeStage(n.stage,n.chunks).catch(()=>{})}async remove(e){let t=await this.manifest(e);await this.delete(Nn,this.manifestKey(e)),t&&await this.removeStage(t.stage,t.chunks)}async prune(e){let t=await this.open(),n=await new Promise((o,a)=>{let c=[],l=t.transaction(Nn,"readonly").objectStore(Nn).openCursor();l.onsuccess=()=>{let u=l.result;if(!u)return o(c);c.push([u.key,u.value]),u.continue()},l.onerror=()=>a(St(l.error,"manifest cursor"))}),i=new Set;for(let[o,a]of n)!Array.isArray(o)||o[0]!==this.namespace||typeof o[1]=="string"&&e.has(o[1])||(await this.delete(Nn,o),await this.removeStage(a.stage,a.chunks));for(let[o,a]of n)Array.isArray(o)&&o[0]===this.namespace&&typeof o[1]=="string"&&e.has(o[1])&&i.add(a.stage);let s=await new Promise((o,a)=>{let c=[],l=t.transaction(Ln,"readonly").objectStore(Ln).openKeyCursor();l.onsuccess=()=>{let u=l.result;if(!u)return o(c);let d=u.key,f=Array.isArray(d)&&typeof d[1]=="string"?d[1]:null;Array.isArray(d)&&d[0]===this.namespace&&(f===null||!i.has(f))&&c.push(d),u.continue()},l.onerror=()=>a(St(l.error,"chunk cursor"))});for(let o of s)await this.delete(Ln,o)}manifest(e){return this.get(Nn,this.manifestKey(e))}manifestKey(e){return[this.namespace,e]}chunkKey(e,t){return[this.namespace,e,t]}async removeStage(e,t){for(let n=0;n{let o=n.transaction(e,"readonly").objectStore(e).get(t);o.onsuccess=()=>i(o.result??null),o.onerror=()=>s(St(o.error,`read from ${e}`))})}async put(e,t,n){let i=await this.open();await new Promise((s,o)=>{let a=i.transaction(e,"readwrite");a.objectStore(e).put(n,t),a.oncomplete=()=>s(),a.onerror=()=>o(St(a.error,`write to ${e}`)),a.onabort=()=>o(St(a.error,`write to ${e}`))})}async delete(e,t){let n=await this.open();await new Promise((i,s)=>{let o=n.transaction(e,"readwrite");o.objectStore(e).delete(t),o.oncomplete=()=>i(),o.onerror=()=>s(St(o.error,`delete from ${e}`)),o.onabort=()=>s(St(o.error,`delete from ${e}`))})}close(){this.database?.then(e=>e.close(),()=>{}),this.database=null}open(){if(typeof indexedDB>"u")throw new w("storage_unavailable","IndexedDB is required for binary file sync.");return this.database??=new Promise((e,t)=>{let n=indexedDB.open(Z2,1);n.onupgradeneeded=()=>{n.result.objectStoreNames.contains(Nn)||n.result.createObjectStore(Nn),n.result.objectStoreNames.contains(Ln)||n.result.createObjectStore(Ln)},n.onerror=()=>t(St(n.error,"binary store open")),n.onsuccess=()=>e(n.result)}),this.database}},qm=class{constructor(e){this.key=e;this.database=null}async read(){let e=await this.open();return new Promise((t,n)=>{let i=e.transaction(Dn,"readonly").objectStore(Dn).get(this.key);i.onsuccess=()=>t(i.result??null),i.onerror=()=>n(St(i.error,"mirror state read"))})}async write(e){let t=await this.open();await new Promise((n,i)=>{let s=t.transaction(Dn,"readwrite");s.objectStore(Dn).put(e,this.key),s.oncomplete=()=>n(),s.onerror=()=>i(St(s.error,"mirror state write")),s.onabort=()=>i(St(s.error,"mirror state write"))})}async clear(){let e=await this.open();await new Promise((t,n)=>{let i=e.transaction(Dn,"readwrite");i.objectStore(Dn).delete(this.key),i.oncomplete=()=>t(),i.onerror=()=>n(St(i.error,"mirror state clear")),i.onabort=()=>n(St(i.error,"mirror state clear"))})}close(){this.database?.then(e=>e.close(),()=>{}),this.database=null}open(){if(typeof indexedDB>"u")throw new w("storage_unavailable","IndexedDB is required for persistent mirror state.");return this.database??=new Promise((e,t)=>{let n=indexedDB.open(Q2,1);n.onupgradeneeded=()=>{n.result.objectStoreNames.contains(Dn)||n.result.createObjectStore(Dn)},n.onerror=()=>t(St(n.error,"mirror state store open")),n.onsuccess=()=>e(n.result)}),this.database}},Bm=class r{constructor(e){this.key=e}static{this.active=new Set}async runExclusive(e){if(r.active.has(this.key))throw new w("mirror_busy","A mirror operation is already running for this vault.");r.active.add(this.key);try{return await e()}finally{r.active.delete(this.key)}}},fd=class{constructor(e,t,n={}){this.app=e;this.settingsHost=t;this.options=n;this.disposed=!1;this.lifetime=new AbortController;this.stateStores=new Map;this.blobStores=new Map;this.progress=null;this.fileProgress=null;this.syncAbort=null;this.statusRequest=null;this.mirrorOperationTail=Promise.resolve();this.adoptionMarker=null;this.adoptionBusy=!1;this.engineWrites=new Map;this.renewal=null;this.fileSystem=n.fileSystem??new Fm(e.vault,i=>e.fileManager.trashFile(i),()=>this.assertActive(),i=>this.noteEngineWrite(i)),this.enrollmentClient=n.enrollmentClient??new Fl({request:dF()}),this.adoptionClient=n.adoptionClient??new zl({request:uF()})}dispose(){this.disposed=!0,this.lifetime.abort(),this.cancelSync();for(let e of this.stateStores.values())e.close();for(let e of this.blobStores.values())e.close();this.stateStores.clear(),this.blobStores.clear()}async withLifetime(e,t){this.assertActive();let n=new AbortController,i=()=>n.abort();this.lifetime.signal.addEventListener("abort",i,{once:!0}),e?.addEventListener("abort",i,{once:!0}),e?.aborted&&n.abort();try{return fe(n.signal),await t(n.signal)}finally{this.lifetime.signal.removeEventListener("abort",i),e?.removeEventListener("abort",i)}}assertActive(){if(this.disposed)throw new DOMException("Plugin unloaded.","AbortError")}async withAdoptionOperation(e,t){if(this.adoptionBusy)throw new w("authority_adoption_busy","Stop the current move before changing its setup.");this.adoptionBusy=!0;try{return await this.withLifetime(e,t)}finally{this.adoptionBusy=!1}}async initialize(){this.adoptionMarker=await this.readAdoptionMarker();let e=this.settingsHost.getMirrorProfile();if(this.adoptionMarker&&e){if(this.adoptionMarker.phase==="adopted"&&this.adoptionMarker.session.requested.collectionId===e.collectionId){await this.assertMirror(e.collectionId),await this.clearAdoptionCheckpoint(this.adoptionMarker.session.adoptionId);return}throw new w("authority_adoption_state_conflict","This vault contains both an authority-adoption checkpoint and a mirror profile.")}}getProgress(){return this.progress?{...this.progress}:null}getFileProgress(){return this.fileProgress?{...this.fileProgress}:null}getAdoptionMarker(){return this.adoptionMarker?JSON.parse(JSON.stringify(this.adoptionMarker)):null}getAdoptionRecovery(){let e=this.adoptionMarker;if(!e)return null;try{if(this.app.secretStorage.getSecret(this.adoptionSecretId(e.session.adoptionId)))return null}catch{}let t=["waiting_for_approval","uploading"].includes(e.phase);return{canReset:t&&Date.parse(e.session.expiresAt)<=Date.now(),canReconnect:!t}}async resetExpiredAdoption(){return this.withAdoptionOperation(void 0,async()=>{let e=await this.readAdoptionMarker();if(e?.session.adoptionId!==this.adoptionMarker?.session.adoptionId)throw new w("authority_adoption_state_conflict","Move setup changed. Reopen Sync before recovering it.");if(this.adoptionMarker=e,!e||this.settingsHost.getMirrorProfile()||await this.app.vault.adapter.exists(On)||!this.getAdoptionRecovery()?.canReset)throw new w("authority_adoption_reset_unsafe","Only an expired move that never froze this vault can be reset locally.");await this.clearAdoptionCheckpoint(e.session.adoptionId)})}async reconnectAdoption(e){return this.withAdoptionOperation(e.signal,async t=>{let n=this.adoptionMarker;if(!n||!this.getAdoptionRecovery()?.canReconnect||this.settingsHost.getMirrorProfile())throw new w("authority_adoption_reconnect_unsafe","This move does not require hosted recovery.");let i=await this.enrollmentClient.enroll({controlUrl:n.session.controlUrl,collectionId:n.session.requested.collectionId,mirrorName:n.session.requested.mirrorName??n.session.requested.sourceName,mode:"read_write"},{...e,signal:t});if(i.collectionId!==n.session.requested.collectionId||i.mode!=="read_write")throw new w("authority_adoption_state_conflict","Connect approved a different collection or access mode; this vault remains protected.");return fe(t),await this.updateAdoptionPhase("adopted"),this.persistAdoptedMirror(n.session,i)})}getSelectiveSync(){return fr(this.settingsHost.getMirrorProfile()?.selectiveSync??this.adoptionMarker?.selective_sync)}async configureSelectiveSync(e){let t=this.requireProfile();await this.settingsHost.saveMirrorProfile({...t,selectiveSync:fr(e)})}assertLocalAuthorityWritable(){if(this.assertActive(),this.adoptionMarker&&["fenced","activating","adopted"].includes(this.adoptionMarker.phase))throw new w("local_authority_fenced",this.adoptionMarker.phase==="adopted"?"Hosted mdbase is now authoritative. Finish reconnecting this vault as its mirror before editing.":"This local authority is frozen while its exact snapshot is adopted by hosted mdbase.")}async adoptLocalCollection(e,t){return this.withAdoptionOperation(t.signal,n=>this.adoptLocalCollectionActive(e,{...t,signal:n}))}async adoptLocalCollectionActive(e,t){if(this.settingsHost.getMirrorProfile())throw new w("mirror_already_configured","This vault already mirrors a collection authority.");if(this.adoptionMarker)return this.resumeAdoptionActive(t);t.onProgress?.({stage:"checking"}),ex(await this.previewAdoption(e.selectiveSync,t.signal));let n=await this.ensurePortableCollectionIdentity(),i=await this.adoptionClient.begin({controlUrl:e.controlUrl,collectionId:n.collectionId,displayName:n.displayName,sourceName:e.mirrorName,retainMirror:!0,mirrorName:e.mirrorName},t);try{await this.storeAdoptionSecret(i)}catch(s){throw await this.adoptionClient.cancel(i,t).catch(()=>{}),s}return await this.writeAdoptionMarker({version:1,phase:"waiting_for_approval",session:Om(i),selective_sync:fr(e.selectiveSync),manifest_digest:null,source_revision:null,source_head:null}),await t.onVerification(Om(i)),this.runAdoptionWithRecovery(i,t)}async resumeAdoption(e={}){return this.withAdoptionOperation(e.signal,t=>this.resumeAdoptionActive({...e,signal:t}))}async resumeAdoptionActive(e){let t=this.adoptionMarker??await this.readAdoptionMarker();if(!t)throw new w("authority_adoption_not_found","This vault has no collection-adoption checkpoint.");this.adoptionMarker=t;let n=this.app.secretStorage.getSecret(this.adoptionSecretId(t.session.adoptionId));if(!n)throw new w("authority_adoption_credentials_missing","The collection-adoption credential is missing from Obsidian's secret store.");let i={...t.session,credential:n};return t.phase==="waiting_for_approval"&&await e.onVerification?.(Om(i)),this.runAdoptionWithRecovery(i,{...e,onVerification:s=>e.onVerification?.(s)})}async cancelAdoption(e){return this.withAdoptionOperation(e,t=>this.cancelAdoptionActive(t))}async cancelAdoptionActive(e){let t=this.adoptionMarker??await this.readAdoptionMarker();if(!t)return;if(["activating","adopted"].includes(t.phase))throw new w("authority_adoption_activation_started","Hosted activation has started and must be resumed; it can no longer be cancelled.");let n=this.app.secretStorage.getSecret(this.adoptionSecretId(t.session.adoptionId));if(!n)throw new w("authority_adoption_credentials_missing","The collection-adoption credential is missing from Obsidian's secret store.");await this.adoptionClient.cancel({...t.session,credential:n},{signal:e}),await this.clearAdoptionCheckpoint(t.session.adoptionId)}async enroll(e,t){return this.withLifetime(t.signal,n=>this.enrollActive(e,{...t,signal:n}))}async enrollActive(e,t){let n=await this.assertCanBecomeMirror(e.collectionId),i=await this.enrollmentClient.enroll({controlUrl:e.controlUrl,mirrorName:e.mirrorName,mode:e.mode,...n?{collectionId:n}:{}},t),s=await this.markMirror(i.collectionId);try{await this.persistEnrollment(i,e.selectiveSync)}catch(o){if(s)try{await this.app.vault.adapter.remove(On)}catch{throw new w("enrollment_recovery_required",`Enrollment settings could not be saved and the temporary role marker could not be removed: ${o instanceof Error?o.message:String(o)}`)}throw o}return this.requireProfile()}async inspect(){return this.withMirrorOperation(async()=>{let e=this.requireProfile();await this.assertMirror(e.collectionId);let t=await this.createMirror(),{plan:n,status:i}=await t.review();return{preview:_m(n),status:i}})}async preview(){return this.withMirrorOperation(async()=>{let e=this.requireProfile();await this.assertMirror(e.collectionId);let t=await this.createMirror();return _m(await t.inspect())})}async status(){if(this.statusRequest)return this.statusRequest;let e=this.readStatus();this.statusRequest=e;try{return await e}finally{this.statusRequest===e&&(this.statusRequest=null)}}async readStatus(){return this.withMirrorOperation(async()=>{let e=this.settingsHost.getMirrorProfile();return e?(await this.assertMirror(e.collectionId),(await this.createMirror()).status()):null})}async remoteChangesWaiting(){let e=this.requireProfile(),t=await this.stateStoreFor(e).read();if(!t||t.batch)return!0;let i=await(await this.transportFor(e)).changes(t.cursor,1);return i.reset_required||i.scope_epoch!==t.scope_epoch||i.head>t.cursor}async checkpointSummary(){let e=this.settingsHost.getMirrorProfile();if(!e)return null;let t=await this.stateStoreFor(e).read();return t?{cursor:t.cursor,generation:t.generation??0,batch:t.batch?`${t.batch.phase} at action ${t.batch.next_action}/${t.batch.plan.actions.length}`:null,failure:t.batch?.failure?`${t.batch.failure.code}: ${t.batch.failure.message}`:null}:null}async reconnect(){let e=this.requireProfile();this.assertThisDevice(e),await this.renewAccessToken(e);let t=await this.status();if(!t)throw new w("mirror_not_configured","The renewed mirror profile could not be loaded.");return t}async reauthorize(e){return this.withLifetime(e.signal,t=>this.reauthorizeActive({...e,signal:t}))}async reauthorizeActive(e){let t=this.requireProfile(),n=this.isOtherDevice(t),i=this.stateStoreFor(t);if((n?null:await i.read())?.batch)throw new w("mirror_recovery_required","Resume the durable synchronization checkpoint before approving this vault again.");let o=await this.enrollmentClient.enroll({controlUrl:t.controlUrl,mirrorName:t.name,mode:t.mode,collectionId:t.collectionId},e);if(o.collectionId!==t.collectionId)throw new w("mirror_identity_conflict","Connect approved a different collection. The existing mirror was not changed.");return this.withMirrorOperation(async()=>{let a=this.requireProfile();if(a.collectionId!==t.collectionId||a.replicaId!==t.replicaId||a.enrollmentId!==t.enrollmentId)throw new w("mirror_identity_conflict","The connection changed during approval. The current mirror was not changed.");let c=n?null:await i.read();if(c?.batch)throw new w("mirror_recovery_required","Resume the durable synchronization checkpoint before approving this vault again.");let l=nx(o,a.selectiveSync);return c&&o.replicaId!==t.replicaId&&await this.stateStoreFor(l).write({...c,replica_id:o.replicaId}),await this.persistEnrollment(o,a.selectiveSync),!n&&o.replicaId!==t.replicaId&&(this.clearCredentials(t),"clear"in i&&typeof i.clear=="function"&&await i.clear()),(await this.createMirror()).status()})}async conflictComparison(e){let t=this.requireProfile(),n=await this.transportFor(t),i=await n.openSession(),s={state:"absent"};if(e.entity==="record"){let l;do{let u=await n.snapshot(i.snapshot_id,l),d=u.records.find(f=>f.record_id===e.object_id);if(d){s={state:"exact",path:d.path,revision:d.revision,size:new TextEncoder().encode(d.document).byteLength,document:d.document};break}l=u.next_page}while(l)}else{let l;do{let u=await n.fileSnapshot(i.snapshot_id,l),d=u.files.find(f=>f.file_id===e.object_id);if(d){s={state:"exact",path:d.path,revision:d.content_digest,size:d.size,modifiedAt:d.modified_at};break}l=u.next_page}while(l)}let o=e.path??s.path,a={state:"absent"};if(o){let l=this.app.vault.getAbstractFileByPath(o);if(l instanceof z.TFile)if(e.entity==="record"){let u=await this.app.vault.cachedRead(l);a={state:"exact",path:o,size:new TextEncoder().encode(u).byteLength,modifiedAt:l.stat?.mtime?new Date(l.stat.mtime).toISOString():void 0,document:u}}else{let u=await this.fileSystem.inspectBinary(o);u&&(a={state:"exact",path:o,revision:u.content_digest,size:u.size,modifiedAt:l.stat?.mtime?new Date(l.stat.mtime).toISOString():void 0,resourceUrl:this.app.vault.getResourcePath(l)})}}if(!(await this.status())?.conflicts.some(l=>l.object_id===e.object_id&&l.decision_id===e.decision_id))throw new w("conflict_decision_stale","This file changed again while its versions were loading.");return{entity:e.entity,objectId:e.object_id,decisionId:e.decision_id,local:a,remote:s}}async recordComparison(e,t){let n=this.requireProfile(),i=await this.transportFor(n),s=await i.openSession(),o={state:"absent"},a;do{let u=await i.snapshot(s.snapshot_id,a),d=u.records.find(f=>f.record_id===e);if(d){o={state:"exact",path:d.path,revision:d.revision,size:new TextEncoder().encode(d.document).byteLength,document:d.document};break}a=u.next_page}while(a);let c={state:"absent"},l=this.app.vault.getAbstractFileByPath(Or(this.app.vault,t));if(l instanceof z.TFile){let u=await this.app.vault.cachedRead(l);c={state:"exact",path:l.path,size:new TextEncoder().encode(u).byteLength,document:u}}return{entity:"record",objectId:e,decisionId:"",local:c,remote:o}}async autoResolveConflicts(){let e=await this.status();if(!e?.conflicts.length||e.recovery_required)return[];let t=this.requireProfile(),n=await this.stateStoreFor(t).read();if(!n||n.batch)return[];let i=e.conflicts.filter(a=>a.entity==="record"&&n.planned_conflicts?.[a.object_id]?.conflict_kind==="both_changed").map(a=>a.object_id),s=i.length?await this.remoteRecords(new Set(i)):new Map,o=[];for(let a of e.conflicts){let c=n.planned_conflicts?.[a.object_id];if(c)try{o.push(await this.autoResolve(a,c,s.get(a.object_id)))}catch(l){if(l instanceof w&&["conflict_decision_stale","sync_plan_stale"].includes(l.code))continue;o.push({path:a.path??a.object_id,outcome:"unresolved",reason:l instanceof Error?l.message:String(l)})}}return o}async autoResolve(e,t,n){let{object_id:i,decision_id:s}=e,o=t.local.state==="exact"?t.local.object.path:null,a=t.remote.state==="exact"?t.remote.object.path:null,c=e.path??o??a??i;if(t.conflict_kind==="rejected")return{path:c,outcome:"unresolved",reason:e.message};if(o===null)return await this.resolveConflict(i,s,"remote"),{path:c,outcome:a?"restored":"took_hosted"};if(a===null)return await this.resolveConflict(i,s,"local"),{path:c,outcome:"kept_local"};if(e.entity==="record"&&t.conflict_kind==="both_changed"&&n&&n.path===o&&t.remote.state==="exact"&&n.revision===t.remote.object.revision){let u=t.ancestor_document,d=await this.fileSystem.read(o);if(u!==void 0&&d!==null){let f=Y$(u,d,n.document,X2);if(f.clean){await this.resolveConflict(i,s,"local");try{await this.fileSystem.write(o,f.text,d)}catch(p){let m=await this.writeConflictCopy(o,n.document,"hosted conflict copy");return{path:c,outcome:"kept_both",copyPath:m,reason:p instanceof Error?p.message:String(p)}}return{path:c,outcome:"merged"}}}}let l=await this.preserveConflictCopy(o);return await this.resolveConflict(i,s,"remote"),{path:c,outcome:"kept_both",copyPath:l}}async remoteRecords(e){let t=await this.transportFor(this.requireProfile()),n=await t.openSession(),i=new Map,s;do{let o=await t.snapshot(n.snapshot_id,s);for(let a of o.records)e.has(a.record_id)&&i.set(a.record_id,{path:a.path,revision:a.revision,document:a.document});s=i.size===e.size?void 0:o.next_page}while(s);return i}async writeConflictCopy(e,t,n){let i=Or(this.app.vault,e);return this.createConflictCopy(i,new TextEncoder().encode(t).buffer,n)}async createConflictCopy(e,t,n){let i=e.lastIndexOf("/"),s=e.lastIndexOf("."),o=s>i?e.slice(s):"",c=(o?e.slice(0,-o.length):e).replace(/(?: \((?:local|hosted) conflict copy(?: \d+)?\))+$/,""),l=new Uint8Array(t),u=1;for(;;){let d=`${c} (${n}${u===1?"":` ${u}`})${o}`;if(d===e){u+=1;continue}if(this.app.vault.getAbstractFileByPath(d)||await this.app.vault.adapter.exists(d)){try{let f=new Uint8Array(await this.app.vault.adapter.readBinary(d));if(f.length===l.length&&f.every((p,m)=>p===l[m]))return d}catch{}u+=1;continue}try{return await this.app.vault.createBinary(d,t),d}catch(f){if(!await this.app.vault.adapter.exists(d))throw f}}}async preserveConflictCopy(e){let t=Or(this.app.vault,e);if(!(this.app.vault.getAbstractFileByPath(t)instanceof z.TFile))throw new w("mirror_conflict_copy_missing",`No local file exists at ${t}.`);let i=await this.app.vault.adapter.readBinary(t);return this.createConflictCopy(t,i,"local conflict copy")}async disconnect(e){if(this.isSyncing())throw new w("mirror_busy","Stop the current synchronization before disconnecting.");return this.withMirrorOperation(()=>this.disconnectActive(e))}async disconnectActive(e){if(this.isSyncing())throw new w("mirror_busy","Stop the current synchronization before disconnecting.");let t=this.requireProfile(),n=this.stateStoreFor(t),i=await n.read();if(i?.batch)throw new w("mirror_recovery_required","Resume the durable synchronization checkpoint before disconnecting.");let s={removed:[],preserved:[]},o=await this.readMarker();o&&await this.app.vault.adapter.remove(On);try{await this.settingsHost.saveMirrorProfile(null)}catch(a){throw o&&await this.markMirror(t.collectionId),a}return this.isOtherDevice(t)||(this.clearCredentials(t),"clear"in n&&typeof n.clear=="function"&&await n.clear(),await this.blobStoreFor(t).prune(new Set)),e&&i&&await this.removeExactMirrorFiles(i,s),s}async sync(e,t,n,i){if(this.syncAbort)throw new w("mirror_busy","Synchronization is already running for this vault.");let s=new AbortController;this.syncAbort=s;try{return await this.withMirrorOperation(async()=>{let a=await(await this.createMirror(c=>{fe(s.signal),this.progress=c,t?.({...c})},s.signal,c=>{fe(s.signal),this.fileProgress=c,n?.({...c})},i)).apply(e.plan,{signal:s.signal});return fe(s.signal),a})}finally{this.progress=null,this.fileProgress=null,this.syncAbort=null}}cancelSync(){this.syncAbort?.abort()}noteEngineWrite(e){let t=Date.now();for(let[n,i]of this.engineWrites)t-i>Z$&&this.engineWrites.delete(n);this.engineWrites.set((0,z.normalizePath)(e),t)}isEngineWrite(e){let t=this.engineWrites.get((0,z.normalizePath)(e));return t!==void 0&&Date.now()-t<=Z$}isSyncing(){return this.syncAbort!==null}async resolveConflict(e,t,n){return this.withMirrorOperation(async()=>{let i=await this.createMirror();return await i.resolveConflict(e,t,n),i.status()})}async withMirrorOperation(e){let t=this.mirrorOperationTail,n;this.mirrorOperationTail=new Promise(i=>{n=i}),await t;try{return this.assertActive(),await e()}finally{n()}}async runAdoption(e,t){let n=this.requireAdoptionMarker(e.adoptionId),i=null;if(n.phase==="adopted"){let s=await this.adoptionClient.exchange(e,t);if(s.status!=="completed")throw new w("authority_adoption_state_conflict","The local checkpoint says adoption completed, but Connect does not.");i=s}else if(n.phase==="activating"){t.onProgress?.({stage:"activating"});let s=await this.readAdoptionSnapshot(n),o=await this.adoptionClient.exchange(e,t);i=o.status==="completed"?o:await this.adoptionClient.complete(e,s,t)}else if(n.phase==="fenced"){let s=await this.readAdoptionSnapshot(n),o=await this.adoptionClient.exchange(e,t);o.status==="completed"?i=o:(o.status==="ready"&&(t.onProgress?.({stage:"uploading",records:s.records.length}),await this.adoptionClient.uploadSnapshot(e,o,s,this.adoptionUploadOptions(e,t))),await this.updateAdoptionPhase("activating",s),t.onProgress?.({stage:"activating"}),i=await this.adoptionClient.complete(e,s,t))}else{let s=n.phase==="waiting_for_approval"?await this.adoptionClient.waitForApproval(e,t):await this.requirePreparedAdoption(e,t);await this.updateAdoptionPhase("uploading",void 0,s.adoption.expires_at),t.onProgress?.({stage:"checking"});let o=await this.captureAuthoritySnapshot(e.requested.collectionId,t.signal);t.onProgress?.({stage:"uploading",records:o.records.length}),await this.adoptionClient.uploadSnapshot(e,s,o,this.adoptionUploadOptions(e,t)),t.onProgress?.({stage:"checking"});let a=await this.captureAuthoritySnapshot(e.requested.collectionId,t.signal);await this.writeAdoptionSnapshot(a),await this.updateAdoptionPhase("fenced",a);let c=await this.requirePreparedAdoption(e,t);t.onProgress?.({stage:"uploading",records:a.records.length}),await this.adoptionClient.uploadSnapshot(e,c,a,this.adoptionUploadOptions(e,t)),await this.updateAdoptionPhase("activating",a),t.onProgress?.({stage:"activating"}),i=await this.adoptionClient.complete(e,a,t)}return await this.updateAdoptionPhase("adopted"),t.onProgress?.({stage:"connecting"}),this.finishRetainedMirror(e,i,t)}async runAdoptionWithRecovery(e,t){try{return await this.runAdoption(e,t)}catch(n){throw t.signal?.aborted?new DOMException("Adoption paused.","AbortError"):yF(n)?(await this.adoptionClient.cancel(e,{signal:t.signal}).catch(()=>{}),await this.clearAdoptionCheckpoint(e.adoptionId),new w(n.code,"This adoption ended before hosted activation. The vault remains the writable local authority; start a new adoption to try again.")):n}}async requirePreparedAdoption(e,t){let n=await this.adoptionClient.exchange(e,t);if(n.status==="ready")return n;throw n.status==="activating"?new Yr("Hosted authority activation has already started. Resume using the saved fenced snapshot."):new w("authority_adoption_already_completed","Hosted authority has already adopted this collection.")}async finishRetainedMirror(e,t,n){let i,s=this.adoptionClient.mirrorEnrollmentSession(e,t);if(!s)throw new w("authority_adoption_mirror_missing","Hosted authority activated without retaining this vault as a mirror.");try{i=await this.enrollmentClient.waitForApproval(s,{signal:n.signal,onStatus:o=>n.onStatus?.({...o,state:o.state})})}catch(o){if(n.signal?.aborted)throw o;i=await this.enrollmentClient.enroll({controlUrl:e.controlUrl,collectionId:e.requested.collectionId,mirrorName:e.requested.mirrorName??e.requested.sourceName,mode:"read_write"},{signal:n.signal,onVerification:a=>n.onVerification(a)})}return this.persistAdoptedMirror(e,i)}async persistAdoptedMirror(e,t){let n=await this.markMirror(t.collectionId);try{await this.persistEnrollment(t,this.adoptionMarker?.selective_sync)}catch(i){throw n&&await this.app.vault.adapter.remove(On),i}return await this.clearAdoptionCheckpoint(e.adoptionId),this.requireProfile()}async adoptionSources(e,t){fe(t);let n=await ai(this.app.vault);if(fe(t),!n)throw new w("invalid_collection_configuration","A valid mdbase.yaml is required.");let i=await this.app.vault.adapter.read("mdbase.yaml");fe(t);let s=(0,z.parseYaml)(i),o=`${(0,z.normalizePath)(n.settings.types_folder)}/`,a=this.app.vault.getMarkdownFiles().filter(m=>(0,z.normalizePath)(m.path).startsWith(o)).sort((m,h)=>m.path.localeCompare(h.path)),c=gF(s).map(m=>(0,ix.default)(m,{dot:!0})),l=pd(this.app.vault).filter(m=>m.extension==="base"&&c.some(h=>h((0,z.normalizePath)(m.path)))).sort((m,h)=>m.path.localeCompare(h.path)),u=this.app.vault.getMarkdownFiles().filter(m=>!yt((0,z.normalizePath)(m.path),n)).sort((m,h)=>m.path.localeCompare(h.path)),d=["mdbase.yaml",...a.map(m=>m.path),...l.map(m=>m.path)],f=e.file_classes.length?(await this.fileSystem.listBinary?.(new Set(d))??[]).filter(m=>aF(e,m)&&!yt(m,n)):[];fe(t);let p={records:u.length,resources:d.length,files:f.length,conflicts:Rm([...d,...u.map(m=>m.path),...f])};return{config:n,configuration:i,typeFiles:a,baseFiles:l,recordFiles:u,binaryPaths:f,resourcePaths:d,preview:p}}renameNamespace(){return this.app.vault.getAllLoadedFiles?.()??pd(this.app.vault)}async planAdoptionRenames(e=this.getSelectiveSync()){this.assertActive();let{preview:t,resourcePaths:n}=await this.adoptionSources(fr(e)),i=this.renameNamespace().map(c=>c.path).sort(),s=Q$(t.conflicts,i,new Set(n)),o=s.renames.map(({from:c})=>{let l=this.app.vault.getAbstractFileByPath(c);return[c,l instanceof z.TFile?l.stat:null]}),a=(await dd(new TextEncoder().encode(JSON.stringify({paths:i,sources:o,proposed:s,policy:e})).buffer)).content_digest;return{...s,revision:a}}async applyAdoptionRenames(e,t=this.getSelectiveSync(),n){return this.withAdoptionOperation(void 0,async i=>{if(this.assertLocalAuthorityWritable(),this.settingsHost.getMirrorProfile()||await this.app.vault.adapter.exists(On))throw new w("adoption_rename_unsafe","Automatic rename review is only available before this vault becomes a mirror.");let s=await this.planAdoptionRenames(t);if(JSON.stringify(s)!==JSON.stringify(e))throw new w("adoption_rename_stale","Files changed since the rename review. Review the new suggestions before renaming.");let o=e.renames.map(c=>this.app.vault.getAbstractFileByPath(c.from)),a=0;n?.(0,e.renames.length);for(let[c,l]of e.renames.entries()){let u=o[c];try{if(fe(i),this.assertLocalAuthorityWritable(),!(u instanceof z.TFile)||u.path!==l.from||this.app.vault.getAbstractFileByPath(l.from)!==u)throw new Error("The source file changed. Review again.");if(this.renameNamespace().some(d=>$i(d.path)===$i(l.to))||await this.app.vault.adapter.exists(l.to))throw new Error("The destination is now occupied. Review again.");fe(i),await this.app.fileManager.renameFile(u,l.to),a++}catch(d){throw u?.path===l.to&&a++,new w("adoption_rename_failed",`Rename stopped after ${a} of ${e.renames.length} files. Check filenames and links before retrying. ${d instanceof Error?d.message:String(d)}`)}n?.(a,e.renames.length)}return a})}async previewAdoption(e=this.getSelectiveSync(),t){return this.assertActive(),(await this.adoptionSources(fr(e),t)).preview}async captureAuthoritySnapshot(e,t){let{config:n,configuration:i,typeFiles:s,baseFiles:o,recordFiles:a,binaryPaths:c,preview:l}=await this.adoptionSources(this.getSelectiveSync(),t);ex(l);let u=[{path:"mdbase.yaml",kind:"configuration",document:i}];for(let[p,m]of[["type",s],["view",o]])for(let h of m)fe(t),u.push({path:(0,z.normalizePath)(h.path),kind:p,document:await this.app.vault.cachedRead(h)});let d=[];for(let p of a){fe(t);let m=(0,z.normalizePath)(p.path),h=await this.app.vault.cachedRead(p);fe(t),d.push({path:m,document:h})}let f=[];if(c.length){let p=this.adoptionBlobStore(e);for(let m of c){fe(t);let h=await this.fileSystem.readBinary?.(m);if(fe(t),!h)continue;let y=await Dm(h);fe(t);let g=await dd(y);fe(t),await p.write(g.content_digest,(async function*(){yield new Uint8Array(y)})()),fe(t);let b=this.app.vault.getAbstractFileByPath(m);f.push({file_id:Hl(e,`file:${m}`),path:m,revision:g.content_digest,...g,...tx(m)?{media_type:tx(m)}:{},media_class:sx(m),modified_at:new Date(b instanceof z.TFile&&b.stat?.mtime?b.stat.mtime:Date.now()).toISOString()})}}return fe(t),rm({collectionId:e,sourceHead:0,specVersion:n.spec_version,resources:u,records:d,files:f})}adoptionBlobStore(e){return this.options.adoptionBlobStoreFactory?.(e)??this.cachedBlobStore(`adoption:${e}`)}adoptionUploadOptions(e,t){let n=this.adoptionBlobStore(e.requested.collectionId);return{signal:t.signal,fileSource:async i=>Dm(n.read(i.content_digest)),onFileProgress:({file:i,transferredBytes:s,totalBytes:o})=>t.onFileProgress?.(i.path,s,o)}}async ensurePortableCollectionIdentity(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))throw new w("collection_not_initialized","Initialize an mdbase collection before hosting it.");let e=await this.app.vault.adapter.read("mdbase.yaml"),t;try{t=(0,z.parseYaml)(e)}catch{throw new w("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!at(t))throw new w("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let n=at(t["x-mdbase-connect"])?t["x-mdbase-connect"].collection_id:void 0,i;if(n===void 0){i=crypto.randomUUID();let o=at(t["x-mdbase-connect"])?t["x-mdbase-connect"]:{};t["x-mdbase-connect"]={...o,collection_id:i},this.assertActive(),await this.app.vault.adapter.write("mdbase.yaml",(0,z.stringifyYaml)(t))}else if(typeof n=="string"&&ua.test(n))i=n;else throw new w("invalid_collection_configuration","x-mdbase-connect.collection_id must be a UUID string.");let s=typeof t.name=="string"&&t.name.trim()?t.name.trim():this.app.vault.getName();return{collectionId:i,displayName:s}}stateStoreFor(e){if(this.assertActive(),this.options.stateStoreFactory)return this.options.stateStoreFactory(e);let t=`${e.collectionId}:${e.replicaId}`,n=this.stateStores.get(t);return n||(n=new qm(t),this.stateStores.set(t,n)),n}cachedBlobStore(e){this.assertActive();let t=this.blobStores.get(e);return t||(t=new jm(e),this.blobStores.set(e,t)),t}blobStoreFor(e){return this.options.blobStoreFactory?.(e)??this.cachedBlobStore(`${e.collectionId}:${e.replicaId}`)}async transportFor(e,t,n){this.assertActive(),this.assertThisDevice(e),await this.claimLegacyProfile(e);let i=await this.freshAccessToken(e);this.assertActive();let s=this.options.transportFactory?.(e,i)??new Nm(e.syncUrl,this.transportCredentials(e),hd,n,t);return mF(s,t)}async createMirror(e,t,n,i){let s=this.requireProfile();await this.assertMirror(s.collectionId);let o=await this.transportFor(s,t,n),a=this.stateStoreFor(s),c={stateStore:i?new od(a,i):a,fileSystem:this.fileSystem,blobStore:this.blobStoreFor(s),selectiveSync:fr(s.selectiveSync),lease:this.options.leaseFactory?.(s)??new Bm(`${s.collectionId}:${s.replicaId}`),onProgress:e};return s.mode==="read_write"?new ia(s.replicaId,o,c):new Si(s.replicaId,o,c)}requireProfile(){this.assertActive();let e=this.settingsHost.getMirrorProfile();if(!e)throw new w("mirror_not_configured","This vault is not connected to a collection authority.");return e}secretIds(e,t){let n=e==="access"?tF:rF;return{current:`${n}${t.replicaId.toLowerCase()}`,legacy:`${n}${t.collectionId.toLowerCase()}`}}readSecret(e,t){let n=this.secretIds(e,t),i=this.app.secretStorage.getSecret(n.current);if(i)return i;let s=this.app.secretStorage.getSecret(n.legacy);if(!s)return null;try{this.app.secretStorage.setSecret(n.current,s)}catch{}return s}clearCredentials(e){for(let t of["access","refresh"]){let n=this.secretIds(t,e),i=this.app.secretStorage.getSecret(n.current);i&&this.app.secretStorage.getSecret(n.legacy)===i&&this.app.secretStorage.setSecret(n.legacy,""),this.app.secretStorage.setSecret(n.current,"")}}currentDeviceId(){return this.settingsHost.deviceId?.()}isOtherDevice(e=this.settingsHost.getMirrorProfile()){let t=this.currentDeviceId();return!!(e?.deviceId&&t&&e.deviceId!==t)}async claimLegacyProfile(e){let t=this.currentDeviceId();e.deviceId||!t||await this.settingsHost.saveMirrorProfile({...e,deviceId:t})}assertThisDevice(e){if(this.isOtherDevice(e))throw new w("mirror_other_device","This vault's sync settings were copied from another device or vault. Set up sync here to give this copy its own connection.")}adoptionSecretId(e){return`${nF}${e.toLowerCase()}`}async storeAdoptionSecret(e){try{let t=this.adoptionSecretId(e.adoptionId);if(this.app.secretStorage.setSecret(t,e.credential),this.app.secretStorage.getSecret(t)!==e.credential)throw new Error("Secret was not retained")}catch{throw new w("authority_adoption_credentials_unavailable","Obsidian could not save this device's authorization. Unlock or repair Obsidian's secret storage before starting the move. Nothing was uploaded.")}}async persistEnrollment(e,t){this.assertActive();try{let n=this.secretIds("access",e).current,i=this.secretIds("refresh",e).current;if(this.app.secretStorage.setSecret(n,e.accessToken),this.app.secretStorage.setSecret(i,e.refreshCredential),this.app.secretStorage.getSecret(n)!==e.accessToken||this.app.secretStorage.getSecret(i)!==e.refreshCredential)throw new Error("Secret was not retained")}catch{throw new w("mirror_credentials_unavailable","Obsidian could not save this device's authorization. Unlock or repair Obsidian's secret storage, then reconnect. Your files were not changed.")}await this.settingsHost.saveMirrorProfile(nx(e,t??this.settingsHost.getMirrorProfile()?.selectiveSync,this.currentDeviceId()))}async removeExactMirrorFiles(e,t){let n=new Map;for(let[i,s]of Object.entries(e.records)){let o=e.local_bindings?.[i]?.path??s.path;n.set(o,{entity:"document",document:s.record?.document,revision:s.revision})}for(let[i,s]of Object.entries(e.resources??{})){let o=e.local_bindings?.[i]?.path??s.path;n.set(o,{entity:"document",document:s.record?.document,revision:s.revision})}for(let[i,s]of Object.entries(e.files??{})){let o=e.local_bindings?.[i]?.path??s.file.path;n.set(o,{entity:"file",digest:s.file.content_digest,size:s.file.size})}for(let[i,s]of[...n.entries()].sort(([o],[a])=>a.localeCompare(o))){let o=!1;if(s.entity==="document"){let a=await this.fileSystem.read(i);o=a!==null&&(s.document!==void 0?a===s.document:await wF(a,s.revision))}else if(s.entity==="file"){let a=await this.fileSystem.inspectBinary(i);o=a!==null&&a.content_digest===s.digest&&a.size===s.size}if(!o){await this.fileSystem.exists(i)&&t.preserved.push(i);continue}try{await this.fileSystem.remove(i),t.removed.push(i)}catch{t.preserved.push(i)}}}async freshAccessToken(e){if(this.renewal)return this.renewal;let t=this.readSecret("access",e),n=Date.parse(e.accessTokenExpiresAt);return t&&Number.isFinite(n)&&n-Date.now()>iF?t:this.renewAccessToken(e)}renewAccessToken(e){return this.renewal??=this.renewAccessTokenOnce(e).finally(()=>{this.renewal=null}),this.renewal}async renewAccessTokenOnce(e){let t=this.readSecret("refresh",e);if(!t)throw new w("mirror_credentials_missing","The mirror refresh credential is missing. Approve this vault again.");let n=await this.enrollmentClient.renew({controlUrl:e.controlUrl,syncUrl:e.syncUrl,collectionId:e.collectionId,replicaId:e.replicaId,mode:e.mode,name:e.name,enrollmentId:e.enrollmentId,accessToken:this.readSecret("access",e)??"",refreshCredential:t,accessTokenExpiresAt:e.accessTokenExpiresAt},{signal:this.lifetime.signal}),i=this.requireProfile();if(i.collectionId!==e.collectionId||i.replicaId!==e.replicaId||i.enrollmentId!==e.enrollmentId)throw new w("mirror_identity_conflict","The connection changed while credentials were renewing. Retry with the current connection.");return await this.persistEnrollment(n,i.selectiveSync),n.accessToken}transportCredentials(e){return{token:()=>this.freshAccessToken(this.requireProfile()),renew:async t=>{let n=this.readSecret("access",e);return n&&n!==t?n:this.renewAccessToken(this.requireProfile())}}}async assertCanBecomeMirror(e){let t=await this.readMarker(),n=await this.readPortableCollectionId();if(n&&!t)throw new w("local_authority_requires_transfer","This vault has a local Connect identity. Transfer authority explicitly before using it as a mirror.");if(n&&t?.collection_id!==n)throw new w("mirror_identity_conflict","The vault identity and mirror role marker identify different collections.");let i=this.settingsHost.getMirrorProfile(),s=i?.collectionId??e;if(t&&s&&t.collection_id!==s)throw new w("mirror_identity_conflict","This vault is already marked as a different mirror.");if(!t&&!i&&await this.app.vault.adapter.exists("mdbase.yaml"))throw new w("existing_collection_requires_transfer","This vault already contains an mdbase collection. Connect an empty vault, or transfer collection authority explicitly.");return s??t?.collection_id}async readPortableCollectionId(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))return null;let e;try{e=(0,z.parseYaml)(await this.app.vault.adapter.read("mdbase.yaml"))}catch{throw new w("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!at(e))throw new w("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let t=e["x-mdbase-connect"];if(t===void 0)return null;if(!at(t))throw new w("invalid_collection_configuration","x-mdbase-connect must be a YAML mapping.");let n=t.collection_id;if(n===void 0)return null;if(typeof n!="string"||!ua.test(n))throw new w("invalid_collection_configuration","x-mdbase-connect.collection_id must be a UUID string.");return n}async markMirror(e){this.assertActive();let t=await this.readMarker();if(t){if(t.collection_id!==e)throw new w("mirror_identity_conflict","This vault already mirrors a different collection authority.");return!1}return await Ps(this.app.vault,".mdbase"),this.assertActive(),await this.app.vault.adapter.write(On,`${JSON.stringify({version:1,role:"mirror",collection_id:e},null,2)} -`),!0}async assertMirror(e){let t=await this.readMarker();if(!t||t.collection_id!==e)throw new w("mirror_marker_missing","The vault's mirror role marker is missing or does not match this connection.")}async readMarker(){if(!await this.app.vault.adapter.exists(On))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(On))}catch{throw new w("invalid_mirror_marker","The mirror role marker is corrupt.")}if(!at(e)||e.version!==1||e.role!=="mirror"||typeof e.collection_id!="string"||!ua.test(e.collection_id))throw new w("invalid_mirror_marker","The mirror role marker is invalid.");return e}requireAdoptionMarker(e){if(!this.adoptionMarker||this.adoptionMarker.session.adoptionId!==e)throw new w("authority_adoption_state_conflict","The collection-adoption checkpoint does not match this approval.");return this.adoptionMarker}async updateAdoptionPhase(e,t,n){if(!this.adoptionMarker)throw new w("authority_adoption_not_found","Collection-adoption checkpoint is missing.");await this.writeAdoptionMarker({...this.adoptionMarker,phase:e,...n?{session:{...this.adoptionMarker.session,expiresAt:n}}:{},...t?{manifest_digest:t.manifest_digest,source_revision:t.source_revision,source_head:t.source_head}:{}})}async writeAdoptionMarker(e){await Ps(this.app.vault,".mdbase"),this.assertActive(),await this.app.vault.adapter.write(ca,`${JSON.stringify(e,null,2)} -`),this.adoptionMarker=e}async readAdoptionMarker(){if(!await this.app.vault.adapter.exists(ca))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(ca))}catch{throw new w("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is corrupt.")}if(!bF(e))throw new w("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is invalid.");return e}async writeAdoptionSnapshot(e){this.assertActive(),await Ps(this.app.vault,".mdbase"),this.assertActive(),await this.app.vault.adapter.write(la,JSON.stringify(e))}async readAdoptionSnapshot(e){if(!await this.app.vault.adapter.exists(la))throw new w("authority_adoption_snapshot_missing","The fenced authority snapshot is missing; hosted activation cannot be resumed safely.");let t;try{t=JSON.parse(await this.app.vault.adapter.read(la))}catch{throw new w("invalid_authority_adoption_snapshot","The fenced authority snapshot is corrupt.")}if(t.collection_id!==e.session.requested.collectionId||t.manifest_digest!==e.manifest_digest||t.source_revision!==e.source_revision||t.source_head!==e.source_head)throw new w("authority_adoption_snapshot_mismatch","The fenced authority snapshot does not match its durable checkpoint.");return t}async clearAdoptionCheckpoint(e){let t=this.adoptionMarker?.session.requested.collectionId;await this.app.vault.adapter.exists(la)&&await this.app.vault.adapter.remove(la),await this.app.vault.adapter.exists(ca)&&await this.app.vault.adapter.remove(ca),this.adoptionMarker=null;try{this.app.secretStorage.setSecret(this.adoptionSecretId(e),"")}catch{}t&&await this.adoptionBlobStore(t).prune(new Set).catch(()=>{})}};function Om(r){let{credential:e,...t}=r;return t}function yF(r){return r instanceof J&&["authority_adoption_expired","authority_adoption_cancelled"].includes(r.code)}function gF(r){if(!at(r))return[];let e=r["x-obsidian"];return!at(e)||!at(e.bases)||!Array.isArray(e.bases.include)?[]:e.bases.include.filter(t=>typeof t=="string")}function pd(r){let e=r.getFiles?.();if(e)return e;let t=[],n=i=>{for(let s of i.children)s instanceof z.TFile?t.push(s):s instanceof z.TFolder&&n(s)};return n(r.getRoot()),t}function bF(r){if(!at(r)||r.version!==1||!["waiting_for_approval","uploading","fenced","activating","adopted"].includes(String(r.phase))||!at(r.session))return!1;let e=r.session;return typeof e.controlUrl=="string"&&typeof e.adoptionId=="string"&&ua.test(e.adoptionId)&&typeof e.verificationUri=="string"&&typeof e.expiresAt=="string"&&at(e.requested)&&typeof e.requested.collectionId=="string"&&ua.test(e.requested.collectionId)&&typeof e.requested.displayName=="string"&&typeof e.requested.sourceName=="string"&&e.requested.retainMirror===!0&&(r.selective_sync===void 0||vF(r.selective_sync))&&(r.manifest_digest===null||typeof r.manifest_digest=="string")&&(r.source_revision===null||typeof r.source_revision=="string")&&(r.source_head===null||Number.isSafeInteger(r.source_head))}function vF(r){if(!at(r)||!Array.isArray(r.file_classes)||!Array.isArray(r.excluded_folders))return!1;try{let e=fr(r);return e.file_classes.length===r.file_classes.length&&e.excluded_folders.length===r.excluded_folders.length}catch{return!1}}function nx(r,e,t){return{version:1,syncUrl:r.syncUrl,controlUrl:r.controlUrl,collectionId:r.collectionId,replicaId:r.replicaId,mode:r.mode,name:r.name,enrollmentId:r.enrollmentId,accessTokenExpiresAt:r.accessTokenExpiresAt,selectiveSync:fr(e),...t?{deviceId:t}:{}}}async function wF(r,e){if(!e?.startsWith("sha256:"))return!1;let t=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r)));return`sha256:${Array.from(t,i=>i.toString(16).padStart(2,"0")).join("")}`===e}var Xe=require("obsidian");qt();var ma="0.3.0",_F=new Set(["name","description","display_name_key","strict","path_pattern","filename_pattern","match","fields","extends"]),SF=new Set(["type","required","default","description","values","items","fields","min","max","min_length","max_length","pattern","unique","deprecated","generated","computed","target","validate_exists","tn_role","tn_completed_values"]);function pe(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Ae(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}function rn(r){return Zo.digest(r)}function Ei(r){return Array.isArray(r)?`[${r.map(Ei).join(",")}]`:pe(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${Ei(r[e])}`).join(",")}}`:JSON.stringify(r)}function Um(r){if(Array.isArray(r))return r.map(Um);if(!pe(r))return r;let e={};for(let[t,n]of Object.entries(r)){let i=Um(n);i!=null&&(Array.isArray(i)&&i.length===0||pe(i)&&Object.keys(i).length===0||(e[t]=i))}return e}function Cs(r){return[...new Set(r)]}function $F(r){return pe(r.fields)?Object.values(r.fields).some(e=>pe(e)&&(typeof e.tn_role=="string"||Array.isArray(e.tn_completed_values))):!1}function Vm(r,e,t){let n=pe(e)?e:{},i={},s={},o=[],a;switch(n.type){case"any":a={};break;case"string":case"integer":case"number":case"boolean":a={type:n.type};break;case"date":case"datetime":case"time":a={type:"string",format:n.type==="datetime"?"date-time":n.type};break;case"enum":a={enum:Array.isArray(n.values)?Ae(n.values):[]};break;case"link":a={type:"string"},i[r]={target_type:typeof n.target=="string"?n.target:r.endsWith("Parent")||r.endsWith("uid")?"task":"any",validate_exists:n.validate_exists===!0};break;case"list":{let c=Vm(`${r}[]`,n.items,t);a={type:"array",items:c.schema},Object.assign(i,c.links),Object.assign(s,c.legacy),o.push(...c.unsupported);break}case"object":{let c={},l=[];for(let[u,d]of Object.entries(pe(n.fields)?n.fields:{})){let f=Vm(`${r}.${u}`,d,t);c[u]=f.schema,Object.assign(i,f.links),Object.assign(s,f.legacy),o.push(...f.unsupported),pe(d)&&d.required===!0&&l.push(u)}t&&r==="blockedBy[]"&&l.push("uid"),a={type:"object",additionalProperties:Object.keys(c).length===0,properties:c,...l.length?{required:Cs(l)}:{}};break}default:a={},o.push(`${r}.type`);break}t&&r==="title"&&(a.minLength=1,a.description="Short summary of the task."),typeof n.description=="string"&&(a.description=n.description),typeof n.min=="number"&&(n.type==="string"?a.minLength=n.min:n.type==="list"?a.minItems=n.min:a.minimum=n.min),typeof n.max=="number"&&(n.type==="string"?a.maxLength=n.max:n.type==="list"?a.maxItems=n.max:a.maximum=n.max),typeof n.min_length=="number"&&(n.type==="list"?a.minItems=n.min_length:a.minLength=n.min_length),typeof n.max_length=="number"&&(n.type==="list"?a.maxItems=n.max_length:a.maxLength=n.max_length),typeof n.pattern=="string"&&(a.pattern=n.pattern),n.deprecated===!0&&(a.deprecated=!0),n.default!==void 0&&(a.default=Ae(n.default)),n.computed!==void 0&&o.push(`${r}.computed`);for(let[c,l]of Object.entries(n)){let u=t&&(c==="tn_role"||c==="tn_completed_values");(!SF.has(c)||(c==="tn_role"||c==="tn_completed_values")&&!u)&&(s[`${r}.${c}`]=Ae(l))}return{schema:a,links:i,legacy:s,unsupported:o}}function fa(r,e,t,n){let i=pe(r[e])?r[e]:{},s=pe(i.set)?i.set:{};s[t]=n,i.set=s,r[e]=i}function xF(r,e,t){if(t==="now")fa(r,"on_create",e,{now:!0});else if(t==="now_on_write")fa(r,"on_update",e,{now:!0});else if(t==="uuid")fa(r,"on_create",e,{uuid:!0});else if(t==="ulid")fa(r,"on_create",e,{ulid:!0});else if(pe(t)&&t.transform==="slugify"&&typeof t.from=="string")fa(r,"on_create",e,{slugify:t.from});else return!1;return!0}function EF(r){let e=r.match(/^(.*\/)?\{title\}\.md$/);return e?{runtime:"tasknotes",template:"{{title}}",folder:(e[1]??"").replace(/\/$/,""),generated_by:"tasknotes.filename.create"}:{runtime:"tasknotes",template:r,generated_by:"tasknotes.filename.create"}}function AF(r,e,t){if(t.kind==="mdbase.type"||t.schema!==void 0)throw new Error(`${r} already looks like a v0.3 type.`);if(typeof t.name!="string"||!pe(t.fields))throw new Error(`${r} is not a v0.2 type with a name and fields.`);let n=$F(t),i=t.name.trim().toLowerCase(),s={type:{const:i}},o=[],a={},c={},l=[],u={},d={},f=[],p=[],m={},h={},y={};for(let[E,k]of Object.entries(t.fields)){let $=pe(k)?k:{},M=Vm(E,$,n);s[E]=M.schema,Object.assign(c,M.links),Object.assign(d,M.legacy),f.push(...M.unsupported),$.required===!0&&o.push(E),$.default!==void 0&&(a[E]=Ae($.default)),$.unique===!0&&l.push({field:E,scope:"collection"}),$.generated!==void 0&&(xF(u,E,$.generated)?p.push(E):(d[`${E}.generated`]=Ae($.generated),f.push(`${E}.generated`))),typeof $.tn_role=="string"&&(m[$.tn_role]=E),Array.isArray($.tn_completed_values)&&(h.completed_values=Ae($.tn_completed_values))}a.status!==void 0&&(h.default=Ae(a.status)),a.priority!==void 0&&(y.default=Ae(a.priority));let g=typeof t.display_name_key=="string"&&Object.prototype.hasOwnProperty.call(t.fields,t.display_name_key)?t.display_name_key:void 0,b={...g?{display:{name_field:g}}:{},read_defaults:a,links:c,unique:l};typeof t.path_pattern=="string"&&(b.path=n?EF(t.path_pattern):{pattern:t.path_pattern});let v={};for(let[E,k]of Object.entries(t))_F.has(E)||(v[E]=Ae(k));Object.keys(d).length&&(v.fields=d);let S=Um({kind:"mdbase.type",name:i,version:1,description:typeof t.description=="string"?t.description:void 0,match:pe(t.match)?Ae(t.match):void 0,schema:{dialect:"json-schema-2020-12",value:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",additionalProperties:t.strict!==!0,properties:s,...o.length?{required:Cs(o)}:{}}},collection:b,lifecycle:u,...n?{"x-tasknotes":{contract:"tasknotes.task",version:1,field_roles:m,status:h,priority:y,archive:{tags_field:m.tags??"tags",archived_tag:"archived"}}}:{},...Object.keys(v).length?{"x-legacy-v0.2":v}:{}}),_=[];t.extends!==void 0&&f.push("extends");for(let E of Cs(f).sort())_.push({path:r,code:"migration_lossy",message:`${E} cannot be expressed as canonical v0.3 write behavior and was retained as legacy metadata where possible.`,severity:"lossy"});return n&&_.push({path:r,code:"path_policy_runtime_owned",message:"TaskNotes filename behavior is recorded as TaskNotes runtime metadata.",severity:"warning"}),t.strict!==!0&&_.push({path:r,code:"additional_properties_true",message:"The migrated schema allows additional properties because the source type was not strict.",severity:"warning"}),typeof t.display_name_key=="string"&&!g&&_.push({path:r,code:"display_field_missing",message:`The display field '${t.display_name_key}' is not declared, so collection.display was omitted.`,severity:"warning"}),{target:S,summary:{path:r,name:i,fieldsConverted:Object.keys(t.fields).length,requiredFields:Cs(o),defaultsMoved:Object.keys(a),generatedFieldsMoved:Cs(p),linksMoved:Object.keys(c),taskNotes:n},diagnostics:_}}var kF=["default_strict","write_nulls","write_empty_lists","write_defaults","rename_update_refs","cache_folder","migrations_folder","extensions"];function PF(r,e){let t=Ae(r);t.spec_version=ma;let n=pe(t.settings)?t.settings:{};if(t.settings=n,!Array.isArray(n.record_extensions)){let a=Array.isArray(n.extensions)?n.extensions.map(String).map(c=>c.replace(/^\./,"")):[];n.record_extensions=Cs(["md",...a])}Array.isArray(n.explicit_type_keys)||(n.explicit_type_keys=["type","types"]),n.validation===void 0&&typeof n.default_validation=="string"&&(n.validation=n.default_validation),n.validation===void 0&&typeof t.default_validation=="string"&&(n.validation=t.default_validation),n.validation??="warn",n.id_field===void 0&&(n.id_field=typeof t.id_field=="string"?t.id_field:"id");let i=typeof n.types_folder=="string"?(0,Xe.normalizePath)(n.types_folder):"_types",s=(Array.isArray(n.exclude)?n.exclude:[]).map(String).flatMap(a=>CF(a,i)??[]);for(let a of s)MF(a)||e.push({path:"mdbase.yaml",code:"non_portable_exclude",message:`Exclude pattern "${a}" is not a portable v0.3 glob; review it.`,severity:"warning"});n.include_subfolders===!1&&s.push("*/**"),s.length>0?n.exclude=s:delete n.exclude;let o={};for(let a of kF)n[a]!==void 0&&(o[a]=n[a]),delete n[a];if(Object.keys(o).length>0){let a=pe(t["x-legacy-v0.2"])?t["x-legacy-v0.2"]:{};t["x-legacy-v0.2"]={...a,settings:o}}return delete n.include_subfolders,delete n.default_validation,delete t.default_validation,delete t.id_field,t}function CF(r,e){return/[/*?[]/.test(r)?r.includes("/")?r:`**/${r}`:r.startsWith(".")||r==="node_modules"||r===e?null:`${r}/**`}function MF(r){return r!==""&&!r.startsWith("/")&&!/[{}\\]/.test(r)&&r.split("/").every(e=>e==="**"||!e.includes("**"))}function cx(r,e){let t=pe(r.settings)?r.settings:{};return{spec_version:e,name:typeof r.name=="string"?r.name:void 0,description:typeof r.description=="string"?r.description:void 0,settings:{types_folder:typeof t.types_folder=="string"?t.types_folder:"_types",explicit_type_keys:Array.isArray(t.explicit_type_keys)?t.explicit_type_keys.filter(n=>typeof n=="string"):["type","types"],default_strict:t.default_strict===!0,include_subfolders:t.include_subfolders!==!1,exclude:Array.isArray(t.exclude)?t.exclude.filter(n=>typeof n=="string"):["_types",".obsidian",".git",".mdbase"]}}}function TF(r,e){let t={};for(let[n,i]of Object.entries(pe(e.fields)?e.fields:{}))pe(i)&&(t[n]=Ae(i));return{name:typeof e.name=="string"?e.name:r.split("/").pop()?.replace(/\.md$/,"")??"type",fields:t,match:pe(e.match)?Ae(e.match):void 0,filePath:r,specProfile:"v0.2"}}function RF(r,e){let t=pe(e.schema)?e.schema:{},n=pe(t.value)?t.value:{};return{name:typeof e.name=="string"?e.name:r.split("/").pop()?.replace(/\.md$/,"")??"type",fields:gn(n),match:pe(e.match)?Ae(e.match):void 0,collection:pe(e.collection)?Ae(e.collection):void 0,schema:Ae(n),filePath:r,specProfile:"v0.3"}}function IF(r,e,t){let n=Ae(r);for(let i of e){let s=t.get(i);if(s)for(let[o,a]of Object.entries(s.fields))!(o in n)&&a.default!==void 0&&(n[o]=Ae(a.default))}return n}function OF(r,e,t){let n=Ae(r);for(let i of e){let s=t.get(i);if(s)for(let[o,a]of Object.entries(s.collection?.read_defaults??{}))o in n||(n[o]=Ae(a))}return n}async function DF(r,e){let t=(0,Xe.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let n="";for(let i of t.split("/")){n=n?`${n}/${i}`:i;let s=r.getAbstractFileByPath(n);if(!(s instanceof Xe.TFolder)){if(s)throw new Error(`A file blocks folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}async function md(r,e,t){let n=(0,Xe.normalizePath)(e),i=n.lastIndexOf("/");if(i>=0&&await DF(r,n.slice(0,i)),n.startsWith(".mdbase/")){await r.adapter.write(n,t);return}let s=r.getAbstractFileByPath(n);if(s instanceof Xe.TFolder)throw new Error(`A folder blocks file ${n}.`);s instanceof Xe.TFile?await r.modify(s,t):await r.create(n,t)}async function ha(r,e){let t=(0,Xe.normalizePath)(e),n=r.getAbstractFileByPath(t);if(n instanceof Xe.TFile)return r.cachedRead(n);if(await r.adapter.exists(t))return r.adapter.read(t);throw new Error(`File not found: ${e}`)}async function lx(r){let e=await ha(r,"mdbase.yaml"),t=(0,Xe.parseYaml)(e);if(!pe(t))throw new Error("mdbase.yaml must contain a YAML mapping.");let n=typeof t.spec_version=="string"?t.spec_version:"";if(!/^0\.2(?:\.\d+)?$/.test(n))throw new Error(n===ma?"This collection is already mdbase v0.3.":`Expected an mdbase v0.2.x collection, found ${JSON.stringify(n)}.`);let i=pe(t.settings)?t.settings:{},s=typeof i.types_folder=="string"?(0,Xe.normalizePath)(i.types_folder):"_types",o=`${s}/`,a=[],c=[],l=[],u=PF(t,l),d=`${(0,Xe.stringifyYaml)(u).trimEnd()} -`;a.push({path:"mdbase.yaml",sourceDigest:rn(e),targetDigest:rn(d),source:e,target:d});let f=new Map,p=new Map;for(let S of r.getMarkdownFiles().filter(_=>_.path.startsWith(o)).sort((_,E)=>_.path.localeCompare(E.path))){let _=await r.cachedRead(S),E=Me(_);if(!E.hasFrontmatter||E.error)throw new Error(`Cannot migrate ${S.path}: ${E.error??"frontmatter is missing"}.`);let k=AF(S.path,n,E.frontmatter),$=TF(S.path,E.frontmatter),M=RF(S.path,k.target);f.set($.name,$),p.set(M.name,M);let x=`${mt(k.target,E.body)} -`;a.push({path:S.path,sourceDigest:rn(_),targetDigest:rn(x),source:_,target:x}),c.push(k.summary),l.push(...k.diagnostics)}if(!c.length)throw new Error(`No v0.2 type files were found in ${s}.`);let m=0,h=0,y=cx(t,n),g=cx(u,ma),b=r.getMarkdownFiles().filter(S=>!S.path.startsWith(o)).filter(S=>!S.path.startsWith(".mdbase/")).sort((S,_)=>S.path.localeCompare(_.path));for(let[S,_]of b.entries()){let E=Me(await r.cachedRead(_));if(E.error){h+=1;continue}let k=Ke(_.path,E.frontmatter,y,f),$=Ke(_.path,E.frontmatter,g,p),M=IF(E.frontmatter,k,f),x=OF(E.frontmatter,$,p);(Ei(k.slice().sort())!==Ei($.slice().sort())||Ei(M)!==Ei(x))&&l.push({path:_.path,code:"effective_read_changed",message:"The proposed v0.3 types would change this record's resolved types or effective default values.",severity:"lossy"}),m+=1,S>0&&S%250===0&&await new Promise(q=>window.setTimeout(q,0))}let v=rn(Ei({sourceVersion:n,operations:a.map(({path:S,sourceDigest:_,targetDigest:E})=>({path:S,sourceDigest:_,targetDigest:E})),diagnostics:l}));return{planVersion:1,analysisId:v,sourceVersion:n,targetVersion:ma,createdAt:new Date().toISOString(),backupLocation:`.mdbase/migrations/v02-to-v03-${v.slice(0,12)}`,operations:a,typeSummaries:c,diagnostics:l,applicable:!l.some(S=>S.severity==="lossy"),recordFilesRewritten:0,recordsVerified:m,recordsSkipped:h}}async function pa(r,e,t){await md(r,e,`${JSON.stringify(t,null,2)} -`)}async function dx(r,e,t={}){if(e.planVersion!==1||e.targetVersion!==ma)throw new Error("Unsupported migration plan.");if(!e.applicable&&!t.allowLossy)throw new Error("This migration has lossy diagnostics. Review them and explicitly allow lossy migration.");for(let s of e.operations){let o=await ha(r,s.path);if(rn(o)!==s.sourceDigest)throw new Error(`${s.path} changed after migration analysis. Run the review again.`)}let n=`${e.backupLocation}/manifest.json`,i={manifest_version:1,analysis_id:e.analysisId,source_version:e.sourceVersion,target_version:e.targetVersion,status:"prepared",created_at:new Date().toISOString(),written:[],files:e.operations.map(s=>({path:s.path,source_digest:s.sourceDigest,target_digest:s.targetDigest,backup_path:`${e.backupLocation}/files/${s.path}`}))};for(let s of e.operations)await md(r,`${e.backupLocation}/files/${s.path}`,s.source);await pa(r,n,i),i.status="applying",await pa(r,n,i);try{for(let s of e.operations){let o=await ha(r,s.path);if(rn(o)!==s.sourceDigest)throw new Error(`${s.path} changed during migration.`);i.written.push(s.path),await pa(r,n,i),await md(r,s.path,s.target);let a=await ha(r,s.path);if(rn(a)!==s.targetDigest)throw new Error(`${s.path} did not verify after write.`)}return i.status="applied",i.completed_at=new Date().toISOString(),await pa(r,n,i),{applied:!0,restored:!1,manifestPath:n,written:[...i.written]}}catch(s){let o=[];for(let a of[...i.written].reverse()){let c=e.operations.find(l=>l.path===a);if(!c){o.push(a);continue}try{await md(r,a,c.source),rn(await ha(r,a))!==c.sourceDigest&&o.push(a)}catch{o.push(a)}}i.status=o.length?"recovery_required":"rolled_back",i.error=s instanceof Error?s.message:String(s),i.manual_recovery_paths=o.length?o:void 0,i.completed_at=new Date().toISOString();try{await pa(r,n,i)}catch{}return{applied:!1,restored:o.length===0,manifestPath:n,written:[...i.written],error:i.error}}}var yd=require("obsidian");qt();function we(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Mt(r){return JSON.parse(JSON.stringify(r))}var NF=new Set(["file","formula","this"]);function LF(r){let e=r.trim();if(!e)throw new Error("Type name is required.");if(!/^[A-Za-z]/.test(e))throw new Error("Type name must start with a letter.");if(e.length>=64)throw new Error("Type name must be shorter than 64 characters.");if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(e))throw new Error("Type name may contain only letters, numbers, hyphens, and underscores.");if(NF.has(e.toLowerCase()))throw new Error(`Type name '${e}' is reserved.`);return e}function Hm(){return{specProfile:"v0.3",originalFrontmatter:{},name:"",description:"",extendsType:"",displayNameKey:"",strictMode:!1,pathPattern:"",filenamePattern:"",matchPathGlob:"",matchFieldsPresent:"",matchWhere:"",fields:[{name:"title",definition:{type:"string",required:!0}}],implementations:[],body:`# Type +`)??null;let a=new Map;for(let l of new Set([...i.order,...s.order,...n.order])){let u=e$(n.blocks.get(l),i.blocks.get(l),s.blocks.get(l));if(u===null)return null;u!==void 0&&a.set(l,u)}let c=i.order.filter(l=>a.has(l));for(let[l,u]of s.order.entries()){if(!a.has(u)||c.includes(u))continue;let d=s.order.slice(0,l).reverse().find(f=>c.includes(f));c.splice(d===void 0?0:c.indexOf(d)+1,0,u)}return c.flatMap(l=>(a.get(l)??"").split(` +`))}function e$(r,e,t){return e===t?e:e===r?t:t===r?e:null}function xi(r){return[...r.normalize("NFC")].map(e=>e.toLowerCase()).join("").normalize("NFC")}function Dm(r){let e=new Map;for(let t of r){let n=xi(t),i=e.get(n)??[];i.push(t),e.set(n,i)}return[...e.values()].filter(t=>t.length>1)}function t$(r,e,t){let n=new Set([...e].map(xi)),i=[],s=[];for(let o of[...r].sort((a,c)=>a[0]c[0]?1:0)){let a=[...o].sort();if(a.some(c=>t.has(c))||new Set(a).size!==a.length){s.push(a);continue}for(let c of a.slice(1)){let l=c.lastIndexOf("/"),u=c.lastIndexOf("."),d=u>l+1?c.slice(u):"",f=d?c.slice(0,-d.length):c,p=2,h;do h=`${f} (${p++})${d}`;while(n.has(xi(h)));n.add(xi(h)),i.push({from:c,to:h})}}return{renames:i,manual:s}}function c$(r){if(!Xe(r))return null;let e=r;if(!(e.version===1&&typeof e.syncUrl=="string"&&typeof e.controlUrl=="string"&&typeof e.collectionId=="string"&&typeof e.replicaId=="string"&&(e.mode==="read_only"||e.mode==="read_write")&&typeof e.name=="string"&&typeof e.enrollmentId=="string"&&typeof e.accessTokenExpiresAt=="string"&&(e.deviceId===void 0||typeof e.deviceId=="string")))return null;let t;try{t=Ir(e.selectiveSync)}catch{t=Ir()}return{...e,selectiveSync:t}}function Z2(r){try{let e=(0,J.parseYaml)(r);return e===null||typeof e=="object"&&!Array.isArray(e)}catch{return!1}}var On=".mdbase/connect-role.json",ca=".mdbase/authority-adoption.json",la=".mdbase/authority-adoption-snapshot.json",eF="mdbase-obsidian-connect",Dn="mirrors",tF="mdbase-obsidian-connect-blobs",Nn="manifests",Ln="chunks",dd=1024*1024,rF=32*1024*1024,r$=2e3;function $i(r){if(!Number.isSafeInteger(r)||r<0||r>rF)throw new w("file_too_large","Binary sync supports files up to 32 MiB on this device. Exclude this file's folder to continue.")}var nF="mdbase-connect-access-",iF="mdbase-connect-refresh-",sF="mdbase-connect-adoption-",oF=300*1e3,aF=[".git",".trash",".mdbase"],cF=new Set([".git",".mdbase",".trash","node_modules","_contracts","_schemas","_types","_views"]),Nm=["image","audio","video","pdf","other"],ua=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Xe(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Ir(r){let e=r?.file_classes??[];if(e.some(s=>!Nm.includes(s))||new Set(e).size!==e.length)throw new w("invalid_file_materialization","Selected file media classes must be valid and unique.");let t=[...e].sort((s,o)=>Nm.indexOf(s)-Nm.indexOf(o)),n=r?.excluded_folders??[];if(n.some(s=>typeof s!="string"||!s.trim()))throw new w("invalid_file_materialization","Excluded folders cannot be empty.");let i=n.map(s=>yn(s.trim())).sort((s,o)=>s.toLocaleLowerCase().localeCompare(o.toLocaleLowerCase()));if(i.length>100)throw new w("invalid_file_materialization","File sync supports at most 100 excluded folders.");if(new Set(i.map(s=>s.toLocaleLowerCase())).size!==i.length)throw new w("invalid_file_materialization","Excluded folders must be unique on portable filesystems.");for(let s of i)da(s,!0);return{file_classes:t,excluded_folders:i}}function l$(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 n$(r){if(r.conflicts.length)throw new w("authority_import_path_conflict",`${r.conflicts.length} filename conflicts prevent uploading. Review the paths in Sync and rename the conflicting files before retrying. Nothing was renamed or excluded.`)}function lF(r,e,t=l$(e)){if(!r.file_classes.includes(t))return!1;let n=(0,J.normalizePath)(e);return!r.excluded_folders.some(i=>n===i||n.startsWith(`${i}/`))}var dF=/\.(?:md|base)$/,d$=/\.(?:md|base)$/i;function da(r,e=!1){let t=yn(r),n=t.split("/");if(t.length>1024||!e&&d$.test(t)||n.some(i=>i.startsWith(".")||cF.has(i.toLowerCase())||/[<>"|?*]/u.test(i)||/^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/iu.test(i)))throw new w("invalid_file_path",`Collection file path ${t} is hidden, reserved, or non-portable.`);return t}async function fa(r){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",r));return{size:r.byteLength,content_digest:`sha256:${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}`}}async function Fm(r){let e=[],t=0;for await(let s of r){if(!(s instanceof Uint8Array))throw new w("file_integrity_failed","A binary stream returned an invalid chunk.");s.byteLength&&(t+=s.byteLength,$i(t),e.push(Uint8Array.from(s)))}let n=new Uint8Array(t),i=0;for(let s of e)n.set(s,i),i+=s.byteLength;return n.buffer}function i$(r){let e=r.includes(".")?r.slice(r.lastIndexOf(".")+1).toLowerCase():"";return{avif:"image/avif",gif:"image/gif",jpeg:"image/jpeg",jpg:"image/jpeg",png:"image/png",svg:"image/svg+xml",webp:"image/webp",flac:"audio/flac",m4a:"audio/mp4",mp3:"audio/mpeg",ogg:"audio/ogg",opus:"audio/opus",wav:"audio/wav",mov:"video/quicktime",mp4:"video/mp4",webm:"video/webm",pdf:"application/pdf"}[e]}async function uF(r,e){if(r!==void 0){if(!e)return JSON.stringify(r);if(r instanceof ArrayBuffer)return r;if(ArrayBuffer.isView(r))return Uint8Array.from(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)).buffer;if(r instanceof Blob)return r.arrayBuffer();throw new w("invalid_file_upload","The adoption upload body was not binary data.")}}function ud(r,e){if(e!=null)return e;if(!r.trim())return{};try{return JSON.parse(r)}catch{return{}}}var hd=jx(qx());function fF(){return async r=>{if(r.signal?.aborted)throw new DOMException("Enrollment cancelled.","AbortError");let e=await hd({url:r.url,method:r.method,headers:r.headers,body:r.body===void 0?void 0:JSON.stringify(r.body),contentType:r.body===void 0?void 0:"application/json",throw:!1,signal:r.signal});if(r.signal?.aborted)throw new DOMException("Enrollment cancelled.","AbortError");return{status:e.status,body:ud(e.text,e.json),retryAfterMs:aa(e.headers)}}}function pF(){return async r=>{if(r.signal?.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");let e=await uF(r.body,r.rawBody),t=await hd({url:r.url,method:r.method,headers:r.headers,body:e,contentType:e===void 0||r.rawBody?void 0:"application/json",throw:!1,signal:r.signal});if(r.signal?.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");return{status:t.status,body:ud(t.text,t.json),retryAfterMs:aa(t.headers),headers:t.headers}}}var jm=class{constructor(e,t,n=hd,i,s){this.send=n;this.onFileProgress=i;this.signal=s;this.credentials=typeof t=="string"?{token:()=>Promise.resolve(t)}:t;let o;try{o=new URL(e)}catch{throw new w("invalid_sync_url","Sync URL must be an absolute authority endpoint.")}if(!(o.protocol==="https:"||o.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(o.hostname))||o.username||o.password||o.search||o.hash||!/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/sync\/?$/i.test(o.pathname))throw new w("invalid_sync_url","Sync URL must identify one authority sync endpoint.");this.syncUrl=o.href.replace(/\/$/,""),this.filesUrl=this.syncUrl.replace(/\/sync$/u,"/files")}openSession(){return this.request("POST","sessions")}snapshot(e,t){let n=new URLSearchParams({snapshot_id:e});return t&&n.set("page",t),this.request("GET",`snapshot?${n.toString()}`)}fileSnapshot(e,t){let n=new URLSearchParams({snapshot_id:e});return t&&n.set("page",t),this.request("GET",`files/snapshot?${n.toString()}`)}async*downloadFile(e){$i(e.size);let t=crypto.randomUUID();try{let n=0;this.onFileProgress?.({direction:"download",path:e.path,transferredBytes:n,totalBytes:e.size});let i=await this.fileRequest("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:t,file_id:e.file_id,revision:e.revision});if(i.protocol_version!==1||i.type!=="file_transfer"||i.transfer_id!==t||i.direction!=="download"||i.protection!=="transport_tls"||i.total_size!==e.size||i.strategy.kind!=="object_ranges"||!Number.isSafeInteger(i.strategy.part_size)||i.strategy.part_size<=0)throw new w("invalid_sync_response","The authority returned an incompatible file download session.");let s=Math.ceil(e.size/i.strategy.part_size);for(let o=0;o=300)throw this.responseError(c,"file_download_failed");let l=s$(c.headers,"content-length");if(l!==void 0&&Number(l)!==a||c.arrayBuffer.byteLength!==a)throw new w("file_integrity_failed","Hosted authority returned a file part with the wrong length.");n+=a,this.onFileProgress?.({direction:"download",path:e.path,transferredBytes:n,totalBytes:e.size}),a&&(yield new Uint8Array(c.arrayBuffer))}}finally{await this.fileRequest("DELETE",`transfers/${encodeURIComponent(t)}`).catch(()=>{})}}async uploadFile(e,t){$i(e.size);let n=await this.fileRequest("POST","uploads",e);if(n.protocol_version!==1||n.type!=="file_transfer"||n.transfer_id!==e.transfer_id||n.direction!=="upload"||n.protection!=="transport_tls"||n.total_size!==e.size||!["object_put","object_multipart"].includes(n.strategy.kind))throw new w("invalid_sync_response","Authority returned an incompatible file upload session.");let i=n.strategy.kind==="object_multipart"?n.strategy.part_size:Math.max(1,e.size);if(!Number.isSafeInteger(i)||i<=0)throw new w("invalid_sync_response","Authority returned an invalid upload part size.");let s=new qm(t),o=Math.max(1,Math.ceil(e.size/i));if(n.received.some(d=>!Number.isSafeInteger(d)||d<0||d>=o)||new Set(n.received).size!==n.received.length)throw new w("invalid_sync_response","Authority returned invalid upload progress.");let a=n.uploaded_parts??[];if(a.some((d,f)=>!Number.isSafeInteger(d.part_number)||d.part_number<1||d.part_number>o||!d.etag||d.etag.length>255||f>0&&a[f-1].part_number>=d.part_number)||(n.strategy.kind==="object_multipart"?a.length!==n.received.length||a.some((d,f)=>d.part_number-1!==n.received[f]):a.length!==0))throw new w("invalid_sync_response","Authority returned invalid uploaded part receipts.");let c=n.received.reduce((d,f)=>{let p=f*i;return d+Math.min(i,Math.max(0,e.size-p))},0);if(this.onFileProgress?.({direction:"upload",path:e.path,transferredBytes:c,totalBytes:e.size}),n.received.length===o)return this.commitUpload(e.transfer_id,a);let l=new Set(n.received),u=Array.from({length:o},()=>{});for(let d of a)u[d.part_number-1]=d;for(let d=0;d=300)throw new In(y.status===429||y.status>=500?"authority_unavailable":"file_upload_failed",`Object storage returned HTTP ${y.status}.`,y.status);if(c+=p,this.onFileProgress?.({direction:"upload",path:e.path,transferredBytes:c,totalBytes:e.size}),n.strategy.kind==="object_multipart"){let g=s$(y.headers,"etag");if(!g)throw new w("invalid_sync_response","Object storage omitted a multipart ETag.");u[d]={part_number:d+1,etag:g}}}return await s.expectEnd(),this.commitUpload(e.transfer_id,u.filter(d=>d!==void 0))}async commitUpload(e,t){let n=await this.fileRequest("POST",`uploads/${encodeURIComponent(e)}/commit`,{protocol_version:1,type:"commit_file_upload",transfer_id:e,parts:t});if(n.protocol_version!==1||n.type!=="file_upload_committed"||n.transfer_id!==e)throw new w("invalid_sync_response","Authority returned an invalid file upload receipt.");return n}async moveFile(e){let t=await this.fileRequest("POST",`${encodeURIComponent(e.file_id)}/move`,e);if(t.protocol_version!==1||t.type!=="file_moved"||t.mutation_id!==e.mutation_id)throw new w("invalid_sync_response","Authority returned an invalid file move receipt.");return t}async deleteFile(e){let t=await this.fileRequest("POST",`${encodeURIComponent(e.file_id)}/delete`,e);if(t.protocol_version!==1||t.type!=="file_deleted"||t.mutation_id!==e.mutation_id||t.file_id!==e.file_id)throw new w("invalid_sync_response","Authority returned an invalid file delete receipt.");return t}changes(e,t=200){let n=new URLSearchParams({after:String(e),limit:String(t)});return this.request("GET",`changes?${n.toString()}`)}mutate(e){return this.request("POST","mutations",e)}async request(e,t,n){return this.requestAt(this.syncUrl,e,t,n)}async fileRequest(e,t,n){return this.requestAt(this.filesUrl,e,t,n)}async requestAt(e,t,n,i){let s=await this.authorized({url:`${e}/${n}`,method:t,body:i===void 0?void 0:JSON.stringify(i),contentType:i===void 0?void 0:"application/json",throw:!1}),o=ud(s.text,s.json);if(s.status<200||s.status>=300)throw this.responseError(s,"sync_failed");return o}async authorized(e){let t=s=>this.send({...e,headers:{authorization:`Bearer ${s}`},signal:this.signal}),n=await this.credentials.token(),i=await t(n);return i.status!==401||!this.credentials.renew?i:t(await this.credentials.renew(n))}responseError(e,t){let n=ud(e.text,e.json),i=Xe(n)&&Xe(n.error)?n.error:{},s=typeof i.code=="string"?i.code:e.status===401?"mirror_access_rejected":e.status===429||e.status>=500?"authority_unavailable":t;return new In(s,typeof i.message=="string"?i.message:`Sync request failed (${e.status}).`,e.status,aa(e.headers))}},qm=class{constructor(e){this.remainder=new Uint8Array;this.iterator=e[Symbol.asyncIterator]()}async read(e){let t=new Uint8Array(new ArrayBuffer(e)),n=0;for(;n!["authorization","cookie","host","proxy-authorization","content-length"].includes(e.toLowerCase())))}function s$(r,e){return Object.entries(r).find(([n])=>n.toLowerCase()===e.toLowerCase())?.[1]}function u$(r){return[r.configDir||".obsidian",...aF].map(t=>(0,J.normalizePath)(t).replace(/\/+$/,""))}function tn(r,e){let t=yn(e);if(u$(r).some(n=>t===n||t.startsWith(`${n}/`)))throw new w("unsafe_mirror_path",`The collection authority attempted to write a reserved path: ${t}`);return t}function fe(r){if(r?.aborted)throw new DOMException("Synchronization cancelled.","AbortError")}function St(r,e){return r??new Error(`IndexedDB ${e} failed without an error detail.`)}function gF(r,e){let t=async a=>{fe(e);let c=await a();return fe(e),c},n=async function*(a){fe(e);for await(let c of a)fe(e),yield c,fe(e);fe(e)},i=r.uploadFile?.bind(r),s=r.moveFile?.bind(r),o=r.deleteFile?.bind(r);return{openSession:()=>t(()=>r.openSession()),snapshot:(a,c)=>t(()=>r.snapshot(a,c)),fileSnapshot:(a,c)=>t(()=>r.fileSnapshot(a,c)),downloadFile:a=>n(r.downloadFile(a)),...i?{uploadFile:(a,c)=>t(()=>i(a,n(c)))}:{},...s?{moveFile:a=>t(()=>s(a))}:{},...o?{deleteFile:a=>t(()=>o(a))}:{},changes:(a,c)=>t(()=>r.changes(a,c)),mutate:a=>t(()=>r.mutate(a))}}async function Ms(r,e){let t=(0,J.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let n="";for(let i of t.split("/")){n=n?`${n}/${i}`:i;let s=r.getAbstractFileByPath(n);if(!(s instanceof J.TFolder)){if(s)throw new w("mirror_path_collision",`A file blocks the mirror folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}var Bm=class{constructor(e,t=s=>e.delete(s,!0),n=()=>{},i=()=>{}){this.vault=e;this.trashFile=t;this.assertActive=n;this.observeWrite=i}async exists(e){let t=tn(this.vault,e);return this.vault.getAbstractFileByPath(t)!==null||await this.vault.adapter.exists(t)}async read(e){let t=await this.readText(e);if(t===null||typeof t=="string")return t;throw new w(t.code,t.reason)}async readText(e){let t=tn(this.vault,e);if(this.vault.getAbstractFileByPath(t)instanceof J.TFolder)throw new w("mirror_path_collision",`Expected a file at ${t}.`);let i;try{i=await this.vault.adapter.readBinary(t)}catch{try{if(!await this.vault.adapter.exists(t))return null}catch{}throw new w("file_read_failed",`Could not read ${t}.`)}try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(i)}catch{return{kind:"invalid",code:"invalid_utf8",reason:"File is not valid UTF-8.",revision:(await fa(i)).content_digest}}}async pathKind(e){let t=tn(this.vault,e);return(await this.vault.adapter.stat(t))?.type??null}async write(e,t,n){let i=tn(this.vault,e),s=()=>new w("sync_plan_stale",`${i} changed before it could be written. Review sync again.`),o=n;if(o===void 0){let l=await this.readText(i);if(typeof l=="string"||l===null)o=l;else{let u=await this.vault.adapter.readBinary(i);if((await fa(u)).content_digest!==l.revision)throw s();o=new TextDecoder("utf-8",{ignoreBOM:!0}).decode(u)}}let a=i.lastIndexOf("/");a>=0&&await Ms(this.vault,i.slice(0,a));let c=this.vault.getAbstractFileByPath(i);if(c instanceof J.TFolder)throw new w("mirror_path_collision",`A folder blocks the mirror file ${i}.`);if(this.assertActive(),c instanceof J.TFile)await this.vault.process(c,l=>{if(this.assertActive(),c.path!==i||this.vault.getAbstractFileByPath(i)!==c||l!==o&&l!==t)throw s();return this.observeWrite(i),t});else{if(o!==null)throw s();this.observeWrite(i),await this.vault.create(i,t)}}async move(e,t){let n=tn(this.vault,e),i=tn(this.vault,t),s=this.vault.getAbstractFileByPath(n);if(!(s instanceof J.TFile))throw new w("mirror_path_collision",`Expected a file at ${n}.`);if(this.vault.getAbstractFileByPath(i)!==null||await this.vault.adapter.exists(i))throw new w("mirror_path_collision",`A file or folder blocks the mirror path ${i}.`);let o=i.lastIndexOf("/");o>=0&&await Ms(this.vault,i.slice(0,o)),this.assertActive(),this.observeWrite(n),this.observeWrite(i),await this.vault.rename(s,i)}async remove(e){let t=tn(this.vault,e),n=this.vault.getAbstractFileByPath(t);if(n!=null){if(!(n instanceof J.TFile))throw new w("mirror_path_collision",`Expected a file at ${t}.`);this.assertActive(),this.observeWrite(t),await this.trashFile(n)}}async listMarkdown(e){return pd(this.vault).map(t=>(0,J.normalizePath)(t.path)).filter(t=>dF.test(t)&&!e.has(t)).filter(t=>!u$(this.vault).some(n=>t===n||t.startsWith(`${n}/`))).sort()}async inspectBinary(e){let t=da(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof J.TFile))throw new w("mirror_path_collision",`Expected a file at ${t}.`);$i(n.stat.size);let i=await this.vault.readBinary(n);return $i(i.byteLength),fa(i)}async writeBinary(e,t,n){let i=da(e),s=n===void 0?await this.inspectBinary(i):n,o=await Fm(t),a=i.lastIndexOf("/");a>=0&&await Ms(this.vault,i.slice(0,a));let c=await this.inspectBinary(i);if(c?.content_digest!==s?.content_digest||c?.size!==s?.size)throw new w("sync_plan_stale",`${i} changed before it could be written. Review sync again.`);let l=this.vault.getAbstractFileByPath(i);if(l instanceof J.TFolder)throw new w("mirror_path_collision",`A folder blocks the mirror file ${i}.`);this.assertActive(),this.observeWrite(i),l instanceof J.TFile?await this.vault.modifyBinary(l,o):await this.vault.createBinary(i,o)}async listBinary(e){return pd(this.vault).map(t=>(0,J.normalizePath)(t.path)).filter(t=>!d$.test(t)&&!e.has(t)).filter(t=>{try{return da(t),!0}catch{return!1}}).sort()}async readBinary(e){let t=da(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof J.TFile))throw new w("mirror_path_collision",`Expected a file at ${t}.`);$i(n.stat.size);let i=new Uint8Array(await this.vault.readBinary(n));return $i(i.byteLength),(async function*(){for(let s=0;s{}),a}n&&n.stage!==i&&await this.removeStage(n.stage,n.chunks).catch(()=>{})}async remove(e){let t=await this.manifest(e);await this.delete(Nn,this.manifestKey(e)),t&&await this.removeStage(t.stage,t.chunks)}async prune(e){let t=await this.open(),n=await new Promise((o,a)=>{let c=[],l=t.transaction(Nn,"readonly").objectStore(Nn).openCursor();l.onsuccess=()=>{let u=l.result;if(!u)return o(c);c.push([u.key,u.value]),u.continue()},l.onerror=()=>a(St(l.error,"manifest cursor"))}),i=new Set;for(let[o,a]of n)!Array.isArray(o)||o[0]!==this.namespace||typeof o[1]=="string"&&e.has(o[1])||(await this.delete(Nn,o),await this.removeStage(a.stage,a.chunks));for(let[o,a]of n)Array.isArray(o)&&o[0]===this.namespace&&typeof o[1]=="string"&&e.has(o[1])&&i.add(a.stage);let s=await new Promise((o,a)=>{let c=[],l=t.transaction(Ln,"readonly").objectStore(Ln).openKeyCursor();l.onsuccess=()=>{let u=l.result;if(!u)return o(c);let d=u.key,f=Array.isArray(d)&&typeof d[1]=="string"?d[1]:null;Array.isArray(d)&&d[0]===this.namespace&&(f===null||!i.has(f))&&c.push(d),u.continue()},l.onerror=()=>a(St(l.error,"chunk cursor"))});for(let o of s)await this.delete(Ln,o)}manifest(e){return this.get(Nn,this.manifestKey(e))}manifestKey(e){return[this.namespace,e]}chunkKey(e,t){return[this.namespace,e,t]}async removeStage(e,t){for(let n=0;n{let o=n.transaction(e,"readonly").objectStore(e).get(t);o.onsuccess=()=>i(o.result??null),o.onerror=()=>s(St(o.error,`read from ${e}`))})}async put(e,t,n){let i=await this.open();await new Promise((s,o)=>{let a=i.transaction(e,"readwrite");a.objectStore(e).put(n,t),a.oncomplete=()=>s(),a.onerror=()=>o(St(a.error,`write to ${e}`)),a.onabort=()=>o(St(a.error,`write to ${e}`))})}async delete(e,t){let n=await this.open();await new Promise((i,s)=>{let o=n.transaction(e,"readwrite");o.objectStore(e).delete(t),o.oncomplete=()=>i(),o.onerror=()=>s(St(o.error,`delete from ${e}`)),o.onabort=()=>s(St(o.error,`delete from ${e}`))})}close(){this.database?.then(e=>e.close(),()=>{}),this.database=null}open(){if(typeof indexedDB>"u")throw new w("storage_unavailable","IndexedDB is required for binary file sync.");if(this.database)return this.database;let e=new Promise((t,n)=>{let i=indexedDB.open(tF,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Nn)||i.result.createObjectStore(Nn),i.result.objectStoreNames.contains(Ln)||i.result.createObjectStore(Ln)},i.onerror=()=>n(St(i.error,"binary store open")),i.onsuccess=()=>t(i.result)});return this.database=e,e.catch(()=>{this.database===e&&(this.database=null)}),e}},Vm=class{constructor(e){this.key=e;this.database=null}async read(){let e=await this.open();return new Promise((t,n)=>{let i=e.transaction(Dn,"readonly").objectStore(Dn).get(this.key);i.onsuccess=()=>t(i.result??null),i.onerror=()=>n(St(i.error,"mirror state read"))})}async write(e){let t=await this.open();await new Promise((n,i)=>{let s=t.transaction(Dn,"readwrite");s.objectStore(Dn).put(e,this.key),s.oncomplete=()=>n(),s.onerror=()=>i(St(s.error,"mirror state write")),s.onabort=()=>i(St(s.error,"mirror state write"))})}async clear(){let e=await this.open();await new Promise((t,n)=>{let i=e.transaction(Dn,"readwrite");i.objectStore(Dn).delete(this.key),i.oncomplete=()=>t(),i.onerror=()=>n(St(i.error,"mirror state clear")),i.onabort=()=>n(St(i.error,"mirror state clear"))})}close(){this.database?.then(e=>e.close(),()=>{}),this.database=null}open(){if(typeof indexedDB>"u")throw new w("storage_unavailable","IndexedDB is required for persistent mirror state.");if(this.database)return this.database;let e=new Promise((t,n)=>{let i=indexedDB.open(eF,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Dn)||i.result.createObjectStore(Dn)},i.onerror=()=>n(St(i.error,"mirror state store open")),i.onsuccess=()=>t(i.result)});return this.database=e,e.catch(()=>{this.database===e&&(this.database=null)}),e}},Hm=class r{constructor(e){this.key=e}static{this.active=new Set}async runExclusive(e){if(r.active.has(this.key))throw new w("mirror_busy","A mirror operation is already running for this vault.");r.active.add(this.key);try{return await e()}finally{r.active.delete(this.key)}}},fd=class{constructor(e,t,n={}){this.app=e;this.settingsHost=t;this.options=n;this.disposed=!1;this.lifetime=new AbortController;this.stateStores=new Map;this.blobStores=new Map;this.progress=null;this.fileProgress=null;this.syncAbort=null;this.statusRequest=null;this.mirrorOperationTail=Promise.resolve();this.adoptionMarker=null;this.adoptionBusy=!1;this.engineWrites=new Map;this.renewal=null;this.fileSystem=n.fileSystem??new Bm(e.vault,i=>e.fileManager.trashFile(i),()=>this.assertActive(),i=>this.noteEngineWrite(i)),this.enrollmentClient=n.enrollmentClient??new jl({request:fF()}),this.adoptionClient=n.adoptionClient??new Kl({request:pF()})}dispose(){this.disposed=!0,this.lifetime.abort(),this.cancelSync();for(let e of this.stateStores.values())e.close();for(let e of this.blobStores.values())e.close();this.stateStores.clear(),this.blobStores.clear()}async withLifetime(e,t){this.assertActive();let n=new AbortController,i=()=>n.abort();this.lifetime.signal.addEventListener("abort",i,{once:!0}),e?.addEventListener("abort",i,{once:!0}),e?.aborted&&n.abort();try{return fe(n.signal),await t(n.signal)}finally{this.lifetime.signal.removeEventListener("abort",i),e?.removeEventListener("abort",i)}}assertActive(){if(this.disposed)throw new DOMException("Plugin unloaded.","AbortError")}async withAdoptionOperation(e,t){if(this.adoptionBusy)throw new w("authority_adoption_busy","Stop the current move before changing its setup.");this.adoptionBusy=!0;try{return await this.withLifetime(e,t)}finally{this.adoptionBusy=!1}}async initialize(){this.adoptionMarker=await this.readAdoptionMarker();let e=this.settingsHost.getMirrorProfile();if(this.adoptionMarker&&e){if(this.adoptionMarker.phase==="adopted"&&this.adoptionMarker.session.requested.collectionId===e.collectionId){await this.assertMirror(e.collectionId),await this.clearAdoptionCheckpoint(this.adoptionMarker.session.adoptionId);return}throw new w("authority_adoption_state_conflict","This vault contains both an authority-adoption checkpoint and a mirror profile.")}}getProgress(){return this.progress?{...this.progress}:null}getFileProgress(){return this.fileProgress?{...this.fileProgress}:null}getAdoptionMarker(){return this.adoptionMarker?JSON.parse(JSON.stringify(this.adoptionMarker)):null}getAdoptionRecovery(){let e=this.adoptionMarker;if(!e)return null;try{if(this.app.secretStorage.getSecret(this.adoptionSecretId(e.session.adoptionId)))return null}catch{}let t=["waiting_for_approval","uploading"].includes(e.phase);return{canReset:t&&Date.parse(e.session.expiresAt)<=Date.now(),canReconnect:!t}}async resetExpiredAdoption(){return this.withAdoptionOperation(void 0,async()=>{let e=await this.readAdoptionMarker();if(e?.session.adoptionId!==this.adoptionMarker?.session.adoptionId)throw new w("authority_adoption_state_conflict","Move setup changed. Reopen Sync before recovering it.");if(this.adoptionMarker=e,!e||this.settingsHost.getMirrorProfile()||await this.app.vault.adapter.exists(On)||!this.getAdoptionRecovery()?.canReset)throw new w("authority_adoption_reset_unsafe","Only an expired move that never froze this vault can be reset locally.");await this.clearAdoptionCheckpoint(e.session.adoptionId)})}async reconnectAdoption(e){return this.withAdoptionOperation(e.signal,async t=>{let n=this.adoptionMarker;if(!n||!this.getAdoptionRecovery()?.canReconnect||this.settingsHost.getMirrorProfile())throw new w("authority_adoption_reconnect_unsafe","This move does not require hosted recovery.");let i=await this.enrollmentClient.enroll({controlUrl:n.session.controlUrl,collectionId:n.session.requested.collectionId,mirrorName:n.session.requested.mirrorName??n.session.requested.sourceName,mode:"read_write"},{...e,signal:t});if(i.collectionId!==n.session.requested.collectionId||i.mode!=="read_write")throw new w("authority_adoption_state_conflict","Connect approved a different collection or access mode; this vault remains protected.");return fe(t),await this.updateAdoptionPhase("adopted"),this.persistAdoptedMirror(n.session,i)})}getSelectiveSync(){return Ir(this.settingsHost.getMirrorProfile()?.selectiveSync??this.adoptionMarker?.selective_sync)}async configureSelectiveSync(e){let t=this.requireProfile();await this.settingsHost.saveMirrorProfile({...t,selectiveSync:Ir(e)})}assertLocalAuthorityWritable(){if(this.assertActive(),this.adoptionMarker&&["fenced","activating","adopted"].includes(this.adoptionMarker.phase))throw new w("local_authority_fenced",this.adoptionMarker.phase==="adopted"?"Hosted mdbase is now authoritative. Finish reconnecting this vault as its mirror before editing.":"This local authority is frozen while its exact snapshot is adopted by hosted mdbase.")}async adoptLocalCollection(e,t){return this.withAdoptionOperation(t.signal,n=>this.adoptLocalCollectionActive(e,{...t,signal:n}))}async adoptLocalCollectionActive(e,t){if(this.settingsHost.getMirrorProfile())throw new w("mirror_already_configured","This vault already mirrors a collection authority.");if(this.adoptionMarker)return this.resumeAdoptionActive(t);t.onProgress?.({stage:"checking"}),n$(await this.previewAdoption(e.selectiveSync,t.signal));let n=await this.ensurePortableCollectionIdentity(),i=await this.adoptionClient.begin({controlUrl:e.controlUrl,collectionId:n.collectionId,displayName:n.displayName,sourceName:e.mirrorName,retainMirror:!0,mirrorName:e.mirrorName},t);try{await this.storeAdoptionSecret(i)}catch(s){throw await this.adoptionClient.cancel(i,t).catch(()=>{}),s}return await this.writeAdoptionMarker({version:1,phase:"waiting_for_approval",session:Lm(i),selective_sync:Ir(e.selectiveSync),manifest_digest:null,source_revision:null,source_head:null}),await t.onVerification(Lm(i)),this.runAdoptionWithRecovery(i,t)}async resumeAdoption(e={}){return this.withAdoptionOperation(e.signal,t=>this.resumeAdoptionActive({...e,signal:t}))}async resumeAdoptionActive(e){let t=this.adoptionMarker??await this.readAdoptionMarker();if(!t)throw new w("authority_adoption_not_found","This vault has no collection-adoption checkpoint.");this.adoptionMarker=t;let n=this.app.secretStorage.getSecret(this.adoptionSecretId(t.session.adoptionId));if(!n)throw new w("authority_adoption_credentials_missing","The collection-adoption credential is missing from Obsidian's secret store.");let i={...t.session,credential:n};return t.phase==="waiting_for_approval"&&await e.onVerification?.(Lm(i)),this.runAdoptionWithRecovery(i,{...e,onVerification:s=>e.onVerification?.(s)})}async cancelAdoption(e){return this.withAdoptionOperation(e,t=>this.cancelAdoptionActive(t))}async cancelAdoptionActive(e){let t=this.adoptionMarker??await this.readAdoptionMarker();if(!t)return;if(["activating","adopted"].includes(t.phase))throw new w("authority_adoption_activation_started","Hosted activation has started and must be resumed; it can no longer be cancelled.");let n=this.app.secretStorage.getSecret(this.adoptionSecretId(t.session.adoptionId));if(!n)throw new w("authority_adoption_credentials_missing","The collection-adoption credential is missing from Obsidian's secret store.");await this.adoptionClient.cancel({...t.session,credential:n},{signal:e}),await this.clearAdoptionCheckpoint(t.session.adoptionId)}async enroll(e,t){return this.withLifetime(t.signal,n=>this.enrollActive(e,{...t,signal:n}))}async enrollActive(e,t){let n=await this.assertCanBecomeMirror(e.collectionId),i=await this.enrollmentClient.enroll({controlUrl:e.controlUrl,mirrorName:e.mirrorName,mode:e.mode,...n?{collectionId:n}:{}},t),s=await this.markMirror(i.collectionId);try{await this.persistEnrollment(i,e.selectiveSync)}catch(o){if(s)try{await this.app.vault.adapter.remove(On)}catch{throw new w("enrollment_recovery_required",`Enrollment settings could not be saved and the temporary role marker could not be removed: ${o instanceof Error?o.message:String(o)}`)}throw o}return this.requireProfile()}async inspect(){return this.withMirrorOperation(async()=>{let e=this.requireProfile();await this.assertMirror(e.collectionId);let t=await this.createMirror(),{plan:n,status:i}=await t.review();return{preview:$m(n),status:i}})}async preview(){return this.withMirrorOperation(async()=>{let e=this.requireProfile();await this.assertMirror(e.collectionId);let t=await this.createMirror();return $m(await t.inspect())})}async status(){if(this.statusRequest)return this.statusRequest;let e=this.readStatus();this.statusRequest=e;try{return await e}finally{this.statusRequest===e&&(this.statusRequest=null)}}async readStatus(){return this.withMirrorOperation(async()=>{let e=this.settingsHost.getMirrorProfile();return e?(await this.assertMirror(e.collectionId),(await this.createMirror()).status()):null})}async remoteChangesWaiting(){let e=this.requireProfile(),t=await this.stateStoreFor(e).read();if(!t||t.batch)return!0;let i=await(await this.transportFor(e)).changes(t.cursor,1);return i.reset_required||i.scope_epoch!==t.scope_epoch||i.head>t.cursor}async checkpointSummary(){let e=this.settingsHost.getMirrorProfile();if(!e)return null;let t=await this.stateStoreFor(e).read();return t?{cursor:t.cursor,generation:t.generation??0,batch:t.batch?`${t.batch.phase} at action ${t.batch.next_action}/${t.batch.plan.actions.length}`:null,failure:t.batch?.failure?`${t.batch.failure.code}: ${t.batch.failure.message}`:null}:null}async reconnect(){let e=this.requireProfile();this.assertThisDevice(e),await this.renewAccessToken(e);let t=await this.status();if(!t)throw new w("mirror_not_configured","The renewed mirror profile could not be loaded.");return t}async reauthorize(e){return this.withLifetime(e.signal,t=>this.reauthorizeActive({...e,signal:t}))}async reauthorizeActive(e){let t=this.requireProfile(),n=this.isOtherDevice(t),i=this.stateStoreFor(t);if((n?null:await i.read())?.batch)throw new w("mirror_recovery_required","Resume the durable synchronization checkpoint before approving this vault again.");let o=await this.enrollmentClient.enroll({controlUrl:t.controlUrl,mirrorName:t.name,mode:t.mode,collectionId:t.collectionId},e);if(o.collectionId!==t.collectionId)throw new w("mirror_identity_conflict","Connect approved a different collection. The existing mirror was not changed.");return this.withMirrorOperation(async()=>{let a=this.requireProfile();if(a.collectionId!==t.collectionId||a.replicaId!==t.replicaId||a.enrollmentId!==t.enrollmentId)throw new w("mirror_identity_conflict","The connection changed during approval. The current mirror was not changed.");let c=n?null:await i.read();if(c?.batch)throw new w("mirror_recovery_required","Resume the durable synchronization checkpoint before approving this vault again.");let l=o$(o,a.selectiveSync);return c&&o.replicaId!==t.replicaId&&await this.stateStoreFor(l).write({...c,replica_id:o.replicaId}),await this.persistEnrollment(o,a.selectiveSync),!n&&o.replicaId!==t.replicaId&&(this.clearCredentials(t),"clear"in i&&typeof i.clear=="function"&&await i.clear()),(await this.createMirror()).status()})}async conflictComparison(e){let t=this.requireProfile(),n=await this.transportFor(t),i=await n.openSession(),s={state:"absent"};if(e.entity==="record"){let l;do{let u=await n.snapshot(i.snapshot_id,l),d=u.records.find(f=>f.record_id===e.object_id);if(d){s={state:"exact",path:d.path,revision:d.revision,size:new TextEncoder().encode(d.document).byteLength,document:d.document};break}l=u.next_page}while(l)}else{let l;do{let u=await n.fileSnapshot(i.snapshot_id,l),d=u.files.find(f=>f.file_id===e.object_id);if(d){s={state:"exact",path:d.path,revision:d.content_digest,size:d.size,modifiedAt:d.modified_at};break}l=u.next_page}while(l)}let o=e.path??s.path,a={state:"absent"};if(o){let l=this.app.vault.getAbstractFileByPath(o);if(l instanceof J.TFile)if(e.entity==="record"){let u=await this.app.vault.cachedRead(l);a={state:"exact",path:o,size:new TextEncoder().encode(u).byteLength,modifiedAt:l.stat?.mtime?new Date(l.stat.mtime).toISOString():void 0,document:u}}else{let u=await this.fileSystem.inspectBinary(o);u&&(a={state:"exact",path:o,revision:u.content_digest,size:u.size,modifiedAt:l.stat?.mtime?new Date(l.stat.mtime).toISOString():void 0,resourceUrl:this.app.vault.getResourcePath(l)})}}if(!(await this.status())?.conflicts.some(l=>l.object_id===e.object_id&&l.decision_id===e.decision_id))throw new w("conflict_decision_stale","This file changed again while its versions were loading.");return{entity:e.entity,objectId:e.object_id,decisionId:e.decision_id,local:a,remote:s}}async recordComparison(e,t){let n=this.requireProfile(),i=await this.transportFor(n),s=await i.openSession(),o={state:"absent"},a;do{let u=await i.snapshot(s.snapshot_id,a),d=u.records.find(f=>f.record_id===e);if(d){o={state:"exact",path:d.path,revision:d.revision,size:new TextEncoder().encode(d.document).byteLength,document:d.document};break}a=u.next_page}while(a);let c={state:"absent"},l=this.app.vault.getAbstractFileByPath(tn(this.app.vault,t));if(l instanceof J.TFile){let u=await this.app.vault.cachedRead(l);c={state:"exact",path:l.path,size:new TextEncoder().encode(u).byteLength,document:u}}return{entity:"record",objectId:e,decisionId:"",local:c,remote:o}}async autoResolveConflicts(){return this.withMirrorOperation(()=>this.autoResolveConflictsActive())}async autoResolveConflictsActive(){if(!this.settingsHost.getMirrorProfile())return[];let e=await this.createMirror(),t=await e.status();if(!t?.conflicts.length||t.recovery_required)return[];let n=this.requireProfile(),i=await this.stateStoreFor(n).read();if(!i||i.batch)return[];let s=t.conflicts.filter(c=>c.entity==="record"&&i.planned_conflicts?.[c.object_id]?.conflict_kind==="both_changed").map(c=>c.object_id),o=s.length?await this.remoteRecords(new Set(s)):new Map,a=[];for(let c of t.conflicts){let l=i.planned_conflicts?.[c.object_id];if(l)try{a.push(await this.autoResolve(e,c,l,o.get(c.object_id)))}catch(u){if(u instanceof w&&["conflict_decision_stale","sync_plan_stale"].includes(u.code))continue;a.push({path:c.path??c.object_id,outcome:"unresolved",reason:u instanceof Error?u.message:String(u)})}}return a}async autoResolve(e,t,n,i){let{object_id:s,decision_id:o}=t,a=n.local.state==="exact"?n.local.object.path:null,c=n.remote.state==="exact"?n.remote.object.path:null,l=t.path??a??c??s;if(n.conflict_kind==="rejected")return{path:l,outcome:"unresolved",reason:t.message};if(a===null)return await e.resolveConflict(s,o,"remote"),{path:l,outcome:c?"restored":"took_hosted"};if(c===null)return await e.resolveConflict(s,o,"local"),{path:l,outcome:"kept_local"};if(t.entity==="record"&&n.conflict_kind==="both_changed"&&i&&i.path===a&&n.remote.state==="exact"&&i.revision===n.remote.object.revision){let d=n.ancestor_document,f=await this.fileSystem.read(a);if(d!==void 0&&f!==null){let p=Zx(d,f,i.document,Z2);if(p.clean)return await e.resolveConflict(s,o,"local",p.text),{path:l,outcome:"merged"}}}let u=await this.preserveConflictCopy(a);return await e.resolveConflict(s,o,"remote"),{path:l,outcome:"kept_both",copyPath:u}}async remoteRecords(e){let t=await this.transportFor(this.requireProfile()),n=await t.openSession(),i=new Map,s;do{let o=await t.snapshot(n.snapshot_id,s);for(let a of o.records)e.has(a.record_id)&&i.set(a.record_id,{path:a.path,revision:a.revision,document:a.document});s=i.size===e.size?void 0:o.next_page}while(s);return i}async createConflictCopy(e,t,n){let i=e.lastIndexOf("/"),s=e.lastIndexOf("."),o=s>i?e.slice(s):"",c=(o?e.slice(0,-o.length):e).replace(/(?: \((?:local|hosted) conflict copy(?: \d+)?\))+$/,""),l=new Uint8Array(t),u=1;for(;;){let d=`${c} (${n}${u===1?"":` ${u}`})${o}`;if(d===e){u+=1;continue}if(this.app.vault.getAbstractFileByPath(d)||await this.app.vault.adapter.exists(d)){try{let f=new Uint8Array(await this.app.vault.adapter.readBinary(d));if(f.length===l.length&&f.every((p,h)=>p===l[h]))return d}catch{}u+=1;continue}try{return await this.app.vault.createBinary(d,t),d}catch(f){if(!await this.app.vault.adapter.exists(d))throw f}}}async preserveConflictCopy(e){let t=tn(this.app.vault,e);if(!(this.app.vault.getAbstractFileByPath(t)instanceof J.TFile))throw new w("mirror_conflict_copy_missing",`No local file exists at ${t}.`);let i=await this.app.vault.adapter.readBinary(t);return this.createConflictCopy(t,i,"local conflict copy")}async disconnect(e){if(this.isSyncing())throw new w("mirror_busy","Stop the current synchronization before disconnecting.");return this.withMirrorOperation(()=>this.disconnectActive(e))}async disconnectActive(e){if(this.isSyncing())throw new w("mirror_busy","Stop the current synchronization before disconnecting.");let t=this.requireProfile(),n=this.stateStoreFor(t),i=await n.read();if(i?.batch)throw new w("mirror_recovery_required","Resume the durable synchronization checkpoint before disconnecting.");let s={removed:[],preserved:[]},o=await this.readMarker();o&&await this.app.vault.adapter.remove(On);try{await this.settingsHost.saveMirrorProfile(null)}catch(a){throw o&&await this.markMirror(t.collectionId),a}return this.isOtherDevice(t)||(this.clearCredentials(t),"clear"in n&&typeof n.clear=="function"&&await n.clear(),await this.blobStoreFor(t).prune(new Set)),e&&i&&await this.removeExactMirrorFiles(i,s),s}async sync(e,t,n,i){if(this.syncAbort)throw new w("mirror_busy","Synchronization is already running for this vault.");let s=new AbortController;this.syncAbort=s;try{return await this.withMirrorOperation(async()=>{let a=await(await this.createMirror(c=>{fe(s.signal),this.progress=c,t?.({...c})},s.signal,c=>{fe(s.signal),this.fileProgress=c,n?.({...c})},i)).apply(e.plan,{signal:s.signal});return fe(s.signal),a})}finally{this.progress=null,this.fileProgress=null,this.syncAbort=null}}cancelSync(){this.syncAbort?.abort()}noteEngineWrite(e){let t=Date.now();for(let[n,i]of this.engineWrites)t-i>r$&&this.engineWrites.delete(n);this.engineWrites.set((0,J.normalizePath)(e),t)}consumeEngineWrite(e){let t=(0,J.normalizePath)(e),n=this.engineWrites.get(t);this.engineWrites.delete(t);let i=n===void 0?-1:Date.now()-n;return i>=0&&i<=r$}isSyncing(){return this.syncAbort!==null}async resolveConflict(e,t,n){return this.withMirrorOperation(async()=>{let i=await this.createMirror();return await i.resolveConflict(e,t,n),i.status()})}async withMirrorOperation(e){let t=this.mirrorOperationTail,n;this.mirrorOperationTail=new Promise(i=>{n=i}),await t;try{return this.assertActive(),await e()}finally{n()}}async runAdoption(e,t){let n=this.requireAdoptionMarker(e.adoptionId),i=null;if(n.phase==="adopted"){let s=await this.adoptionClient.exchange(e,t);if(s.status!=="completed")throw new w("authority_adoption_state_conflict","The local checkpoint says adoption completed, but Connect does not.");i=s}else if(n.phase==="activating"){t.onProgress?.({stage:"activating"});let s=await this.readAdoptionSnapshot(n),o=await this.adoptionClient.exchange(e,t);i=o.status==="completed"?o:await this.adoptionClient.complete(e,s,t)}else if(n.phase==="fenced"){let s=await this.readAdoptionSnapshot(n),o=await this.adoptionClient.exchange(e,t);o.status==="completed"?i=o:(o.status==="ready"&&(t.onProgress?.({stage:"uploading",records:s.records.length}),await this.adoptionClient.uploadSnapshot(e,o,s,this.adoptionUploadOptions(e,t))),await this.updateAdoptionPhase("activating",s),t.onProgress?.({stage:"activating"}),i=await this.adoptionClient.complete(e,s,t))}else{let s=n.phase==="waiting_for_approval"?await this.adoptionClient.waitForApproval(e,t):await this.requirePreparedAdoption(e,t);await this.updateAdoptionPhase("uploading",void 0,s.adoption.expires_at),t.onProgress?.({stage:"checking"});let o=await this.captureAuthoritySnapshot(e.requested.collectionId,t.signal);t.onProgress?.({stage:"uploading",records:o.records.length}),await this.adoptionClient.uploadSnapshot(e,s,o,this.adoptionUploadOptions(e,t)),t.onProgress?.({stage:"checking"});let a=await this.captureAuthoritySnapshot(e.requested.collectionId,t.signal);await this.writeAdoptionSnapshot(a),await this.updateAdoptionPhase("fenced",a);let c=await this.requirePreparedAdoption(e,t);t.onProgress?.({stage:"uploading",records:a.records.length}),await this.adoptionClient.uploadSnapshot(e,c,a,this.adoptionUploadOptions(e,t)),await this.updateAdoptionPhase("activating",a),t.onProgress?.({stage:"activating"}),i=await this.adoptionClient.complete(e,a,t)}return await this.updateAdoptionPhase("adopted"),t.onProgress?.({stage:"connecting"}),this.finishRetainedMirror(e,i,t)}async runAdoptionWithRecovery(e,t){try{return await this.runAdoption(e,t)}catch(n){throw t.signal?.aborted?new DOMException("Adoption paused.","AbortError"):bF(n)?(await this.adoptionClient.cancel(e,{signal:t.signal}).catch(()=>{}),await this.clearAdoptionCheckpoint(e.adoptionId),new w(n.code,"This adoption ended before hosted activation. The vault remains the writable local authority; start a new adoption to try again.")):n}}async requirePreparedAdoption(e,t){let n=await this.adoptionClient.exchange(e,t);if(n.status==="ready")return n;throw n.status==="activating"?new Jr("Hosted authority activation has already started. Resume using the saved fenced snapshot."):new w("authority_adoption_already_completed","Hosted authority has already adopted this collection.")}async finishRetainedMirror(e,t,n){let i,s=this.adoptionClient.mirrorEnrollmentSession(e,t);if(!s)throw new w("authority_adoption_mirror_missing","Hosted authority activated without retaining this vault as a mirror.");try{i=await this.enrollmentClient.waitForApproval(s,{signal:n.signal,onStatus:o=>n.onStatus?.({...o,state:o.state})})}catch(o){if(n.signal?.aborted)throw o;i=await this.enrollmentClient.enroll({controlUrl:e.controlUrl,collectionId:e.requested.collectionId,mirrorName:e.requested.mirrorName??e.requested.sourceName,mode:"read_write"},{signal:n.signal,onVerification:a=>n.onVerification(a)})}return this.persistAdoptedMirror(e,i)}async persistAdoptedMirror(e,t){let n=await this.markMirror(t.collectionId);try{await this.persistEnrollment(t,this.adoptionMarker?.selective_sync)}catch(i){throw n&&await this.app.vault.adapter.remove(On),i}return await this.clearAdoptionCheckpoint(e.adoptionId),this.requireProfile()}async adoptionSources(e,t){fe(t);let n=await ai(this.app.vault);if(fe(t),!n)throw new w("invalid_collection_configuration","A valid mdbase.yaml is required.");let i=await this.app.vault.adapter.read("mdbase.yaml");fe(t);let s=(0,J.parseYaml)(i),o=`${(0,J.normalizePath)(n.settings.types_folder)}/`,a=this.app.vault.getMarkdownFiles().filter(h=>(0,J.normalizePath)(h.path).startsWith(o)).sort((h,m)=>h.path.localeCompare(m.path)),c=vF(s).map(h=>(0,a$.default)(h,{dot:!0})),l=pd(this.app.vault).filter(h=>h.extension==="base"&&c.some(m=>m((0,J.normalizePath)(h.path)))).sort((h,m)=>h.path.localeCompare(m.path)),u=this.app.vault.getMarkdownFiles().filter(h=>!yt((0,J.normalizePath)(h.path),n)).sort((h,m)=>h.path.localeCompare(m.path)),d=["mdbase.yaml",...a.map(h=>h.path),...l.map(h=>h.path)],f=e.file_classes.length?(await this.fileSystem.listBinary?.(new Set(d))??[]).filter(h=>lF(e,h)&&!yt(h,n)):[];fe(t);let p={records:u.length,resources:d.length,files:f.length,conflicts:Dm([...d,...u.map(h=>h.path),...f])};return{config:n,configuration:i,typeFiles:a,baseFiles:l,recordFiles:u,binaryPaths:f,resourcePaths:d,preview:p}}renameNamespace(){return this.app.vault.getAllLoadedFiles?.()??pd(this.app.vault)}async planAdoptionRenames(e=this.getSelectiveSync()){this.assertActive();let{preview:t,resourcePaths:n}=await this.adoptionSources(Ir(e)),i=this.renameNamespace().map(c=>c.path).sort(),s=t$(t.conflicts,i,new Set(n)),o=s.renames.map(({from:c})=>{let l=this.app.vault.getAbstractFileByPath(c);return[c,l instanceof J.TFile?l.stat:null]}),a=(await fa(new TextEncoder().encode(JSON.stringify({paths:i,sources:o,proposed:s,policy:e})).buffer)).content_digest;return{...s,revision:a}}async applyAdoptionRenames(e,t=this.getSelectiveSync(),n){return this.withAdoptionOperation(void 0,async i=>{if(this.assertLocalAuthorityWritable(),this.settingsHost.getMirrorProfile()||await this.app.vault.adapter.exists(On))throw new w("adoption_rename_unsafe","Automatic rename review is only available before this vault becomes a mirror.");let s=await this.planAdoptionRenames(t);if(JSON.stringify(s)!==JSON.stringify(e))throw new w("adoption_rename_stale","Files changed since the rename review. Review the new suggestions before renaming.");let o=e.renames.map(c=>this.app.vault.getAbstractFileByPath(c.from)),a=0;n?.(0,e.renames.length);for(let[c,l]of e.renames.entries()){let u=o[c];try{if(fe(i),this.assertLocalAuthorityWritable(),!(u instanceof J.TFile)||u.path!==l.from||this.app.vault.getAbstractFileByPath(l.from)!==u)throw new Error("The source file changed. Review again.");if(this.renameNamespace().some(d=>xi(d.path)===xi(l.to))||await this.app.vault.adapter.exists(l.to))throw new Error("The destination is now occupied. Review again.");fe(i),await this.app.fileManager.renameFile(u,l.to),a++}catch(d){throw u?.path===l.to&&a++,new w("adoption_rename_failed",`Rename stopped after ${a} of ${e.renames.length} files. Check filenames and links before retrying. ${d instanceof Error?d.message:String(d)}`)}n?.(a,e.renames.length)}return a})}async previewAdoption(e=this.getSelectiveSync(),t){return this.assertActive(),(await this.adoptionSources(Ir(e),t)).preview}async captureAuthoritySnapshot(e,t){let{config:n,configuration:i,typeFiles:s,baseFiles:o,recordFiles:a,binaryPaths:c,preview:l}=await this.adoptionSources(this.getSelectiveSync(),t);n$(l);let u=[{path:"mdbase.yaml",kind:"configuration",document:i}];for(let[p,h]of[["type",s],["view",o]])for(let m of h)fe(t),u.push({path:(0,J.normalizePath)(m.path),kind:p,document:await this.app.vault.cachedRead(m)});let d=[];for(let p of a){fe(t);let h=(0,J.normalizePath)(p.path),m=await this.app.vault.cachedRead(p);fe(t),d.push({path:h,document:m})}let f=[];if(c.length){let p=this.adoptionBlobStore(e);for(let h of c){fe(t);let m=await this.fileSystem.readBinary?.(h);if(fe(t),!m)continue;let y=await Fm(m);fe(t);let g=await fa(y);fe(t),await p.write(g.content_digest,(async function*(){yield new Uint8Array(y)})()),fe(t);let b=this.app.vault.getAbstractFileByPath(h);f.push({file_id:zl(e,`file:${h}`),path:h,revision:g.content_digest,...g,...i$(h)?{media_type:i$(h)}:{},media_class:l$(h),modified_at:new Date(b instanceof J.TFile&&b.stat?.mtime?b.stat.mtime:Date.now()).toISOString()})}}return fe(t),im({collectionId:e,sourceHead:0,specVersion:n.spec_version,resources:u,records:d,files:f})}adoptionBlobStore(e){return this.options.adoptionBlobStoreFactory?.(e)??this.cachedBlobStore(`adoption:${e}`)}adoptionUploadOptions(e,t){let n=this.adoptionBlobStore(e.requested.collectionId);return{signal:t.signal,fileSource:async i=>Fm(n.read(i.content_digest)),onFileProgress:({file:i,transferredBytes:s,totalBytes:o})=>t.onFileProgress?.(i.path,s,o)}}async ensurePortableCollectionIdentity(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))throw new w("collection_not_initialized","Initialize an mdbase collection before hosting it.");let e=await this.app.vault.adapter.read("mdbase.yaml"),t;try{t=(0,J.parseYaml)(e)}catch{throw new w("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!Xe(t))throw new w("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let n=Xe(t["x-mdbase-connect"])?t["x-mdbase-connect"].collection_id:void 0,i;if(n===void 0){i=crypto.randomUUID();let o=Xe(t["x-mdbase-connect"])?t["x-mdbase-connect"]:{};t["x-mdbase-connect"]={...o,collection_id:i},this.assertActive(),await this.app.vault.adapter.write("mdbase.yaml",(0,J.stringifyYaml)(t))}else if(typeof n=="string"&&ua.test(n))i=n;else throw new w("invalid_collection_configuration","x-mdbase-connect.collection_id must be a UUID string.");let s=typeof t.name=="string"&&t.name.trim()?t.name.trim():this.app.vault.getName();return{collectionId:i,displayName:s}}stateStoreFor(e){if(this.assertActive(),this.options.stateStoreFactory)return this.options.stateStoreFactory(e);let t=`${e.collectionId}:${e.replicaId}`,n=this.stateStores.get(t);return n||(n=new Vm(t),this.stateStores.set(t,n)),n}cachedBlobStore(e){this.assertActive();let t=this.blobStores.get(e);return t||(t=new Um(e),this.blobStores.set(e,t)),t}blobStoreFor(e){return this.options.blobStoreFactory?.(e)??this.cachedBlobStore(`${e.collectionId}:${e.replicaId}`)}async transportFor(e,t,n){this.assertActive(),this.assertThisDevice(e),await this.claimLegacyProfile(e);let i=await this.freshAccessToken(e);this.assertActive();let s=this.options.transportFactory?.(e,i)??new jm(e.syncUrl,this.transportCredentials(e),hd,n,t);return gF(s,t)}async createMirror(e,t,n,i){let s=this.requireProfile();await this.assertMirror(s.collectionId);let o=await this.transportFor(s,t,n),a=this.stateStoreFor(s),c={stateStore:i?new ad(a,i):a,fileSystem:this.fileSystem,blobStore:this.blobStoreFor(s),selectiveSync:Ir(s.selectiveSync),lease:this.options.leaseFactory?.(s)??new Hm(`${s.collectionId}:${s.replicaId}`),onProgress:e};return s.mode==="read_write"?new sa(s.replicaId,o,c):new Si(s.replicaId,o,c)}requireProfile(){this.assertActive();let e=this.settingsHost.getMirrorProfile();if(!e)throw new w("mirror_not_configured","This vault is not connected to a collection authority.");return e}secretIds(e,t){let n=e==="access"?nF:iF;return{current:`${n}${t.replicaId.toLowerCase()}`,legacy:`${n}${t.collectionId.toLowerCase()}`}}readSecret(e,t){let n=this.secretIds(e,t),i=this.app.secretStorage.getSecret(n.current);if(i)return i;let s=this.app.secretStorage.getSecret(n.legacy);if(!s)return null;try{this.app.secretStorage.setSecret(n.current,s)}catch{}return s}clearCredentials(e){for(let t of["access","refresh"]){let n=this.secretIds(t,e),i=this.app.secretStorage.getSecret(n.current);i&&this.app.secretStorage.getSecret(n.legacy)===i&&this.app.secretStorage.setSecret(n.legacy,""),this.app.secretStorage.setSecret(n.current,"")}}currentDeviceId(){return this.settingsHost.deviceId?.()}isOtherDevice(e=this.settingsHost.getMirrorProfile()){let t=this.currentDeviceId();return!!(e?.deviceId&&t&&e.deviceId!==t)}async claimLegacyProfile(e){let t=this.currentDeviceId();e.deviceId||!t||await this.settingsHost.saveMirrorProfile({...e,deviceId:t})}assertThisDevice(e){if(this.isOtherDevice(e))throw new w("mirror_other_device","This vault's sync settings were copied from another device or vault. Set up sync here to give this copy its own connection.")}adoptionSecretId(e){return`${sF}${e.toLowerCase()}`}async storeAdoptionSecret(e){try{let t=this.adoptionSecretId(e.adoptionId);if(this.app.secretStorage.setSecret(t,e.credential),this.app.secretStorage.getSecret(t)!==e.credential)throw new Error("Secret was not retained")}catch{throw new w("authority_adoption_credentials_unavailable","Obsidian could not save this device's authorization. Unlock or repair Obsidian's secret storage before starting the move. Nothing was uploaded.")}}async persistEnrollment(e,t){this.assertActive();try{let n=this.secretIds("access",e).current,i=this.secretIds("refresh",e).current;if(this.app.secretStorage.setSecret(n,e.accessToken),this.app.secretStorage.setSecret(i,e.refreshCredential),this.app.secretStorage.getSecret(n)!==e.accessToken||this.app.secretStorage.getSecret(i)!==e.refreshCredential)throw new Error("Secret was not retained")}catch{throw new w("mirror_credentials_unavailable","Obsidian could not save this device's authorization. Unlock or repair Obsidian's secret storage, then reconnect. Your files were not changed.")}await this.settingsHost.saveMirrorProfile(o$(e,t??this.settingsHost.getMirrorProfile()?.selectiveSync,this.currentDeviceId()))}async removeExactMirrorFiles(e,t){let n=new Map;for(let[i,s]of Object.entries(e.records)){let o=e.local_bindings?.[i]?.path??s.path;n.set(o,{entity:"document",document:s.record?.document,revision:s.revision})}for(let[i,s]of Object.entries(e.resources??{})){let o=e.local_bindings?.[i]?.path??s.path;n.set(o,{entity:"document",document:s.record?.document,revision:s.revision})}for(let[i,s]of Object.entries(e.files??{})){let o=e.local_bindings?.[i]?.path??s.file.path;n.set(o,{entity:"file",digest:s.file.content_digest,size:s.file.size})}for(let[i,s]of[...n.entries()].sort(([o],[a])=>a.localeCompare(o))){let o=!1;if(s.entity==="document"){let a=await this.fileSystem.read(i);o=a!==null&&(s.document!==void 0?a===s.document:await SF(a,s.revision))}else if(s.entity==="file"){let a=await this.fileSystem.inspectBinary(i);o=a!==null&&a.content_digest===s.digest&&a.size===s.size}if(!o){await this.fileSystem.exists(i)&&t.preserved.push(i);continue}try{await this.fileSystem.remove(i),t.removed.push(i)}catch{t.preserved.push(i)}}}async freshAccessToken(e){if(this.renewal)return this.renewal;let t=this.readSecret("access",e),n=Date.parse(e.accessTokenExpiresAt);return t&&Number.isFinite(n)&&n-Date.now()>oF?t:this.renewAccessToken(e)}renewAccessToken(e){return this.renewal??=this.renewAccessTokenOnce(e).finally(()=>{this.renewal=null}),this.renewal}async renewAccessTokenOnce(e){let t=this.readSecret("refresh",e);if(!t)throw new w("mirror_credentials_missing","The mirror refresh credential is missing. Approve this vault again.");let n=await this.enrollmentClient.renew({controlUrl:e.controlUrl,syncUrl:e.syncUrl,collectionId:e.collectionId,replicaId:e.replicaId,mode:e.mode,name:e.name,enrollmentId:e.enrollmentId,accessToken:this.readSecret("access",e)??"",refreshCredential:t,accessTokenExpiresAt:e.accessTokenExpiresAt},{signal:this.lifetime.signal}),i=this.requireProfile();if(i.collectionId!==e.collectionId||i.replicaId!==e.replicaId||i.enrollmentId!==e.enrollmentId)throw new w("mirror_identity_conflict","The connection changed while credentials were renewing. Retry with the current connection.");return await this.persistEnrollment(n,i.selectiveSync),n.accessToken}transportCredentials(e){return{token:()=>this.freshAccessToken(this.requireProfile()),renew:async t=>{let n=this.readSecret("access",e);return n&&n!==t?n:this.renewAccessToken(this.requireProfile())}}}async assertCanBecomeMirror(e){let t=await this.readMarker(),n=await this.readPortableCollectionId();if(n&&!t)throw new w("local_authority_requires_transfer","This vault has a local Connect identity. Transfer authority explicitly before using it as a mirror.");if(n&&t?.collection_id!==n)throw new w("mirror_identity_conflict","The vault identity and mirror role marker identify different collections.");let i=this.settingsHost.getMirrorProfile(),s=i?.collectionId??e;if(t&&s&&t.collection_id!==s)throw new w("mirror_identity_conflict","This vault is already marked as a different mirror.");if(!t&&!i&&await this.app.vault.adapter.exists("mdbase.yaml"))throw new w("existing_collection_requires_transfer","This vault already contains an mdbase collection. Connect an empty vault, or transfer collection authority explicitly.");return s??t?.collection_id}async readPortableCollectionId(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))return null;let e;try{e=(0,J.parseYaml)(await this.app.vault.adapter.read("mdbase.yaml"))}catch{throw new w("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!Xe(e))throw new w("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let t=e["x-mdbase-connect"];if(t===void 0)return null;if(!Xe(t))throw new w("invalid_collection_configuration","x-mdbase-connect must be a YAML mapping.");let n=t.collection_id;if(n===void 0)return null;if(typeof n!="string"||!ua.test(n))throw new w("invalid_collection_configuration","x-mdbase-connect.collection_id must be a UUID string.");return n}async markMirror(e){this.assertActive();let t=await this.readMarker();if(t){if(t.collection_id!==e)throw new w("mirror_identity_conflict","This vault already mirrors a different collection authority.");return!1}return await Ms(this.app.vault,".mdbase"),this.assertActive(),await this.app.vault.adapter.write(On,`${JSON.stringify({version:1,role:"mirror",collection_id:e},null,2)} +`),!0}async assertMirror(e){let t=await this.readMarker();if(!t||t.collection_id!==e)throw new w("mirror_marker_missing","The vault's mirror role marker is missing or does not match this connection.")}async readMarker(){if(!await this.app.vault.adapter.exists(On))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(On))}catch{throw new w("invalid_mirror_marker","The mirror role marker is corrupt.")}if(!Xe(e)||e.version!==1||e.role!=="mirror"||typeof e.collection_id!="string"||!ua.test(e.collection_id))throw new w("invalid_mirror_marker","The mirror role marker is invalid.");return e}requireAdoptionMarker(e){if(!this.adoptionMarker||this.adoptionMarker.session.adoptionId!==e)throw new w("authority_adoption_state_conflict","The collection-adoption checkpoint does not match this approval.");return this.adoptionMarker}async updateAdoptionPhase(e,t,n){if(!this.adoptionMarker)throw new w("authority_adoption_not_found","Collection-adoption checkpoint is missing.");await this.writeAdoptionMarker({...this.adoptionMarker,phase:e,...n?{session:{...this.adoptionMarker.session,expiresAt:n}}:{},...t?{manifest_digest:t.manifest_digest,source_revision:t.source_revision,source_head:t.source_head}:{}})}async writeAdoptionMarker(e){await Ms(this.app.vault,".mdbase"),this.assertActive(),await this.app.vault.adapter.write(ca,`${JSON.stringify(e,null,2)} +`),this.adoptionMarker=e}async readAdoptionMarker(){if(!await this.app.vault.adapter.exists(ca))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(ca))}catch{throw new w("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is corrupt.")}if(!wF(e))throw new w("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is invalid.");return e}async writeAdoptionSnapshot(e){this.assertActive(),await Ms(this.app.vault,".mdbase"),this.assertActive(),await this.app.vault.adapter.write(la,JSON.stringify(e))}async readAdoptionSnapshot(e){if(!await this.app.vault.adapter.exists(la))throw new w("authority_adoption_snapshot_missing","The fenced authority snapshot is missing; hosted activation cannot be resumed safely.");let t;try{t=JSON.parse(await this.app.vault.adapter.read(la))}catch{throw new w("invalid_authority_adoption_snapshot","The fenced authority snapshot is corrupt.")}if(t.collection_id!==e.session.requested.collectionId||t.manifest_digest!==e.manifest_digest||t.source_revision!==e.source_revision||t.source_head!==e.source_head)throw new w("authority_adoption_snapshot_mismatch","The fenced authority snapshot does not match its durable checkpoint.");return t}async clearAdoptionCheckpoint(e){let t=this.adoptionMarker?.session.requested.collectionId;await this.app.vault.adapter.exists(la)&&await this.app.vault.adapter.remove(la),await this.app.vault.adapter.exists(ca)&&await this.app.vault.adapter.remove(ca),this.adoptionMarker=null;try{this.app.secretStorage.setSecret(this.adoptionSecretId(e),"")}catch{}t&&await this.adoptionBlobStore(t).prune(new Set).catch(()=>{})}};function Lm(r){let{credential:e,...t}=r;return t}function bF(r){return r instanceof G&&["authority_adoption_expired","authority_adoption_cancelled"].includes(r.code)}function vF(r){if(!Xe(r))return[];let e=r["x-obsidian"];return!Xe(e)||!Xe(e.bases)||!Array.isArray(e.bases.include)?[]:e.bases.include.filter(t=>typeof t=="string")}function pd(r){let e=r.getFiles?.();if(e)return e;let t=[],n=i=>{for(let s of i.children)s instanceof J.TFile?t.push(s):s instanceof J.TFolder&&n(s)};return n(r.getRoot()),t}function wF(r){if(!Xe(r)||r.version!==1||!["waiting_for_approval","uploading","fenced","activating","adopted"].includes(String(r.phase))||!Xe(r.session))return!1;let e=r.session;return typeof e.controlUrl=="string"&&typeof e.adoptionId=="string"&&ua.test(e.adoptionId)&&typeof e.verificationUri=="string"&&typeof e.expiresAt=="string"&&Xe(e.requested)&&typeof e.requested.collectionId=="string"&&ua.test(e.requested.collectionId)&&typeof e.requested.displayName=="string"&&typeof e.requested.sourceName=="string"&&e.requested.retainMirror===!0&&(r.selective_sync===void 0||_F(r.selective_sync))&&(r.manifest_digest===null||typeof r.manifest_digest=="string")&&(r.source_revision===null||typeof r.source_revision=="string")&&(r.source_head===null||Number.isSafeInteger(r.source_head))}function _F(r){if(!Xe(r)||!Array.isArray(r.file_classes)||!Array.isArray(r.excluded_folders))return!1;try{let e=Ir(r);return e.file_classes.length===r.file_classes.length&&e.excluded_folders.length===r.excluded_folders.length}catch{return!1}}function o$(r,e,t){return{version:1,syncUrl:r.syncUrl,controlUrl:r.controlUrl,collectionId:r.collectionId,replicaId:r.replicaId,mode:r.mode,name:r.name,enrollmentId:r.enrollmentId,accessTokenExpiresAt:r.accessTokenExpiresAt,selectiveSync:Ir(e),...t?{deviceId:t}:{}}}async function SF(r,e){if(!e?.startsWith("sha256:"))return!1;let t=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r)));return`sha256:${Array.from(t,i=>i.toString(16).padStart(2,"0")).join("")}`===e}var Qe=require("obsidian");qt();var ya="0.3.0",xF=new Set(["name","description","display_name_key","strict","path_pattern","filename_pattern","match","fields","extends"]),$F=new Set(["type","required","default","description","values","items","fields","min","max","min_length","max_length","pattern","unique","deprecated","generated","computed","target","validate_exists","tn_role","tn_completed_values"]);function pe(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Ae(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}function rn(r){return ea.digest(r)}function Ei(r){return Array.isArray(r)?`[${r.map(Ei).join(",")}]`:pe(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${Ei(r[e])}`).join(",")}}`:JSON.stringify(r)}function zm(r){if(Array.isArray(r))return r.map(zm);if(!pe(r))return r;let e={};for(let[t,n]of Object.entries(r)){let i=zm(n);i!=null&&(Array.isArray(i)&&i.length===0||pe(i)&&Object.keys(i).length===0||(e[t]=i))}return e}function Cs(r){return[...new Set(r)]}function EF(r){return pe(r.fields)?Object.values(r.fields).some(e=>pe(e)&&(typeof e.tn_role=="string"||Array.isArray(e.tn_completed_values))):!1}function Km(r,e,t){let n=pe(e)?e:{},i={},s={},o=[],a;switch(n.type){case"any":a={};break;case"string":case"integer":case"number":case"boolean":a={type:n.type};break;case"date":case"datetime":case"time":a={type:"string",format:n.type==="datetime"?"date-time":n.type};break;case"enum":a={enum:Array.isArray(n.values)?Ae(n.values):[]};break;case"link":a={type:"string"},i[r]={target_type:typeof n.target=="string"?n.target:r.endsWith("Parent")||r.endsWith("uid")?"task":"any",validate_exists:n.validate_exists===!0};break;case"list":{let c=Km(`${r}[]`,n.items,t);a={type:"array",items:c.schema},Object.assign(i,c.links),Object.assign(s,c.legacy),o.push(...c.unsupported);break}case"object":{let c={},l=[];for(let[u,d]of Object.entries(pe(n.fields)?n.fields:{})){let f=Km(`${r}.${u}`,d,t);c[u]=f.schema,Object.assign(i,f.links),Object.assign(s,f.legacy),o.push(...f.unsupported),pe(d)&&d.required===!0&&l.push(u)}t&&r==="blockedBy[]"&&l.push("uid"),a={type:"object",additionalProperties:Object.keys(c).length===0,properties:c,...l.length?{required:Cs(l)}:{}};break}default:a={},o.push(`${r}.type`);break}t&&r==="title"&&(a.minLength=1,a.description="Short summary of the task."),typeof n.description=="string"&&(a.description=n.description),typeof n.min=="number"&&(n.type==="string"?a.minLength=n.min:n.type==="list"?a.minItems=n.min:a.minimum=n.min),typeof n.max=="number"&&(n.type==="string"?a.maxLength=n.max:n.type==="list"?a.maxItems=n.max:a.maximum=n.max),typeof n.min_length=="number"&&(n.type==="list"?a.minItems=n.min_length:a.minLength=n.min_length),typeof n.max_length=="number"&&(n.type==="list"?a.maxItems=n.max_length:a.maxLength=n.max_length),typeof n.pattern=="string"&&(a.pattern=n.pattern),n.deprecated===!0&&(a.deprecated=!0),n.default!==void 0&&(a.default=Ae(n.default)),n.computed!==void 0&&o.push(`${r}.computed`);for(let[c,l]of Object.entries(n)){let u=t&&(c==="tn_role"||c==="tn_completed_values");(!$F.has(c)||(c==="tn_role"||c==="tn_completed_values")&&!u)&&(s[`${r}.${c}`]=Ae(l))}return{schema:a,links:i,legacy:s,unsupported:o}}function pa(r,e,t,n){let i=pe(r[e])?r[e]:{},s=pe(i.set)?i.set:{};s[t]=n,i.set=s,r[e]=i}function AF(r,e,t){if(t==="now")pa(r,"on_create",e,{now:!0});else if(t==="now_on_write")pa(r,"on_update",e,{now:!0});else if(t==="uuid")pa(r,"on_create",e,{uuid:!0});else if(t==="ulid")pa(r,"on_create",e,{ulid:!0});else if(pe(t)&&t.transform==="slugify"&&typeof t.from=="string")pa(r,"on_create",e,{slugify:t.from});else return!1;return!0}function kF(r){let e=r.match(/^(.*\/)?\{title\}\.md$/);return e?{runtime:"tasknotes",template:"{{title}}",folder:(e[1]??"").replace(/\/$/,""),generated_by:"tasknotes.filename.create"}:{runtime:"tasknotes",template:r,generated_by:"tasknotes.filename.create"}}function PF(r,e,t){if(t.kind==="mdbase.type"||t.schema!==void 0)throw new Error(`${r} already looks like a v0.3 type.`);if(typeof t.name!="string"||!pe(t.fields))throw new Error(`${r} is not a v0.2 type with a name and fields.`);let n=EF(t),i=t.name.trim().toLowerCase(),s={type:{const:i}},o=[],a={},c={},l=[],u={},d={},f=[],p=[],h={},m={},y={};for(let[E,k]of Object.entries(t.fields)){let x=pe(k)?k:{},T=Km(E,x,n);s[E]=T.schema,Object.assign(c,T.links),Object.assign(d,T.legacy),f.push(...T.unsupported),x.required===!0&&o.push(E),x.default!==void 0&&(a[E]=Ae(x.default)),x.unique===!0&&l.push({field:E,scope:"collection"}),x.generated!==void 0&&(AF(u,E,x.generated)?p.push(E):(d[`${E}.generated`]=Ae(x.generated),f.push(`${E}.generated`))),typeof x.tn_role=="string"&&(h[x.tn_role]=E),Array.isArray(x.tn_completed_values)&&(m.completed_values=Ae(x.tn_completed_values))}a.status!==void 0&&(m.default=Ae(a.status)),a.priority!==void 0&&(y.default=Ae(a.priority));let g=typeof t.display_name_key=="string"&&Object.prototype.hasOwnProperty.call(t.fields,t.display_name_key)?t.display_name_key:void 0,b={...g?{display:{name_field:g}}:{},read_defaults:a,links:c,unique:l};typeof t.path_pattern=="string"&&(b.path=n?kF(t.path_pattern):{pattern:t.path_pattern});let v={};for(let[E,k]of Object.entries(t))xF.has(E)||(v[E]=Ae(k));Object.keys(d).length&&(v.fields=d);let S=zm({kind:"mdbase.type",name:i,version:1,description:typeof t.description=="string"?t.description:void 0,match:pe(t.match)?Ae(t.match):void 0,schema:{dialect:"json-schema-2020-12",value:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",additionalProperties:t.strict!==!0,properties:s,...o.length?{required:Cs(o)}:{}}},collection:b,lifecycle:u,...n?{"x-tasknotes":{contract:"tasknotes.task",version:1,field_roles:h,status:m,priority:y,archive:{tags_field:h.tags??"tags",archived_tag:"archived"}}}:{},...Object.keys(v).length?{"x-legacy-v0.2":v}:{}}),_=[];t.extends!==void 0&&f.push("extends");for(let E of Cs(f).sort())_.push({path:r,code:"migration_lossy",message:`${E} cannot be expressed as canonical v0.3 write behavior and was retained as legacy metadata where possible.`,severity:"lossy"});return n&&_.push({path:r,code:"path_policy_runtime_owned",message:"TaskNotes filename behavior is recorded as TaskNotes runtime metadata.",severity:"warning"}),t.strict!==!0&&_.push({path:r,code:"additional_properties_true",message:"The migrated schema allows additional properties because the source type was not strict.",severity:"warning"}),typeof t.display_name_key=="string"&&!g&&_.push({path:r,code:"display_field_missing",message:`The display field '${t.display_name_key}' is not declared, so collection.display was omitted.`,severity:"warning"}),{target:S,summary:{path:r,name:i,fieldsConverted:Object.keys(t.fields).length,requiredFields:Cs(o),defaultsMoved:Object.keys(a),generatedFieldsMoved:Cs(p),linksMoved:Object.keys(c),taskNotes:n},diagnostics:_}}var MF=["default_strict","write_nulls","write_empty_lists","write_defaults","rename_update_refs","cache_folder","migrations_folder","extensions"];function CF(r,e){let t=Ae(r);t.spec_version=ya;let n=pe(t.settings)?t.settings:{};if(t.settings=n,!Array.isArray(n.record_extensions)){let a=Array.isArray(n.extensions)?n.extensions.map(String).map(c=>c.replace(/^\./,"")):[];n.record_extensions=Cs(["md",...a])}Array.isArray(n.explicit_type_keys)||(n.explicit_type_keys=["type","types"]),n.validation===void 0&&typeof n.default_validation=="string"&&(n.validation=n.default_validation),n.validation===void 0&&typeof t.default_validation=="string"&&(n.validation=t.default_validation),n.validation??="warn",n.id_field===void 0&&(n.id_field=typeof t.id_field=="string"?t.id_field:"id");let i=typeof n.types_folder=="string"?(0,Qe.normalizePath)(n.types_folder):"_types",s=(Array.isArray(n.exclude)?n.exclude:[]).map(String).flatMap(a=>TF(a,i)??[]);for(let a of s)RF(a)||e.push({path:"mdbase.yaml",code:"non_portable_exclude",message:`Exclude pattern "${a}" is not a portable v0.3 glob; review it.`,severity:"warning"});n.include_subfolders===!1&&s.push("*/**"),s.length>0?n.exclude=s:delete n.exclude;let o={};for(let a of MF)n[a]!==void 0&&(o[a]=n[a]),delete n[a];if(Object.keys(o).length>0){let a=pe(t["x-legacy-v0.2"])?t["x-legacy-v0.2"]:{};t["x-legacy-v0.2"]={...a,settings:o}}return delete n.include_subfolders,delete n.default_validation,delete t.default_validation,delete t.id_field,t}function TF(r,e){return/[/*?[]/.test(r)?r.includes("/")?r:`**/${r}`:r.startsWith(".")||r==="node_modules"||r===e?null:`${r}/**`}function RF(r){return r!==""&&!r.startsWith("/")&&!/[{}\\]/.test(r)&&r.split("/").every(e=>e==="**"||!e.includes("**"))}function f$(r,e){let t=pe(r.settings)?r.settings:{};return{spec_version:e,name:typeof r.name=="string"?r.name:void 0,description:typeof r.description=="string"?r.description:void 0,settings:{types_folder:typeof t.types_folder=="string"?t.types_folder:"_types",explicit_type_keys:Array.isArray(t.explicit_type_keys)?t.explicit_type_keys.filter(n=>typeof n=="string"):["type","types"],default_strict:t.default_strict===!0,include_subfolders:t.include_subfolders!==!1,exclude:Array.isArray(t.exclude)?t.exclude.filter(n=>typeof n=="string"):["_types",".obsidian",".git",".mdbase"]}}}function IF(r,e){let t={};for(let[n,i]of Object.entries(pe(e.fields)?e.fields:{}))pe(i)&&(t[n]=Ae(i));return{name:typeof e.name=="string"?e.name:r.split("/").pop()?.replace(/\.md$/,"")??"type",fields:t,match:pe(e.match)?Ae(e.match):void 0,filePath:r,specProfile:"v0.2"}}function OF(r,e){let t=pe(e.schema)?e.schema:{},n=pe(t.value)?t.value:{};return{name:typeof e.name=="string"?e.name:r.split("/").pop()?.replace(/\.md$/,"")??"type",fields:gn(n),match:pe(e.match)?Ae(e.match):void 0,collection:pe(e.collection)?Ae(e.collection):void 0,schema:Ae(n),filePath:r,specProfile:"v0.3"}}function DF(r,e,t){let n=Ae(r);for(let i of e){let s=t.get(i);if(s)for(let[o,a]of Object.entries(s.fields))!(o in n)&&a.default!==void 0&&(n[o]=Ae(a.default))}return n}function NF(r,e,t){let n=Ae(r);for(let i of e){let s=t.get(i);if(s)for(let[o,a]of Object.entries(s.collection?.read_defaults??{}))o in n||(n[o]=Ae(a))}return n}async function LF(r,e){let t=(0,Qe.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 Qe.TFolder)){if(s)throw new Error(`A file blocks folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}async function md(r,e,t){let n=(0,Qe.normalizePath)(e),i=n.lastIndexOf("/");if(i>=0&&await LF(r,n.slice(0,i)),n.startsWith(".mdbase/")){await r.adapter.write(n,t);return}let s=r.getAbstractFileByPath(n);if(s instanceof Qe.TFolder)throw new Error(`A folder blocks file ${n}.`);s instanceof Qe.TFile?await r.modify(s,t):await r.create(n,t)}async function ma(r,e){let t=(0,Qe.normalizePath)(e),n=r.getAbstractFileByPath(t);if(n instanceof Qe.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 p$(r){let e=await ma(r,"mdbase.yaml"),t=(0,Qe.parseYaml)(e);if(!pe(t))throw new Error("mdbase.yaml must contain a YAML mapping.");let n=typeof t.spec_version=="string"?t.spec_version:"";if(!/^0\.2(?:\.\d+)?$/.test(n))throw new Error(n===ya?"This collection is already mdbase v0.3.":`Expected an mdbase v0.2.x collection, found ${JSON.stringify(n)}.`);let i=pe(t.settings)?t.settings:{},s=typeof i.types_folder=="string"?(0,Qe.normalizePath)(i.types_folder):"_types",o=`${s}/`,a=[],c=[],l=[],u=CF(t,l),d=`${(0,Qe.stringifyYaml)(u).trimEnd()} +`;a.push({path:"mdbase.yaml",sourceDigest:rn(e),targetDigest:rn(d),source:e,target:d});let f=new Map,p=new Map;for(let S of r.getMarkdownFiles().filter(_=>_.path.startsWith(o)).sort((_,E)=>_.path.localeCompare(E.path))){let _=await r.cachedRead(S),E=Ce(_);if(!E.hasFrontmatter||E.error)throw new Error(`Cannot migrate ${S.path}: ${E.error??"frontmatter is missing"}.`);let k=PF(S.path,n,E.frontmatter),x=IF(S.path,E.frontmatter),T=OF(S.path,k.target);f.set(x.name,x),p.set(T.name,T);let $=`${mt(k.target,E.body)} +`;a.push({path:S.path,sourceDigest:rn(_),targetDigest:rn($),source:_,target:$}),c.push(k.summary),l.push(...k.diagnostics)}if(!c.length)throw new Error(`No v0.2 type files were found in ${s}.`);let h=0,m=0,y=f$(t,n),g=f$(u,ya),b=r.getMarkdownFiles().filter(S=>!S.path.startsWith(o)).filter(S=>!S.path.startsWith(".mdbase/")).sort((S,_)=>S.path.localeCompare(_.path));for(let[S,_]of b.entries()){let E=Ce(await r.cachedRead(_));if(E.error){m+=1;continue}let k=Ke(_.path,E.frontmatter,y,f),x=Ke(_.path,E.frontmatter,g,p),T=DF(E.frontmatter,k,f),$=NF(E.frontmatter,x,p);(Ei(k.slice().sort())!==Ei(x.slice().sort())||Ei(T)!==Ei($))&&l.push({path:_.path,code:"effective_read_changed",message:"The proposed v0.3 types would change this record's resolved types or effective default values.",severity:"lossy"}),h+=1,S>0&&S%250===0&&await new Promise(q=>window.setTimeout(q,0))}let v=rn(Ei({sourceVersion:n,operations:a.map(({path:S,sourceDigest:_,targetDigest:E})=>({path:S,sourceDigest:_,targetDigest:E})),diagnostics:l}));return{planVersion:1,analysisId:v,sourceVersion:n,targetVersion:ya,createdAt:new Date().toISOString(),backupLocation:`.mdbase/migrations/v02-to-v03-${v.slice(0,12)}`,operations:a,typeSummaries:c,diagnostics:l,applicable:!l.some(S=>S.severity==="lossy"),recordFilesRewritten:0,recordsVerified:h,recordsSkipped:m}}async function ha(r,e,t){await md(r,e,`${JSON.stringify(t,null,2)} +`)}async function h$(r,e,t={}){if(e.planVersion!==1||e.targetVersion!==ya)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 ma(r,s.path);if(rn(o)!==s.sourceDigest)throw new Error(`${s.path} changed after migration analysis. Run the review again.`)}let n=`${e.backupLocation}/manifest.json`,i={manifest_version:1,analysis_id:e.analysisId,source_version:e.sourceVersion,target_version:e.targetVersion,status:"prepared",created_at:new Date().toISOString(),written:[],files:e.operations.map(s=>({path:s.path,source_digest:s.sourceDigest,target_digest:s.targetDigest,backup_path:`${e.backupLocation}/files/${s.path}`}))};for(let s of e.operations)await md(r,`${e.backupLocation}/files/${s.path}`,s.source);await ha(r,n,i),i.status="applying",await ha(r,n,i);try{for(let s of e.operations){let o=await ma(r,s.path);if(rn(o)!==s.sourceDigest)throw new Error(`${s.path} changed during migration.`);i.written.push(s.path),await ha(r,n,i),await md(r,s.path,s.target);let a=await ma(r,s.path);if(rn(a)!==s.targetDigest)throw new Error(`${s.path} did not verify after write.`)}return i.status="applied",i.completed_at=new Date().toISOString(),await ha(r,n,i),{applied:!0,restored:!1,manifestPath:n,written:[...i.written]}}catch(s){let o=[];for(let a of[...i.written].reverse()){let c=e.operations.find(l=>l.path===a);if(!c){o.push(a);continue}try{await md(r,a,c.source),rn(await ma(r,a))!==c.sourceDigest&&o.push(a)}catch{o.push(a)}}i.status=o.length?"recovery_required":"rolled_back",i.error=s instanceof Error?s.message:String(s),i.manual_recovery_paths=o.length?o:void 0,i.completed_at=new Date().toISOString();try{await ha(r,n,i)}catch{}return{applied:!1,restored:o.length===0,manifestPath:n,written:[...i.written],error:i.error}}}var yd=require("obsidian");qt();function we(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Ct(r){return JSON.parse(JSON.stringify(r))}var FF=new Set(["file","formula","this"]);function jF(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(FF.has(e.toLowerCase()))throw new Error(`Type name '${e}' is reserved.`);return e}function Wm(){return{specProfile:"v0.3",originalFrontmatter:{},name:"",description:"",extendsType:"",displayNameKey:"",strictMode:!1,pathPattern:"",filenamePattern:"",matchPathGlob:"",matchFieldsPresent:"",matchWhere:"",fields:[{name:"title",definition:{type:"string",required:!0}}],implementations:[],body:`# Type -Describe the type and intended usage.`,extraFrontmatter:{}}}function FF(r){return we(r)?Object.entries(r).filter(e=>we(e[1])).map(([e,t])=>({name:e,definition:Mt(t)})):[]}function jF(r){return Array.isArray(r)?r.flatMap(e=>{if(!we(e)||typeof e.contract!="string"||typeof e.version!="string")return[];let t=we(e.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,i])=>typeof i=="string")):{},n=we(e.binding)?Mt(e.binding):void 0;return[{contract:e.contract,version:e.version,fields:t,...n?{binding:n}:{}}]}):[]}function qF(r){return Object.fromEntries(r.map(e=>[e.name,e.definition]))}function BF(r,e){let t=e.split("."),n=r,i;for(let[s,o]of t.entries()){let a=o.match(/^([^[]+)((?:\[\])*)$/);if(!a||(i=n[a[1]],!i))return null;let c=a[2].length/2;for(let l=0;l{if(e.selectors.add(i),n.type==="link"&&e.links.set(i,{target_type:typeof n.target=="string"&&n.target.trim()?n.target.trim():"any",validate_exists:n.validate_exists===!0}),n.type==="list"&&n.items&&t(n.items,`${i}[]`),n.type==="object"&&n.fields)for(let[s,o]of Object.entries(n.fields))t(o,`${i}.${s}`)};for(let[n,i]of Object.entries(r))t(i,n);return e}function gd(r,e,t){let n=r.kind==="mdbase.type",i=n&&we(r.schema)?r.schema:{},s=we(i.value)?i.value:{},o=typeof i.ref=="string"?i.ref:"",a=n&&we(r.collection)?r.collection:{},c=we(a.display)?a.display:{},l=we(a.path)?a.path:{},u=FF(n?gn(s):r.fields);n&&UF(u,a.links);let d=we(r.match)?r.match:{},f=n?s.additionalProperties===!1:r.strict,p=new Set(["name","description","extends","display_name_key","strict","path_pattern","filename_pattern","match","fields"]),m={};for(let[y,g]of Object.entries(r))p.has(y)||(m[y]=Mt(g));let h="";if(d.where!==void 0)try{h=(0,yd.stringifyYaml)(d.where).trim()}catch{h=""}return{specProfile:n?"v0.3":"v0.2",originalFrontmatter:Mt(r),name:typeof r.name=="string"&&r.name.trim()?r.name:t,description:typeof r.description=="string"?r.description:"",extendsType:typeof r.extends=="string"?r.extends:"",displayNameKey:n?typeof c.name_field=="string"?c.name_field:"":typeof r.display_name_key=="string"?r.display_name_key:"",strictMode:f==="warn"?"warn":f===!0,pathPattern:n?typeof l.pattern=="string"?l.pattern:"":typeof r.path_pattern=="string"?r.path_pattern:"",filenamePattern:n?"":typeof r.filename_pattern=="string"?r.filename_pattern:"",matchPathGlob:typeof d.path_glob=="string"?d.path_glob:"",matchFieldsPresent:Array.isArray(d.fields_present)?d.fields_present.map(String).join(", "):"",matchWhere:h,fields:u.length||o?u:Hm().fields,implementations:jF(r.implements),body:e.trim()||`# ${t} +Describe the type and intended usage.`,extraFrontmatter:{}}}function qF(r){return we(r)?Object.entries(r).filter(e=>we(e[1])).map(([e,t])=>({name:e,definition:Ct(t)})):[]}function BF(r){return Array.isArray(r)?r.flatMap(e=>{if(!we(e)||typeof e.contract!="string"||typeof e.version!="string")return[];let t=we(e.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,i])=>typeof i=="string")):{},n=we(e.binding)?Ct(e.binding):void 0;return[{contract:e.contract,version:e.version,fields:t,...n?{binding:n}:{}}]}):[]}function UF(r){return Object.fromEntries(r.map(e=>[e.name,e.definition]))}function VF(r,e){let t=e.split("."),n=r,i;for(let[s,o]of t.entries()){let a=o.match(/^([^[]+)((?:\[\])*)$/);if(!a||(i=n[a[1]],!i))return null;let c=a[2].length/2;for(let l=0;l{if(e.selectors.add(i),n.type==="link"&&e.links.set(i,{target_type:typeof n.target=="string"&&n.target.trim()?n.target.trim():"any",validate_exists:n.validate_exists===!0}),n.type==="list"&&n.items&&t(n.items,`${i}[]`),n.type==="object"&&n.fields)for(let[s,o]of Object.entries(n.fields))t(o,`${i}.${s}`)};for(let[n,i]of Object.entries(r))t(i,n);return e}function gd(r,e,t){let n=r.kind==="mdbase.type",i=n&&we(r.schema)?r.schema:{},s=we(i.value)?i.value:{},o=typeof i.ref=="string"?i.ref:"",a=n&&we(r.collection)?r.collection:{},c=we(a.display)?a.display:{},l=we(a.path)?a.path:{},u=qF(n?gn(s):r.fields);n&&HF(u,a.links);let d=we(r.match)?r.match:{},f=n?s.additionalProperties===!1:r.strict,p=new Set(["name","description","extends","display_name_key","strict","path_pattern","filename_pattern","match","fields"]),h={};for(let[y,g]of Object.entries(r))p.has(y)||(h[y]=Ct(g));let m="";if(d.where!==void 0)try{m=(0,yd.stringifyYaml)(d.where).trim()}catch{m=""}return{specProfile:n?"v0.3":"v0.2",originalFrontmatter:Ct(r),name:typeof r.name=="string"&&r.name.trim()?r.name:t,description:typeof r.description=="string"?r.description:"",extendsType:typeof r.extends=="string"?r.extends:"",displayNameKey:n?typeof c.name_field=="string"?c.name_field:"":typeof r.display_name_key=="string"?r.display_name_key:"",strictMode:f==="warn"?"warn":f===!0,pathPattern:n?typeof l.pattern=="string"?l.pattern:"":typeof r.path_pattern=="string"?r.path_pattern:"",filenamePattern:n?"":typeof r.filename_pattern=="string"?r.filename_pattern:"",matchPathGlob:typeof d.path_glob=="string"?d.path_glob:"",matchFieldsPresent:Array.isArray(d.fields_present)?d.fields_present.map(String).join(", "):"",matchWhere:m,fields:u.length||o?u:Wm().fields,implementations:BF(r.implements),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 Fn(r){if(r.specProfile!=="v0.3")throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection before editing.");if(r.readOnlyReason)throw new Error(r.readOnlyReason);let e=r.originalFrontmatter?Mt(r.originalFrontmatter):{},t=we(e.schema)?e.schema:{},n=we(t.value)?t.value:{},i=Object.create(null);for(let h of r.fields){let y=h.name.trim();if(!y)throw new Error("Every field needs a name.");if(Object.prototype.hasOwnProperty.call(i,y))throw new Error(`Duplicate field name: ${y}`);i[y]=Mt(h.definition)}let s=LF(r.name),o={...e,kind:"mdbase.type",name:s,version:typeof e.version=="number"?e.version:1,schema:{...t,dialect:"json-schema-2020-12",value:es(i,n,r.strictMode===!0)}};delete o.schema.ref,r.description.trim()?o.description=r.description.trim():delete o.description;let a=we(o.match)?Mt(o.match):{};r.matchPathGlob.trim()?a.path_glob=r.matchPathGlob.trim():delete a.path_glob;let c=r.matchFieldsPresent.split(",").map(h=>h.trim()).filter(Boolean);if(c.length?a.fields_present=c:delete a.fields_present,r.matchWhere.trim()){let h=(0,yd.parseYaml)(r.matchWhere);if(!we(h))throw new Error("Match where must be a YAML mapping.");a.where=h}else delete a.where;Object.keys(a).length?o.match=a:delete o.match;let l=we(o.collection)?Mt(o.collection):{},u=we(l.display)?Mt(l.display):{};if(r.displayNameKey.trim()?u.name_field=r.displayNameKey.trim():delete u.name_field,Object.keys(u).length?l.display=u:delete l.display,r.pathPattern.trim()){let h=we(l.path)?l.path:{};l.path={...h,pattern:r.pathPattern.trim()}}else if(we(l.path)&&typeof l.path.pattern=="string"){let h={...l.path};delete h.pattern,Object.keys(h).length?l.path=h:delete l.path}let d=we(l.links)?Mt(l.links):{},f=Mt(d),p=ux(i),m=ux(gn(n));for(let h of new Set([...m.selectors,...p.selectors]))delete f[h];for(let[h,y]of p.links)f[h]={...we(d[h])?d[h]:{},target_type:y.target_type,validate_exists:y.validate_exists};Object.keys(f).length?l.links=f:delete l.links,Object.keys(l).length?o.collection=l:delete o.collection,r.implementations.length?o.implements=r.implementations.map(h=>({contract:h.contract,version:h.version,fields:Mt(h.fields),...h.binding&&Object.keys(h.binding).length?{binding:Mt(h.binding)}:{}})):delete o.implements;for(let h of["fields","strict","extends","display_name_key","path_pattern","filename_pattern"])delete o[h];return o}qt();function nn(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function fx(r){return JSON.parse(JSON.stringify(r))}function Ms(r){return`${r.id}@${r.version}`}function ya(r){let e=nn(r.schema)?r.schema:{},t=nn(e.properties)?e.properties:{},n=new Set(Array.isArray(e.required)?e.required.map(String):[]);return Object.entries(t).filter(i=>nn(i[1])).map(([i,s])=>({name:i,reference:i,required:n.has(i),schema:s,...typeof s.description=="string"?{description:s.description}:{}}))}function ga(r){let e=Object.fromEntries(r.fields.map(s=>[s.name,s.definition])),t=es(e),n=nn(t.properties)?t.properties:{},i=new Set(Array.isArray(t.required)?t.required.map(String):[]);return Object.entries(n).filter(s=>nn(s[1])).map(([s,o])=>({label:s,reference:s,required:i.has(s),type:jn(o),schema:o}))}function Ts(r,e){return r.fields[e.reference]??r.fields[e.name]??""}function ba(r,e){if(!e)return r.required?{level:"error",label:"Required",message:`Map required contract field ${r.reference}.`}:{level:"unmapped",label:"Not exposed",message:"This optional contract field is not exposed."};let t=jn(r.schema);return gx(t,e.type)?r.required&&!e.required?{level:"warning",label:"Review",message:`${e.reference} is optional in this type, so the contract value may be absent.`}:{level:"valid",label:"Ready",message:"This field satisfies the contract shape."}:{level:"error",label:"Incompatible",message:`${e.reference} is ${e.type}, but the contract expects ${t}.`}}function px(r,e){if(r.implementations.some(i=>i.contract===e.id&&i.version===e.version))throw new Error(`${e.id} ${e.version} is already implemented.`);let t=ga(r),n=Object.fromEntries(ya(e).flatMap(i=>{let s=t.find(o=>o.reference.toLowerCase()===i.reference.toLowerCase()&&gx(jn(i.schema),o.type));return s?[[i.reference,s.reference]]:[]}));r.implementations.push({contract:e.id,version:e.version,fields:n})}function hx(r,e,t){r.implementations=r.implementations.filter(n=>n.contract!==e||n.version!==t)}function mx(r,e,t){t?r.fields[e]=t:delete r.fields[e]}function zm(r,e){r.binding=Object.keys(e).length?fx(e):void 0}function va(r){if(!r)return"";if(Array.isArray(r.enum)&&r.enum.length)return fx(r.enum[0]);let e=jn(r);if(e==="object"){let t={},n=nn(r.properties)?r.properties:{},i=new Set(Array.isArray(r.required)?r.required.map(String):[]);for(let[s,o]of Object.entries(n))i.has(s)&&nn(o)&&(t[s]=va(o));return t}return e==="array"?[]:e==="boolean"?!1:e==="number"||e==="integer"?0:""}function jn(r){return"const"in r?typeof r.const:Array.isArray(r.type)?String(r.type.find(e=>e!=="null")??r.type[0]??"string"):typeof r.type=="string"?r.type:Array.isArray(r.enum)?"string":nn(r.properties)||nn(r.additionalProperties)?"object":"any"}function yx(r){let e=jn(r);return e==="array"?"List":e==="boolean"?"Boolean":e==="integer"?"Integer":e==="number"?"Number":e==="object"?"Object":e==="any"?"Any value":"Text"}function gx(r,e){return r==="any"||e==="any"||r===e?!0:r==="number"&&e==="integer"}function Km(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function VF(r){return JSON.parse(JSON.stringify(r))}function Jm(r){let e=2166136261,t=2654435769;for(let n=0;n>>0).toString(36)}-${(t>>>0).toString(36)}`}function bx(r){let e=VF(r);return delete e.sourceRevision,e}function bd(r,e){return r===null||e===null?r===e:JSON.stringify(bx(r))===JSON.stringify(bx(e))}function vx(r){return new Map(r.fields.map(e=>[e.name,e]))}function Wm(r){return typeof r.type=="string"?r.type:"any"}function Gm(r,e,t,n){let i=Wm(r);if(i==="enum"&&(!Array.isArray(r.values)||r.values.length===0)&&t.push({code:"enum_without_values",severity:"warning",path:e,message:"Add at least one allowed value, or use String for an unrestricted value."}),i==="enum"&&Array.isArray(r.values)){let s=r.values.map(o=>JSON.stringify(o));new Set(s).size!==s.length&&t.push({code:"enum_duplicate_values",severity:"error",path:e,message:"Allowed values must be unique."}),r.default!==void 0&&!s.includes(JSON.stringify(r.default))&&t.push({code:"default_not_allowed",severity:"error",path:e,message:"The default is not one of the allowed values."})}for(let[s,o,a]of[["min","max","Minimum"],["min_length","max_length","Minimum length"]]){let c=r[s],l=r[o];typeof c=="number"&&typeof l=="number"&&c>l&&t.push({code:"constraint_range_inverted",severity:"error",path:e,message:`${a} is greater than the maximum.`})}if(typeof r.pattern=="string")try{new RegExp(r.pattern)}catch(s){t.push({code:"invalid_pattern",severity:"error",path:e,message:`The pattern is not a valid regular expression: ${s instanceof Error?s.message:String(s)}`})}if(i==="link"){let s=typeof r.target=="string"?r.target.trim():"";s&&s!=="any"&&n.size&&!n.has(s)&&t.push({code:"unknown_link_target",severity:"error",path:e,message:`The target type '${s}' is not installed in this collection.`})}if(i==="list"&&(Km(r.items)?Gm(r.items,`${e}[]`,t,n):t.push({code:"list_items_missing",severity:"error",path:e,message:"Choose the shape of each list item."})),i==="object"){if(!Km(r.fields)){t.push({code:"object_fields_missing",severity:"error",path:e,message:"Add an object field or change this field's type."});return}let s=new Set;for(let[o,a]of Object.entries(r.fields)){let c=`${e}.${o||"unnamed"}`;o.trim()?s.has(o)&&t.push({code:"duplicate_field_name",severity:"error",path:c,message:`The nested field '${o}' is declared more than once.`}):t.push({code:"field_name_required",severity:"error",path:c,message:"Every nested field needs a name."}),s.add(o),Km(a)&&Gm(a,c,t,n)}}}function wa(r,e={}){let t=[],n=new Set(e.knownTypes??[]);try{Fn(r)}catch(a){t.push({code:"invalid_type_document",severity:"error",path:"type",message:a instanceof Error?a.message:String(a)})}let i=new Set;for(let a of r.fields){let c=a.name.trim(),l=`fields.${c||"unnamed"}`;c?i.has(c)&&t.push({code:"duplicate_field_name",severity:"error",path:l,message:`The field '${c}' is declared more than once.`}):t.push({code:"field_name_required",severity:"error",path:l,message:"Every field needs a name."}),i.add(c),Gm(a.definition,l,t,n)}r.displayNameKey.trim()&&!i.has(r.displayNameKey.trim())&&t.push({code:"display_field_missing",severity:"error",path:"identity.displayNameKey",message:`The display field '${r.displayNameKey.trim()}' is not declared.`});let s=new Map([...e.contracts??[]].map(a=>[Ms(a),a])),o=ga(r);for(let a of r.implementations){let c=`${a.contract}@${a.version}`,l=s.get(c);if(!l){t.push({code:"contract_unavailable",severity:"error",path:`applications.${c}`,message:"This exact application contract is not installed."});continue}for(let u of ya(l)){let d=Ts(a,u),f=o.find(m=>m.reference===d),p=ba(u,f);p.level!=="valid"&&t.push({code:p.level==="error"?"invalid_contract_mapping":"review_contract_mapping",severity:p.level==="error"?"error":"warning",path:`applications.${c}.${u.reference}`,message:p.message})}}return t.filter((a,c,l)=>l.findIndex(u=>u.code===a.code&&u.path===a.path&&u.message===a.message)===c)}function _a(r,e){if(!r)return[{code:"create_type",risk:"safe",summary:`Create the type '${e.name||"Untitled type"}'.`}];let t=[];r.name!==e.name&&t.push({code:"rename_type",risk:"high",summary:`Rename the type from '${r.name}' to '${e.name}'. Existing type references may need review.`}),(r.description!==e.description||r.displayNameKey!==e.displayNameKey)&&t.push({code:"identity",risk:"safe",summary:"Update the type's identity and display metadata."}),(r.matchPathGlob!==e.matchPathGlob||r.matchFieldsPresent!==e.matchFieldsPresent||r.matchWhere!==e.matchWhere)&&t.push({code:"membership",risk:"high",summary:"Change which records belong to this type."}),r.pathPattern!==e.pathPattern&&t.push({code:"placement",risk:"review",summary:"Change the suggested path for new records."}),r.strictMode!==e.strictMode&&t.push({code:"strictness",risk:e.strictMode===!0?"high":"review",summary:e.strictMode===!0?"Reject fields that are not declared by this type.":"Allow fields that are not declared by this type."});let n=vx(r),i=vx(e),s=[...i.keys()].filter(l=>!n.has(l)),o=[...n.keys()].filter(l=>!i.has(l));s.length&&t.push({code:"add_fields",risk:s.some(l=>i.get(l)?.definition.required===!0)?"high":"safe",summary:`Add ${s.length===1?"field":"fields"}: ${s.join(", ")}.`}),o.length&&t.push({code:"remove_fields",risk:"high",summary:`Remove ${o.length===1?"field":"fields"}: ${o.join(", ")}.`});for(let[l,u]of i){let d=n.get(l);if(!d)continue;let f=Wm(d.definition),p=Wm(u.definition);f!==p&&t.push({code:"change_field_type",risk:"high",summary:`Change '${l}' from ${f} to ${p}.`}),d.definition.required!==!0&&u.definition.required===!0&&t.push({code:"require_field",risk:"high",summary:`Make '${l}' required. Existing records may become invalid.`}),f===p&&JSON.stringify(d.definition)!==JSON.stringify(u.definition)&&d.definition.required===u.definition.required&&t.push({code:"field_rules",risk:"review",summary:`Update validation or documentation for '${l}'.`})}let a=[...n.keys()].filter(l=>i.has(l)),c=[...i.keys()].filter(l=>n.has(l));return a.join("\0")!==c.join("\0")&&t.push({code:"reorder_fields",risk:"safe",summary:"Reorder fields."}),JSON.stringify(r.implementations)!==JSON.stringify(e.implementations)&&t.push({code:"application_compatibility",risk:"review",summary:"Update application contract mappings or settings."}),!t.length&&!bd(r,e)&&t.push({code:"type_document",risk:"review",summary:"Update advanced type metadata or documentation."}),t}var Ds=require("obsidian");var Sa="mdbase-frontmatter",wx=` +Type definition for ${t}.`,extraFrontmatter:h,...o?{readOnlyReason:`This type uses schema.ref (${o}). Edit the referenced JSON Schema file directly.`}:{}}}function Fn(r){if(r.specProfile!=="v0.3")throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection before editing.");if(r.readOnlyReason)throw new Error(r.readOnlyReason);let e=r.originalFrontmatter?Ct(r.originalFrontmatter):{},t=we(e.schema)?e.schema:{},n=we(t.value)?t.value:{},i=Object.create(null);for(let m of r.fields){let y=m.name.trim();if(!y)throw new Error("Every field needs a name.");if(Object.prototype.hasOwnProperty.call(i,y))throw new Error(`Duplicate field name: ${y}`);i[y]=Ct(m.definition)}let s=jF(r.name),o={...e,kind:"mdbase.type",name:s,version:typeof e.version=="number"?e.version:1,schema:{...t,dialect:"json-schema-2020-12",value:es(i,n,r.strictMode===!0)}};delete o.schema.ref,r.description.trim()?o.description=r.description.trim():delete o.description;let a=we(o.match)?Ct(o.match):{};r.matchPathGlob.trim()?a.path_glob=r.matchPathGlob.trim():delete a.path_glob;let c=r.matchFieldsPresent.split(",").map(m=>m.trim()).filter(Boolean);if(c.length?a.fields_present=c:delete a.fields_present,r.matchWhere.trim()){let m=(0,yd.parseYaml)(r.matchWhere);if(!we(m))throw new Error("Match where must be a YAML mapping.");a.where=m}else delete a.where;Object.keys(a).length?o.match=a:delete o.match;let l=we(o.collection)?Ct(o.collection):{},u=we(l.display)?Ct(l.display):{};if(r.displayNameKey.trim()?u.name_field=r.displayNameKey.trim():delete u.name_field,Object.keys(u).length?l.display=u:delete l.display,r.pathPattern.trim()){let m=we(l.path)?l.path:{};l.path={...m,pattern:r.pathPattern.trim()}}else if(we(l.path)&&typeof l.path.pattern=="string"){let m={...l.path};delete m.pattern,Object.keys(m).length?l.path=m:delete l.path}let d=we(l.links)?Ct(l.links):{},f=Ct(d),p=m$(i),h=m$(gn(n));for(let m of new Set([...h.selectors,...p.selectors]))delete f[m];for(let[m,y]of p.links)f[m]={...we(d[m])?d[m]:{},target_type:y.target_type,validate_exists:y.validate_exists};Object.keys(f).length?l.links=f:delete l.links,Object.keys(l).length?o.collection=l:delete o.collection,r.implementations.length?o.implements=r.implementations.map(m=>({contract:m.contract,version:m.version,fields:Ct(m.fields),...m.binding&&Object.keys(m.binding).length?{binding:Ct(m.binding)}:{}})):delete o.implements;for(let m of["fields","strict","extends","display_name_key","path_pattern","filename_pattern"])delete o[m];return o}qt();function nn(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function y$(r){return JSON.parse(JSON.stringify(r))}function Ts(r){return`${r.id}@${r.version}`}function ga(r){let e=nn(r.schema)?r.schema:{},t=nn(e.properties)?e.properties:{},n=new Set(Array.isArray(e.required)?e.required.map(String):[]);return Object.entries(t).filter(i=>nn(i[1])).map(([i,s])=>({name:i,reference:i,required:n.has(i),schema:s,...typeof s.description=="string"?{description:s.description}:{}}))}function ba(r){let e=Object.fromEntries(r.fields.map(s=>[s.name,s.definition])),t=es(e),n=nn(t.properties)?t.properties:{},i=new Set(Array.isArray(t.required)?t.required.map(String):[]);return Object.entries(n).filter(s=>nn(s[1])).map(([s,o])=>({label:s,reference:s,required:i.has(s),type:jn(o),schema:o}))}function Rs(r,e){return r.fields[e.reference]??r.fields[e.name]??""}function va(r,e){if(!e)return r.required?{level:"error",label:"Required",message:`Map required contract field ${r.reference}.`}:{level:"unmapped",label:"Not exposed",message:"This optional contract field is not exposed."};let t=jn(r.schema);return _$(t,e.type)?r.required&&!e.required?{level:"warning",label:"Review",message:`${e.reference} is optional in this type, so the contract value may be absent.`}:{level:"valid",label:"Ready",message:"This field satisfies the contract shape."}:{level:"error",label:"Incompatible",message:`${e.reference} is ${e.type}, but the contract expects ${t}.`}}function g$(r,e){if(r.implementations.some(i=>i.contract===e.id&&i.version===e.version))throw new Error(`${e.id} ${e.version} is already implemented.`);let t=ba(r),n=Object.fromEntries(ga(e).flatMap(i=>{let s=t.find(o=>o.reference.toLowerCase()===i.reference.toLowerCase()&&_$(jn(i.schema),o.type));return s?[[i.reference,s.reference]]:[]}));r.implementations.push({contract:e.id,version:e.version,fields:n})}function b$(r,e,t){r.implementations=r.implementations.filter(n=>n.contract!==e||n.version!==t)}function v$(r,e,t){t?r.fields[e]=t:delete r.fields[e]}function Gm(r,e){r.binding=Object.keys(e).length?y$(e):void 0}function wa(r){if(!r)return"";if(Array.isArray(r.enum)&&r.enum.length)return y$(r.enum[0]);let e=jn(r);if(e==="object"){let t={},n=nn(r.properties)?r.properties:{},i=new Set(Array.isArray(r.required)?r.required.map(String):[]);for(let[s,o]of Object.entries(n))i.has(s)&&nn(o)&&(t[s]=wa(o));return t}return e==="array"?[]:e==="boolean"?!1:e==="number"||e==="integer"?0:""}function jn(r){return"const"in r?typeof r.const:Array.isArray(r.type)?String(r.type.find(e=>e!=="null")??r.type[0]??"string"):typeof r.type=="string"?r.type:Array.isArray(r.enum)?"string":nn(r.properties)||nn(r.additionalProperties)?"object":"any"}function w$(r){let e=jn(r);return e==="array"?"List":e==="boolean"?"Boolean":e==="integer"?"Integer":e==="number"?"Number":e==="object"?"Object":e==="any"?"Any value":"Text"}function _$(r,e){return r==="any"||e==="any"||r===e?!0:r==="number"&&e==="integer"}function Jm(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function zF(r){return JSON.parse(JSON.stringify(r))}function Qm(r){let e=2166136261,t=2654435769;for(let n=0;n>>0).toString(36)}-${(t>>>0).toString(36)}`}function S$(r){let e=zF(r);return delete e.sourceRevision,e}function bd(r,e){return r===null||e===null?r===e:JSON.stringify(S$(r))===JSON.stringify(S$(e))}function x$(r){return new Map(r.fields.map(e=>[e.name,e]))}function Ym(r){return typeof r.type=="string"?r.type:"any"}function Xm(r,e,t,n){let i=Ym(r);if(i==="enum"&&(!Array.isArray(r.values)||r.values.length===0)&&t.push({code:"enum_without_values",severity:"warning",path:e,message:"Add at least one allowed value, or use String for an unrestricted value."}),i==="enum"&&Array.isArray(r.values)){let s=r.values.map(o=>JSON.stringify(o));new Set(s).size!==s.length&&t.push({code:"enum_duplicate_values",severity:"error",path:e,message:"Allowed values must be unique."}),r.default!==void 0&&!s.includes(JSON.stringify(r.default))&&t.push({code:"default_not_allowed",severity:"error",path:e,message:"The default is not one of the allowed values."})}for(let[s,o,a]of[["min","max","Minimum"],["min_length","max_length","Minimum length"]]){let c=r[s],l=r[o];typeof c=="number"&&typeof l=="number"&&c>l&&t.push({code:"constraint_range_inverted",severity:"error",path:e,message:`${a} is greater than the maximum.`})}if(typeof r.pattern=="string")try{new RegExp(r.pattern)}catch(s){t.push({code:"invalid_pattern",severity:"error",path:e,message:`The pattern is not a valid regular expression: ${s instanceof Error?s.message:String(s)}`})}if(i==="link"){let s=typeof r.target=="string"?r.target.trim():"";s&&s!=="any"&&n.size&&!n.has(s)&&t.push({code:"unknown_link_target",severity:"error",path:e,message:`The target type '${s}' is not installed in this collection.`})}if(i==="list"&&(Jm(r.items)?Xm(r.items,`${e}[]`,t,n):t.push({code:"list_items_missing",severity:"error",path:e,message:"Choose the shape of each list item."})),i==="object"){if(!Jm(r.fields)){t.push({code:"object_fields_missing",severity:"error",path:e,message:"Add an object field or change this field's type."});return}let s=new Set;for(let[o,a]of Object.entries(r.fields)){let c=`${e}.${o||"unnamed"}`;o.trim()?s.has(o)&&t.push({code:"duplicate_field_name",severity:"error",path:c,message:`The nested field '${o}' is declared more than once.`}):t.push({code:"field_name_required",severity:"error",path:c,message:"Every nested field needs a name."}),s.add(o),Jm(a)&&Xm(a,c,t,n)}}}function _a(r,e={}){let t=[],n=new Set(e.knownTypes??[]);try{Fn(r)}catch(a){t.push({code:"invalid_type_document",severity:"error",path:"type",message:a instanceof Error?a.message:String(a)})}let i=new Set;for(let a of r.fields){let c=a.name.trim(),l=`fields.${c||"unnamed"}`;c?i.has(c)&&t.push({code:"duplicate_field_name",severity:"error",path:l,message:`The field '${c}' is declared more than once.`}):t.push({code:"field_name_required",severity:"error",path:l,message:"Every field needs a name."}),i.add(c),Xm(a.definition,l,t,n)}r.displayNameKey.trim()&&!i.has(r.displayNameKey.trim())&&t.push({code:"display_field_missing",severity:"error",path:"identity.displayNameKey",message:`The display field '${r.displayNameKey.trim()}' is not declared.`});let s=new Map([...e.contracts??[]].map(a=>[Ts(a),a])),o=ba(r);for(let a of r.implementations){let c=`${a.contract}@${a.version}`,l=s.get(c);if(!l){t.push({code:"contract_unavailable",severity:"error",path:`applications.${c}`,message:"This exact application contract is not installed."});continue}for(let u of ga(l)){let d=Rs(a,u),f=o.find(h=>h.reference===d),p=va(u,f);p.level!=="valid"&&t.push({code:p.level==="error"?"invalid_contract_mapping":"review_contract_mapping",severity:p.level==="error"?"error":"warning",path:`applications.${c}.${u.reference}`,message:p.message})}}return t.filter((a,c,l)=>l.findIndex(u=>u.code===a.code&&u.path===a.path&&u.message===a.message)===c)}function Sa(r,e){if(!r)return[{code:"create_type",risk:"safe",summary:`Create the type '${e.name||"Untitled type"}'.`}];let t=[];r.name!==e.name&&t.push({code:"rename_type",risk:"high",summary:`Rename the type from '${r.name}' to '${e.name}'. Existing type references may need review.`}),(r.description!==e.description||r.displayNameKey!==e.displayNameKey)&&t.push({code:"identity",risk:"safe",summary:"Update the type's identity and display metadata."}),(r.matchPathGlob!==e.matchPathGlob||r.matchFieldsPresent!==e.matchFieldsPresent||r.matchWhere!==e.matchWhere)&&t.push({code:"membership",risk:"high",summary:"Change which records belong to this type."}),r.pathPattern!==e.pathPattern&&t.push({code:"placement",risk:"review",summary:"Change the suggested path for new records."}),r.strictMode!==e.strictMode&&t.push({code:"strictness",risk:e.strictMode===!0?"high":"review",summary:e.strictMode===!0?"Reject fields that are not declared by this type.":"Allow fields that are not declared by this type."});let n=x$(r),i=x$(e),s=[...i.keys()].filter(l=>!n.has(l)),o=[...n.keys()].filter(l=>!i.has(l));s.length&&t.push({code:"add_fields",risk:s.some(l=>i.get(l)?.definition.required===!0)?"high":"safe",summary:`Add ${s.length===1?"field":"fields"}: ${s.join(", ")}.`}),o.length&&t.push({code:"remove_fields",risk:"high",summary:`Remove ${o.length===1?"field":"fields"}: ${o.join(", ")}.`});for(let[l,u]of i){let d=n.get(l);if(!d)continue;let f=Ym(d.definition),p=Ym(u.definition);f!==p&&t.push({code:"change_field_type",risk:"high",summary:`Change '${l}' from ${f} to ${p}.`}),d.definition.required!==!0&&u.definition.required===!0&&t.push({code:"require_field",risk:"high",summary:`Make '${l}' required. Existing records may become invalid.`}),f===p&&JSON.stringify(d.definition)!==JSON.stringify(u.definition)&&d.definition.required===u.definition.required&&t.push({code:"field_rules",risk:"review",summary:`Update validation or documentation for '${l}'.`})}let a=[...n.keys()].filter(l=>i.has(l)),c=[...i.keys()].filter(l=>n.has(l));return a.join("\0")!==c.join("\0")&&t.push({code:"reorder_fields",risk:"safe",summary:"Reorder fields."}),JSON.stringify(r.implementations)!==JSON.stringify(e.implementations)&&t.push({code:"application_compatibility",risk:"review",summary:"Update application contract mappings or settings."}),!t.length&&!bd(r,e)&&t.push({code:"type_document",risk:"review",summary:"Update advanced type metadata or documentation."}),t}var Ns=require("obsidian");var xa="mdbase-frontmatter",$$=` @@ -209,17 +209,17 @@ Type definition for ${t}.`,extraFrontmatter:m,...o?{readOnlyReason:`This type us -`;var Ax=require("obsidian");var HF={schema_required:"missing",missing_required:"missing",schema_additional_properties:"not declared",unknown_field:"not declared",schema_type:"wrong type",invalid_type:"wrong type",schema_enum:"not an allowed value",invalid_enum:"not an allowed value",schema_maximum:"above maximum",above_max:"above maximum",schema_minimum:"below minimum",below_min:"below minimum",schema_max_length:"too long",above_max_length:"too long",schema_min_length:"too short",below_min_length:"too short",schema_max_items:"too many items",schema_min_items:"too few items",schema_pattern:"pattern mismatch",pattern_mismatch:"pattern mismatch",format_invalid:"invalid format",duplicate_value:"duplicate value",duplicate_unique:"duplicate value",link_not_found:"missing link target",missing_link_target:"missing link target",link_wrong_type:"link to wrong type",no_matching_type:"no matching type",unknown_type:"unknown type",invalid_frontmatter:"invalid frontmatter"};function zF(r){return HF[r]??r.replace(/^schema_/,"").replace(/_/g," ")}function KF(r){return[r.type??"",r.field??"",r.code].join("\0")}function Ym(r){return[r.type,r.field,zF(r.code)].filter(Boolean).join(" \xB7 ")}function _x(r){let e=new Map;for(let t of r){let n=KF(t),i=e.get(n);i||(i={key:n,label:Ym(t),issues:[]},e.set(n,i)),i.issues.push(t)}return[...e.values()].sort((t,n)=>n.issues.length-t.issues.length||t.label.localeCompare(n.label))}qt();function Sx(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function $x(r,e,t){let n=new Map;for(let i of r){let s=Ke(i.path,i.frontmatter,e,t);s.length&&n.set(i.path,s)}return n}function xx(r,e){let t=new Map,n=i=>{let s=t.get(i);return s||(s={notes:0,issues:0},t.set(i,s)),s};for(let i of r.values())for(let s of i)n(s).notes+=1;for(let i of e)for(let s of Xm(i,r))n(s).issues+=1;return t}function Xm(r,e){return r.type?[r.type]:e.get(r.path)??[]}function WF(r,e){let t=Fn(r),n=Sx(t.schema)?t.schema:{},i=Sx(n.value)?n.value:{};return wc(t,e??`${r.name||"new"}.md`,i)}function GF(){return new Promise(r=>window.setTimeout(r,0))}async function Ex(r){let e;try{e=WF(r.draft,r.filePath)}catch(s){return{error:s instanceof Error?s.message:String(s)}}let t=r.savedName?r.types.get(r.savedName)??null:null,n=new Map(r.types);r.savedName&&n.delete(r.savedName),n.set(e.name,e);let i={matched:[],added:[],removed:[],failing:[],fixed:0};for(let[s,o]of r.records.entries()){if(s>0&&s%400===0&&(await GF(),r.isCurrent&&!r.isCurrent()))return null;let a=t!==null&&Ke(o.path,o.frontmatter,r.config,r.types).includes(t.name),c=Ke(o.path,o.frontmatter,r.config,n).includes(e.name);if(c&&i.matched.push(o.path),c&&!a&&i.added.push(o.path),a&&!c&&i.removed.push(o.path),!c&&!a)continue;let l=a&&t?ts(o.path,o.frontmatter,t).length:0,u=c?ts(o.path,o.frontmatter,e):[];u.length?i.failing.push({path:o.path,issues:u,isNew:l===0}):l>0&&c&&(i.fixed+=1)}return{impact:i}}var vd=class{constructor(e){this.ctx=e;this.issueQuery="";this.issueSeverity="all";this.issueLimit=250;this.issueGroupBy="file"}getState(){return{issueQuery:this.issueQuery,issueSeverity:this.issueSeverity,issueGroupBy:this.issueGroupBy}}setState(e){typeof e.issueQuery=="string"&&(this.issueQuery=e.issueQuery.slice(0,2e3)),["all","error","warn"].includes(String(e.issueSeverity))&&(this.issueSeverity=e.issueSeverity),(e.issueGroupBy==="rule"||e.issueGroupBy==="file")&&(this.issueGroupBy=e.issueGroupBy)}updateValidationProgress(){let e=this.ctx.containerEl.querySelector("[data-validation-summary]");e&&(e.textContent=this.ctx.host.getValidationSummary())}filterToPath(e){this.issueQuery=e,this.issueLimit=250}render(e){let t=e.createDiv({cls:"mdbase-issues-document"}),n=this.ctx.host.getIssues(),i=new Set(n.map(b=>b.path)).size,s=t.createDiv({cls:"mdbase-document-header"}),o=s.createDiv(),a=this.ctx.host.getValidationSummary();o.createEl("h2",{text:n.length?`${n.length.toLocaleString()} ${n.length===1?"issue":"issues"} \xB7 ${i.toLocaleString()} ${i===1?"file":"files"}`:a==="Not checked yet"?"Validation":"No known issues"});let c=o.createDiv({cls:"mdbase-muted",text:a});if(c.setAttr("role","status"),c.setAttr("data-validation-summary","true"),this.ctx.host.isValidating()){let b=s.createEl("button",{text:"Stop validation"});b.onclick=()=>this.ctx.host.cancelValidation()}let l=s.createEl("button",{text:"Validate"});if(l.disabled=this.ctx.busy||this.ctx.host.isValidating(),l.onclick=()=>void this.ctx.perform(async()=>{await this.ctx.host.validateCollection(),this.ctx.render()}),!n.length)return;let u=t.createDiv({cls:"mdbase-issue-controls"}),d=u.createEl("select");d.setAttr("aria-label","Issue severity"),d.createEl("option",{value:"all",text:"All severities"}),d.createEl("option",{value:"error",text:"Errors"}),d.createEl("option",{value:"warn",text:"Warnings"}),d.value=this.issueSeverity,d.onchange=()=>{this.issueSeverity=d.value==="error"||d.value==="warn"?d.value:"all",this.issueLimit=250,this.ctx.render()};let f=u.createEl("select");f.setAttr("aria-label","Group issues"),f.createEl("option",{value:"file",text:"By file"}),f.createEl("option",{value:"rule",text:"By rule"}),f.value=this.issueGroupBy,f.onchange=()=>{this.issueGroupBy=f.value==="rule"?"rule":"file",this.ctx.render()};let p=u.createEl("input",{type:"search"});p.setAttr("aria-label","Filter issues"),p.setAttr("data-focus-key","issue-search"),p.placeholder="Filter issues",p.value=this.issueQuery,p.oninput=()=>{this.issueQuery=p.value,this.issueLimit=250,this.ctx.render();let b=this.ctx.containerEl.querySelector(".mdbase-issue-controls input[type='search']");b?.focus(),b?.setSelectionRange(b.value.length,b.value.length)};let m=this.issueQuery.trim().toLowerCase(),h=n.filter(b=>this.issueSeverity!=="all"&&b.severity!==this.issueSeverity?!1:m?`${b.path} ${b.code} ${b.type??""} ${b.field??""} ${b.message}`.toLowerCase().includes(m):!0),y=new Set(h.map(b=>b.path)).size;if((h.length!==n.length||h.length>this.issueLimit)&&t.createDiv({cls:"mdbase-issues-summary",text:`${Math.min(h.length,this.issueLimit).toLocaleString()} of ${h.length.toLocaleString()} issues \xB7 ${y.toLocaleString()} files`}),!h.length){t.createDiv({cls:"mdbase-empty-state",text:"No issues match these filters."});return}let g=h.slice(0,this.issueLimit);if(this.issueGroupBy==="rule"?this.renderIssuesByRule(t,g):this.renderIssuesByFile(t,g),h.length>g.length){let b=t.createEl("button",{cls:"mdbase-load-more",text:`Load ${Math.min(250,h.length-g.length)} more`});b.onclick=()=>{this.issueLimit+=250,this.ctx.render()}}}renderIssuesByFile(e,t){let n=new Map;for(let i of t)n.set(i.path,[...n.get(i.path)??[],i]);for(let[i,s]of n){let o=e.createEl("section",{cls:"mdbase-issue-group"}),a=o.createDiv({cls:"mdbase-issue-group-header"}),c=a.createEl("button",{cls:"mdbase-issue-file-button"});(0,Ax.setIcon)(c.createSpan({cls:"mdbase-issue-file-icon"}),"file-text"),c.createSpan({cls:"mdbase-issue-file-path",text:i}),c.setAttr("title",`Open ${i}`),c.onclick=()=>void this.ctx.host.openFileByPath(i),a.createSpan({cls:"mdbase-issue-file-count",text:`${s.length} ${s.length===1?"issue":"issues"}`});for(let l of s){let u=o.createDiv({cls:"mdbase-issue-row"});this.fillIssueRow(u,l,`${l.severity==="warn"?"Warning":"Error"}${l.field?` \xB7 ${l.field}`:""}`)}}}renderIssuesByRule(e,t){for(let n of _x(t)){let i=n.issues[0],s=e.createEl("section",{cls:"mdbase-issue-group"}),o=s.createDiv({cls:"mdbase-issue-group-header"}),a=o.createDiv({cls:"mdbase-issue-rule-title"});a.createSpan({cls:"mdbase-issue-indicator",attr:{"data-severity":i.severity,"aria-hidden":"true"}}),a.createSpan({cls:"mdbase-issue-file-path",text:Ym(i)});let c=new Set(n.issues.map(p=>p.path)).size;o.createSpan({cls:"mdbase-issue-file-count",text:`${c.toLocaleString()} ${c===1?"note":"notes"}`});let l=o.createDiv({cls:"mdbase-issue-row-actions"});this.renderEditRuleButton(l,i);let u=this.ctx.host.getQuickFixLabel(i),d=u?n.issues.filter(p=>this.ctx.host.getQuickFixLabel(p)===u):[],f=new Set(d.map(p=>p.path)).size;if(u&&f>1){let p=l.createEl("button",{text:`${u} \xB7 ${f} notes`});p.disabled=this.ctx.busy,p.onclick=()=>void this.applyBulkQuickFix(u,d)}for(let p of n.issues){let m=s.createDiv({cls:"mdbase-issue-row"});this.fillIssueRow(m,p,p.path,!0)}}}fillIssueRow(e,t,n,i=!1){e.setAttr("data-severity",t.severity),e.createSpan({cls:"mdbase-issue-indicator"}).setAttr("aria-hidden","true");let s=typeof t.details?.technical_message=="string"?t.details.technical_message:"";e.setAttr("title",s?`${t.code}: ${s}`:t.code);let o=e.createDiv({cls:"mdbase-issue-metadata"});if(i){let l=o.createEl("button",{cls:"mdbase-link-button mdbase-issue-context",text:n});l.setAttr("title",`Open ${t.path}${t.field?` at ${t.field}`:""}`),l.onclick=()=>void this.ctx.host.openFileByPath(t.path,t.field)}else o.createDiv({cls:"mdbase-issue-context",text:n});e.createDiv({cls:"mdbase-issue-row-message",text:t.message});let a=e.createDiv({cls:"mdbase-issue-row-actions"});if(!i&&t.field){let l=this.ctx.iconButton(a,"arrow-up-right",`Open ${t.path} at ${t.field}`);l.onclick=()=>void this.ctx.host.openFileByPath(t.path,t.field)}i||this.renderEditRuleButton(a,t);let c=this.ctx.host.getQuickFixLabel(t);if(c){let l=a.createEl("button",{text:c});l.disabled=this.ctx.busy,l.onclick=()=>void this.ctx.perform(async()=>{await this.ctx.host.applyQuickFix(t)})}}renderEditRuleButton(e,t){let n=Xm(t,this.ctx.recordTypes())[0],i=n?this.ctx.schema?.types.get(n):void 0;if(!i)return;let s=this.ctx.iconButton(e,"pencil",t.field?`Edit ${t.field} in ${i.name}`:`Edit type ${i.name}`);s.onclick=()=>void this.ctx.openTypeField(i.filePath,t.field)}async applyBulkQuickFix(e,t){let n=new Set(t.map(s=>s.path)).size;await new Ec(this.ctx.app).confirm(e,t)&&await this.ctx.perform(async()=>{let s=await this.ctx.host.applyQuickFixes(t);this.ctx.message=s.skipped?`${e}: updated ${s.changed} of ${n} ${n===1?"note":"notes"}. ${s.skipped} changed since validation and were left as they are.`:`${e}: updated ${s.changed} ${s.changed===1?"note":"notes"}.`})}};var Rs=require("obsidian"),wd="https://connect.mdbase.dev",kx=["string","integer","number","boolean","date","datetime","time","enum","link","list","object","any"];function Se(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function qn(r){return JSON.parse(JSON.stringify(r))}function Px(r){let e=Rs.Platform.isIosApp?"iOS":Rs.Platform.isAndroidApp?"Android":Rs.Platform.isMacOS?"Mac":Rs.Platform.isWin?"Windows":Rs.Platform.isLinux?"Linux":"Obsidian";return`${r} \xB7 ${e}`}function Qm(r){return r==="any"?"Any value":r==="datetime"?"Date and time":r&&r[0].toUpperCase()+r.slice(1)}function $a(r){return typeof r.type=="string"?r.type:"any"}function Cx(r){if(!Object.prototype.hasOwnProperty.call(r,"field"))return"field";let e=2;for(;Object.prototype.hasOwnProperty.call(r,`field${e}`);)e+=1;return`field${e}`}function _d(r,e,t){Object.defineProperty(r,e,{configurable:!0,enumerable:!0,writable:!0,value:t})}function Tt(r,e,t,n,i={}){let s=r.createDiv({cls:"mdbase-form-row"}),o=s.createEl("label",{text:e}),a=`mdbase-${Math.random().toString(36).slice(2)}`;o.htmlFor=a,i.description&&s.createDiv({cls:"mdbase-form-description",text:i.description});let c=i.multiline?s.createEl("textarea"):s.createEl("input",{type:"text"});return c.id=a,c.setAttr("data-focus-key",`form-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`),c.value=t,c.placeholder=i.placeholder??"",c.addEventListener("input",()=>n(c.value)),c}function zt(r,e,t){let n=r.createDiv({cls:"mdbase-status-row"});n.createSpan({cls:"mdbase-status-label",text:e}),n.createSpan({cls:"mdbase-status-value",text:t})}function Zm(r){if(r<1e3)return String(r);let e=r<1e4?1:0;return`${(r/1e3).toFixed(e)}k`}var xa=10,Mx={cancelled:"Paused",stale:"Stopped: changes detected",attention:"Needs attention",blocked:"Stopped",failed:"Failed"};function ey(r){return r.charAt(0).toUpperCase()+r.slice(1)}function Tx(r){if(!r)return"Never synced";let e=Date.parse(r);if(!Number.isFinite(e))return r;let t=Math.round((e-Date.now())/1e3),n=Math.abs(t),i=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"});if(n<60)return i.format(t,"second");let s=Math.round(t/60);if(Math.abs(s)<60)return i.format(s,"minute");let o=Math.round(s/60);return Math.abs(o)<24?i.format(o,"hour"):i.format(Math.round(o/24),"day")}function Rx(r){return r?r.state==="up_to_date"?"Up to date":r.state==="changes_waiting"?"Changes waiting":["attention","blocked","failed","stale"].includes(r.state)||r.recovery_required?"Needs attention":r.state==="cancelled"?"Paused safely":r.state==="applying"?"Synchronizing":r.state==="planned"?"Review ready":"Ready for first sync":"Checking connection"}function ty(r){return r instanceof Error&&r.name==="AbortError"}var Ix=require("obsidian"),Sd="Attachments are limited to 32 MiB per file on desktop and mobile. Exclusions apply to both notes and attachments. Previously synced files remain in this vault; excluded paths no longer transfer. Excluding a folder does not delete hosted copies.";function $d(r,e,t,n){let i=[...t],s=e.createDiv({cls:"mdbase-folder-exclusions"}),o=s.createDiv({cls:"mdbase-folder-chips"}),a=s.createEl("input",{type:"text",placeholder:"Choose or enter a folder"});a.id="mdbase-excluded-folder",a.setAttr("aria-label","Excluded folder"),a.setAttr("data-focus-key","excluded-folder-input");let c=s.createEl("datalist");c.id="mdbase-folder-options",a.setAttr("list",c.id);for(let f of r.vault.getAllLoadedFiles())f instanceof Ix.TFolder&&f.path&&f.path!=="/"&&c.createEl("option",{value:f.path});let l=s.createDiv({cls:"mdbase-inline-error",attr:{role:"alert"}}),u=()=>{o.empty();for(let f of i){let p=o.createEl("button",{text:`${f} \xD7`});p.setAttr("aria-label",`Remove exclusion ${f}`),p.onclick=()=>{i.splice(i.indexOf(f),1),n([...i]),u()}}},d=()=>{let f=a.value.trim().replace(/\/+$/,"");if(!f||f.startsWith("/")||f.includes("\\")||f.split("/").some(p=>!p||p==="."||p==="..")){l.textContent="Choose a vault-relative folder without parent traversal or empty segments.";return}l.textContent="",i.includes(f)||(i.push(f),n([...i]),u()),a.value="",a.focus()};s.createEl("button",{text:"Exclude folder"}).onclick=d,a.onkeydown=f=>{f.key==="Enter"&&(f.preventDefault(),d())},u()}var Is=require("obsidian");function Ox(r,e){let t=r.split(` +`;var C$=require("obsidian");var KF={schema_required:"missing",missing_required:"missing",schema_additional_properties:"not declared",unknown_field:"not declared",schema_type:"wrong type",invalid_type:"wrong type",schema_enum:"not an allowed value",invalid_enum:"not an allowed value",schema_maximum:"above maximum",above_max:"above maximum",schema_minimum:"below minimum",below_min:"below minimum",schema_max_length:"too long",above_max_length:"too long",schema_min_length:"too short",below_min_length:"too short",schema_max_items:"too many items",schema_min_items:"too few items",schema_pattern:"pattern mismatch",pattern_mismatch:"pattern mismatch",format_invalid:"invalid format",duplicate_value:"duplicate value",duplicate_unique:"duplicate value",link_not_found:"missing link target",missing_link_target:"missing link target",link_wrong_type:"link to wrong type",no_matching_type:"no matching type",unknown_type:"unknown type",invalid_frontmatter:"invalid frontmatter"};function WF(r){return KF[r]??r.replace(/^schema_/,"").replace(/_/g," ")}function GF(r){return[r.type??"",r.field??"",r.code].join("\0")}function Zm(r){return[r.type,r.field,WF(r.code)].filter(Boolean).join(" \xB7 ")}function E$(r){let e=new Map;for(let t of r){let n=GF(t),i=e.get(n);i||(i={key:n,label:Zm(t),issues:[]},e.set(n,i)),i.issues.push(t)}return[...e.values()].sort((t,n)=>n.issues.length-t.issues.length||t.label.localeCompare(n.label))}qt();function A$(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function k$(r,e,t){let n=new Map;for(let i of r){let s=Ke(i.path,i.frontmatter,e,t);s.length&&n.set(i.path,s)}return n}function P$(r,e){let t=new Map,n=i=>{let s=t.get(i);return s||(s={notes:0,issues:0},t.set(i,s)),s};for(let i of r.values())for(let s of i)n(s).notes+=1;for(let i of e)for(let s of ey(i,r))n(s).issues+=1;return t}function ey(r,e){return r.type?[r.type]:e.get(r.path)??[]}function JF(r,e){let t=Fn(r),n=A$(t.schema)?t.schema:{},i=A$(n.value)?n.value:{};return _c(t,e??`${r.name||"new"}.md`,i)}function YF(){return new Promise(r=>window.setTimeout(r,0))}async function M$(r){let e;try{e=JF(r.draft,r.filePath)}catch(s){return{error:s instanceof Error?s.message:String(s)}}let t=r.savedName?r.types.get(r.savedName)??null:null,n=new Map(r.types);r.savedName&&n.delete(r.savedName),n.set(e.name,e);let i={matched:[],added:[],removed:[],failing:[],fixed:0};for(let[s,o]of r.records.entries()){if(s>0&&s%400===0&&(await YF(),r.isCurrent&&!r.isCurrent()))return null;let a=t!==null&&Ke(o.path,o.frontmatter,r.config,r.types).includes(t.name),c=Ke(o.path,o.frontmatter,r.config,n).includes(e.name);if(c&&i.matched.push(o.path),c&&!a&&i.added.push(o.path),a&&!c&&i.removed.push(o.path),!c&&!a)continue;let l=a&&t?ts(o.path,o.frontmatter,t).length:0,u=c?ts(o.path,o.frontmatter,e):[];u.length?i.failing.push({path:o.path,issues:u,isNew:l===0}):l>0&&c&&(i.fixed+=1)}return{impact:i}}var vd=class{constructor(e){this.ctx=e;this.issueQuery="";this.issueSeverity="all";this.issueLimit=250;this.issueGroupBy="file"}getState(){return{issueQuery:this.issueQuery,issueSeverity:this.issueSeverity,issueGroupBy:this.issueGroupBy}}setState(e){typeof e.issueQuery=="string"&&(this.issueQuery=e.issueQuery.slice(0,2e3)),["all","error","warn"].includes(String(e.issueSeverity))&&(this.issueSeverity=e.issueSeverity),(e.issueGroupBy==="rule"||e.issueGroupBy==="file")&&(this.issueGroupBy=e.issueGroupBy)}updateValidationProgress(){let e=this.ctx.containerEl.querySelector("[data-validation-summary]");e&&(e.textContent=this.ctx.host.getValidationSummary())}filterToPath(e){this.issueQuery=e,this.issueLimit=250}render(e){let t=e.createDiv({cls:"mdbase-issues-document"}),n=this.ctx.host.getIssues(),i=new Set(n.map(b=>b.path)).size,s=t.createDiv({cls:"mdbase-document-header"}),o=s.createDiv(),a=this.ctx.host.getValidationSummary();o.createEl("h2",{text:n.length?`${n.length.toLocaleString()} ${n.length===1?"issue":"issues"} \xB7 ${i.toLocaleString()} ${i===1?"file":"files"}`:a==="Not checked yet"?"Validation":"No known issues"});let c=o.createDiv({cls:"mdbase-muted",text:a});if(c.setAttr("role","status"),c.setAttr("data-validation-summary","true"),this.ctx.host.isValidating()){let b=s.createEl("button",{text:"Stop validation"});b.onclick=()=>this.ctx.host.cancelValidation()}let l=s.createEl("button",{text:"Validate"});if(l.disabled=this.ctx.busy||this.ctx.host.isValidating(),l.onclick=()=>void this.ctx.perform(async()=>{await this.ctx.host.validateCollection(),this.ctx.render()}),!n.length)return;let u=t.createDiv({cls:"mdbase-issue-controls"}),d=u.createEl("select");d.setAttr("aria-label","Issue severity"),d.createEl("option",{value:"all",text:"All severities"}),d.createEl("option",{value:"error",text:"Errors"}),d.createEl("option",{value:"warn",text:"Warnings"}),d.value=this.issueSeverity,d.onchange=()=>{this.issueSeverity=d.value==="error"||d.value==="warn"?d.value:"all",this.issueLimit=250,this.ctx.render()};let f=u.createEl("select");f.setAttr("aria-label","Group issues"),f.createEl("option",{value:"file",text:"By file"}),f.createEl("option",{value:"rule",text:"By rule"}),f.value=this.issueGroupBy,f.onchange=()=>{this.issueGroupBy=f.value==="rule"?"rule":"file",this.ctx.render()};let p=u.createEl("input",{type:"search"});p.setAttr("aria-label","Filter issues"),p.setAttr("data-focus-key","issue-search"),p.placeholder="Filter issues",p.value=this.issueQuery,p.oninput=()=>{this.issueQuery=p.value,this.issueLimit=250,this.ctx.render();let b=this.ctx.containerEl.querySelector(".mdbase-issue-controls input[type='search']");b?.focus(),b?.setSelectionRange(b.value.length,b.value.length)};let h=this.issueQuery.trim().toLowerCase(),m=n.filter(b=>this.issueSeverity!=="all"&&b.severity!==this.issueSeverity?!1:h?`${b.path} ${b.code} ${b.type??""} ${b.field??""} ${b.message}`.toLowerCase().includes(h):!0),y=new Set(m.map(b=>b.path)).size;if((m.length!==n.length||m.length>this.issueLimit)&&t.createDiv({cls:"mdbase-issues-summary",text:`${Math.min(m.length,this.issueLimit).toLocaleString()} of ${m.length.toLocaleString()} issues \xB7 ${y.toLocaleString()} files`}),!m.length){t.createDiv({cls:"mdbase-empty-state",text:"No issues match these filters."});return}let g=m.slice(0,this.issueLimit);if(this.issueGroupBy==="rule"?this.renderIssuesByRule(t,g):this.renderIssuesByFile(t,g),m.length>g.length){let b=t.createEl("button",{cls:"mdbase-load-more",text:`Load ${Math.min(250,m.length-g.length)} more`});b.onclick=()=>{this.issueLimit+=250,this.ctx.render()}}}renderIssuesByFile(e,t){let n=new Map;for(let i of t)n.set(i.path,[...n.get(i.path)??[],i]);for(let[i,s]of n){let o=e.createEl("section",{cls:"mdbase-issue-group"}),a=o.createDiv({cls:"mdbase-issue-group-header"}),c=a.createEl("button",{cls:"mdbase-issue-file-button"});(0,C$.setIcon)(c.createSpan({cls:"mdbase-issue-file-icon"}),"file-text"),c.createSpan({cls:"mdbase-issue-file-path",text:i}),c.setAttr("title",`Open ${i}`),c.onclick=()=>void this.ctx.host.openFileByPath(i),a.createSpan({cls:"mdbase-issue-file-count",text:`${s.length} ${s.length===1?"issue":"issues"}`});for(let l of s){let u=o.createDiv({cls:"mdbase-issue-row"});this.fillIssueRow(u,l,`${l.severity==="warn"?"Warning":"Error"}${l.field?` \xB7 ${l.field}`:""}`)}}}renderIssuesByRule(e,t){for(let n of E$(t)){let i=n.issues[0],s=e.createEl("section",{cls:"mdbase-issue-group"}),o=s.createDiv({cls:"mdbase-issue-group-header"}),a=o.createDiv({cls:"mdbase-issue-rule-title"});a.createSpan({cls:"mdbase-issue-indicator",attr:{"data-severity":i.severity,"aria-hidden":"true"}}),a.createSpan({cls:"mdbase-issue-file-path",text:Zm(i)});let c=new Set(n.issues.map(p=>p.path)).size;o.createSpan({cls:"mdbase-issue-file-count",text:`${c.toLocaleString()} ${c===1?"note":"notes"}`});let l=o.createDiv({cls:"mdbase-issue-row-actions"});this.renderEditRuleButton(l,i);let u=this.ctx.host.getQuickFixLabel(i),d=u?n.issues.filter(p=>this.ctx.host.getQuickFixLabel(p)===u):[],f=new Set(d.map(p=>p.path)).size;if(u&&f>1){let p=l.createEl("button",{text:`${u} \xB7 ${f} notes`});p.disabled=this.ctx.busy,p.onclick=()=>void this.applyBulkQuickFix(u,d)}for(let p of n.issues){let h=s.createDiv({cls:"mdbase-issue-row"});this.fillIssueRow(h,p,p.path,!0)}}}fillIssueRow(e,t,n,i=!1){e.setAttr("data-severity",t.severity),e.createSpan({cls:"mdbase-issue-indicator"}).setAttr("aria-hidden","true");let s=typeof t.details?.technical_message=="string"?t.details.technical_message:"";e.setAttr("title",s?`${t.code}: ${s}`:t.code);let o=e.createDiv({cls:"mdbase-issue-metadata"});if(i){let l=o.createEl("button",{cls:"mdbase-link-button mdbase-issue-context",text:n});l.setAttr("title",`Open ${t.path}${t.field?` at ${t.field}`:""}`),l.onclick=()=>void this.ctx.host.openFileByPath(t.path,t.field)}else o.createDiv({cls:"mdbase-issue-context",text:n});e.createDiv({cls:"mdbase-issue-row-message",text:t.message});let a=e.createDiv({cls:"mdbase-issue-row-actions"});if(!i&&t.field){let l=this.ctx.iconButton(a,"arrow-up-right",`Open ${t.path} at ${t.field}`);l.onclick=()=>void this.ctx.host.openFileByPath(t.path,t.field)}i||this.renderEditRuleButton(a,t);let c=this.ctx.host.getQuickFixLabel(t);if(c){let l=a.createEl("button",{text:c});l.disabled=this.ctx.busy,l.onclick=()=>void this.ctx.perform(async()=>{await this.ctx.host.applyQuickFix(t)})}}renderEditRuleButton(e,t){let n=ey(t,this.ctx.recordTypes())[0],i=n?this.ctx.schema?.types.get(n):void 0;if(!i)return;let s=this.ctx.iconButton(e,"pencil",t.field?`Edit ${t.field} in ${i.name}`:`Edit type ${i.name}`);s.onclick=()=>void this.ctx.openTypeField(i.filePath,t.field)}async applyBulkQuickFix(e,t){let n=new Set(t.map(s=>s.path)).size;await new Ac(this.ctx.app).confirm(e,t)&&await this.ctx.perform(async()=>{let s=await this.ctx.host.applyQuickFixes(t);this.ctx.message=s.skipped?`${e}: updated ${s.changed} of ${n} ${n===1?"note":"notes"}. ${s.skipped} changed since validation and were left as they are.`:`${e}: updated ${s.changed} ${s.changed===1?"note":"notes"}.`})}};var Is=require("obsidian"),wd="https://connect.mdbase.dev",T$=["string","integer","number","boolean","date","datetime","time","enum","link","list","object","any"];function Se(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function qn(r){return JSON.parse(JSON.stringify(r))}function R$(r){let e=Is.Platform.isIosApp?"iOS":Is.Platform.isAndroidApp?"Android":Is.Platform.isMacOS?"Mac":Is.Platform.isWin?"Windows":Is.Platform.isLinux?"Linux":"Obsidian";return`${r} \xB7 ${e}`}function ty(r){return r==="any"?"Any value":r==="datetime"?"Date and time":r&&r[0].toUpperCase()+r.slice(1)}function $a(r){return typeof r.type=="string"?r.type:"any"}function I$(r){if(!Object.prototype.hasOwnProperty.call(r,"field"))return"field";let e=2;for(;Object.prototype.hasOwnProperty.call(r,`field${e}`);)e+=1;return`field${e}`}function _d(r,e,t){Object.defineProperty(r,e,{configurable:!0,enumerable:!0,writable:!0,value:t})}function Tt(r,e,t,n,i={}){let s=r.createDiv({cls:"mdbase-form-row"}),o=s.createEl("label",{text:e}),a=`mdbase-${Math.random().toString(36).slice(2)}`;o.htmlFor=a,i.description&&s.createDiv({cls:"mdbase-form-description",text:i.description});let c=i.multiline?s.createEl("textarea"):s.createEl("input",{type:"text"});return c.id=a,c.setAttr("data-focus-key",`form-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`),c.value=t,c.placeholder=i.placeholder??"",c.addEventListener("input",()=>n(c.value)),c}function Kt(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 ry(r){if(r<1e3)return String(r);let e=r<1e4?1:0;return`${(r/1e3).toFixed(e)}k`}var Ea=10,O$={cancelled:"Paused",stale:"Stopped: changes detected",attention:"Needs attention",blocked:"Stopped",failed:"Failed"};function ny(r){return r.charAt(0).toUpperCase()+r.slice(1)}function D$(r){if(!r)return"Never synced";let e=Date.parse(r);if(!Number.isFinite(e))return r;let t=Math.round((e-Date.now())/1e3),n=Math.abs(t),i=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"});if(n<60)return i.format(t,"second");let s=Math.round(t/60);if(Math.abs(s)<60)return i.format(s,"minute");let o=Math.round(s/60);return Math.abs(o)<24?i.format(o,"hour"):i.format(Math.round(o/24),"day")}function N$(r){return r?r.state==="up_to_date"?"Up to date":r.state==="changes_waiting"?"Changes waiting":["attention","blocked","failed","stale"].includes(r.state)||r.recovery_required?"Needs attention":r.state==="cancelled"?"Paused safely":r.state==="applying"?"Synchronizing":r.state==="planned"?"Review ready":"Ready for first sync":"Checking connection"}function Sd(r){return r instanceof Error&&r.name==="AbortError"}var L$=require("obsidian"),xd="Attachments are limited to 32 MiB per file on desktop and mobile. Exclusions apply to both notes and attachments. Previously synced files remain in this vault; excluded paths no longer transfer. Excluding a folder does not delete hosted copies.";function $d(r,e,t,n){let i=[...t],s=e.createDiv({cls:"mdbase-folder-exclusions"}),o=s.createDiv({cls:"mdbase-folder-chips"}),a=s.createEl("input",{type:"text",placeholder:"Choose or enter a folder"});a.id="mdbase-excluded-folder",a.setAttr("aria-label","Excluded folder"),a.setAttr("data-focus-key","excluded-folder-input");let c=s.createEl("datalist");c.id="mdbase-folder-options",a.setAttr("list",c.id);for(let f of r.vault.getAllLoadedFiles())f instanceof L$.TFolder&&f.path&&f.path!=="/"&&c.createEl("option",{value:f.path});let l=s.createDiv({cls:"mdbase-inline-error",attr:{role:"alert"}}),u=()=>{o.empty();for(let f of i){let p=o.createEl("button",{text:`${f} \xD7`});p.setAttr("aria-label",`Remove exclusion ${f}`),p.onclick=()=>{i.splice(i.indexOf(f),1),n([...i]),u()}}},d=()=>{let f=a.value.trim().replace(/\/+$/,"");if(!f||f.startsWith("/")||f.includes("\\")||f.split("/").some(p=>!p||p==="."||p==="..")){l.textContent="Choose a vault-relative folder without parent traversal or empty segments.";return}l.textContent="",i.includes(f)||(i.push(f),n([...i]),u()),a.value="",a.focus()};s.createEl("button",{text:"Exclude folder"}).onclick=d,a.onkeydown=f=>{f.key==="Enter"&&(f.preventDefault(),d())},u()}var Os=require("obsidian");function F$(r,e){let t=r.split(` `),n=e.split(` -`),i=t.length>200||n.length>200,s=t.slice(0,200),o=n.slice(0,200),a=Array.from({length:s.length+1},()=>new Uint16Array(o.length+1));for(let d=s.length-1;d>=0;d-=1)for(let f=o.length-1;f>=0;f-=1)a[d][f]=s[d]===o[f]?a[d+1][f+1]+1:Math.max(a[d+1][f],a[d][f+1]);let c=[],l=0,u=0;for(;(l=300);)l=o.length||l=a[l][u+1]?(c.push({kind:"local",value:s[l]}),l+=1):(c.push({kind:"remote",value:o[u]}),u+=1);return{lines:c,truncated:i||l0&&!r.actions.some(o=>o.command!=="advance_checkpoint"))return{actionLabel:"Resolve issues",actionDisabled:!0,message:"Synchronization is paused. Resolve the blocking issues, then refresh the review."};let n=r.actions.filter(o=>o.command!=="advance_checkpoint").length,i=r.actions.some(o=>o.command==="advance_checkpoint"),s=r.issues.some(o=>o.code==="invalid_frontmatter"&&!o.blocking);return{actionLabel:n?`Sync ${n}${r.summary.blocking_issues?" available":""} ${n===1?"change":"changes"}`:i?"Confirm sync":"Up to date",actionDisabled:t||r.actions.length===0,message:r.summary.blocking_issues>0?"Sync available changes. Unresolved items are isolated and remain for the next review; they do not stop independent transfers.":s?"Frontmatter warnings do not block this sync. Document bytes are preserved; synchronization does not repair YAML.":e?"Review each transfer below, then sync when ready.":"This vault and the hosted collection are already aligned."}}function pr(r){return r<1024?`${r} B`:r<1024*1024?`${(r/1024).toFixed(r<10*1024?1:0)} KB`:r<1024*1024*1024?`${(r/(1024*1024)).toFixed(r<10*1024*1024?1:0)} MB`:`${(r/(1024*1024*1024)).toFixed(1)} GB`}function Dx(r){let{connected:e,status:t,progress:n,fileProgress:i,problem:s,validationIssues:o,localChangeObserved:a}=r,c=r.reviewChanges??0;if(!e)return o?{state:"attention",label:`mdbase: ${o} ${o===1?"issue":"issues"}`,detail:"Open validation issues",destination:"issues"}:{state:"local",label:"mdbase: Local",detail:"This vault is not connected",destination:"sync"};if(i){let u=i.totalBytes>0?Math.min(100,Math.round(i.transferredBytes/i.totalBytes*100)):100;return{state:"syncing",label:`mdbase: ${i.direction==="upload"?"Uploading":"Downloading"} ${u}%`,detail:`${i.path} \xB7 ${pr(i.transferredBytes)} of ${pr(i.totalBytes)}`,destination:"sync"}}if(n)return{state:"syncing",label:`mdbase: Syncing${n.total==null?"":` ${n.completed}/${n.total}`}`,detail:"Open synchronization progress",destination:"sync"};if(s&&s.kind!=="busy")return{state:s.kind==="paused"?"paused":s.kind==="offline"?"offline":"attention",label:s.kind==="paused"?"mdbase: Paused":s.kind==="offline"?"mdbase: Offline":s.kind==="device"?"mdbase: Set up sync":"mdbase: Needs attention",detail:s.kind==="offline"?`${s.title}. Changes will sync when it's back.`:s.title,destination:"sync"};if(c>0)return{state:"attention",label:`mdbase: Review ${c} ${c===1?"change":"changes"}`,detail:"Some changes need review before syncing",destination:"sync"};if(t?.recovery_required||t?.conflicts.length||t?.local_issues.length||["attention","blocked","failed","stale"].includes(t?.state??""))return{state:"attention",label:"mdbase: Needs attention",detail:"Review synchronization",destination:"sync"};if(t?.state==="cancelled")return{state:"paused",label:"mdbase: Paused",detail:"Review and resume synchronization",destination:"sync"};let l=t?.pending??0;return a||l>0||t?.state==="changes_waiting"||t?.state==="planned"?{state:"waiting",label:l>0?`mdbase: ${l} ${l===1?"change":"changes"}`:"mdbase: Changes waiting",detail:"Review local and hosted changes",destination:"sync"}:t?.state==="up_to_date"?{state:"synced",label:"mdbase: Synced",detail:"Local and hosted collections are aligned",destination:"sync"}:{state:"waiting",label:"mdbase: Ready to sync",detail:"Review the first synchronization",destination:"sync"}}var YF=new Set(["mirror_credentials_missing","invalid_mirror_enrollment","mirror_enrollment_expired","mirror_pairing_not_found","invalid_mirror_pairing","mirror_access_rejected","replica_revoked"]);function Rt(r){let e=QF(r);return e==="mirror_busy"?{code:e,kind:"busy",title:"Synchronization is already running",message:"The active transfer is still using this vault. Its progress is shown below.",action:"resume",actionLabel:"Show progress"}:e==="mirror_other_device"?{code:e,kind:"device",title:"Set up sync on this device",message:"This vault's sync settings came from another device or another copy of the vault, probably through a different sync service. Approve this copy to give it its own connection. Your files stay as they are.",action:"reauthorize",actionLabel:"Set up this device"}:YF.has(e)?{code:e,kind:"auth",title:"Connect approval is required again",message:"Your local files and mirror checkpoint are safe. Approve this vault again to restore access.",action:"reauthorize",actionLabel:"Sign in again"}:["operation_cancelled","cancelled","sync_cancelled","AbortError"].includes(e)?{code:e,kind:"paused",title:"Synchronization paused",message:"Completed changes are saved. Sync resumes from the same point when you continue.",action:"resume",actionLabel:"Resume sync"}:["stale","stale_mirror_plan","mirror_plan_stale","sync_plan_stale","conflict_decision_stale"].includes(e)?{code:e,kind:"decision",title:"The collection changed again",message:"No stale decision was applied. Review the newest local and hosted versions.",action:"review",actionLabel:"Review newest changes"}:["enrollment_recovery_required","mirror_recovery_required","pending_mirror_recovery"].includes(e)?{code:e,kind:"recovery",title:"Synchronization needs recovery",message:"Your original files are safe. Resume from the durable checkpoint before disconnecting this vault.",action:"resume",actionLabel:"Resume recovery"}:oa(r)?{code:e,kind:"offline",title:"Can't reach mdbase Connect",message:"Your changes are saved on this device and sync automatically when the connection returns.",action:"retry",actionLabel:"Retry now"}:{code:e,kind:"internal",title:"Sync stopped unexpectedly",message:`${ZF(r,"An unexpected error stopped synchronization.")} Your files are safe. Sync tries again automatically; if this keeps happening, copy the diagnostics and report it.`,action:"retry",actionLabel:"Try again"}}function Nx(r){return Rt(Object.assign(new Error(r.message),{code:r.code}))}function Lx(r){return Array.isArray(r)?r.filter(XF).slice(-JF):[]}function XF(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;return typeof e.id=="string"&&typeof e.occurredAt=="string"&&typeof e.summary=="string"&&(e.detail===void 0||typeof e.detail=="string")&&(e.path===void 0||typeof e.path=="string")&&["success","info","attention","error"].includes(e.tone??"")&&typeof e.requiresAcknowledgement=="boolean"}function QF(r){return r instanceof DOMException?r.name:r&&typeof r=="object"&&"code"in r&&typeof r.code=="string"?r.code:r instanceof Error&&r.name?r.name:"sync_failed"}function ZF(r,e){return r instanceof Error&&r.message?r.message:e}var xd=class{constructor(e){this.ctx=e;this.conflictComparisons=new Map;this.loadingConflictComparisons=new Set;this.pendingSyncFocus=null;this.historyQuery="";this.transferQuery="";this.transferFilter="all";this.transferPages=new Map;this.historyLimit=xa;this.previewComparisons=new Map;this.comparedPreview=null;this.loadingPreviewComparisons=new Set;this.enrollmentVerification="";this.enrollmentAbort=null;this.enrollmentControlUrl=wd;this.enrollmentMirrorName=Px(this.ctx.app.vault.getName());this.enrollmentCollectionId="";this.enrollmentMode="read_write";this.filePolicyDraft=null;this.adoptionFileProgress="";this.adoptionPreview=null;this.adoptionRenamePlan=null;this.adoptionStage="";this.adoptionFailed=!1}getState(){return{historyQuery:this.historyQuery}}setState(e){typeof e.historyQuery=="string"&&(this.historyQuery=e.historyQuery.slice(0,2e3))}get session(){return this.ctx.host.sync}dispose(){this.enrollmentAbort?.abort(),this.enrollmentAbort=null}focusSection(e){this.ctx.destination="sync",this.pendingSyncFocus=e,this.ctx.render(),window.setTimeout(()=>this.focusPendingSyncSection(),0)}async reconnectCollection(){await this.session.reconnect()==="reauthorize"&&await this.ctx.perform(()=>this.reauthorizeCollection())}render(e){let t=e.createDiv({cls:"mdbase-sync-document"}),n=this.ctx.host.getMirrorProfile();if(!n){this.renderEnrollment(t);return}let i=this.session.state,s=!!(i.fileProgress||i.progress),a=(i.problem?.kind==="busy"?null:i.problem)??(i.paused&&!s?{code:"sync_paused",kind:"paused",title:"Sync is paused",message:"Changes on this device and in Connect wait until you resume.",action:"resume",actionLabel:"Resume sync"}:i.status?.recovery_required?{code:"mirror_recovery_required",kind:"recovery",title:"Synchronization needs recovery",message:"Your original files are safe. Resume from the durable checkpoint before disconnecting this vault.",action:"resume",actionLabel:"Resume recovery"}:null),c=s?"Syncing":i.busy?"Checking\u2026":a?.kind==="paused"?"Paused":a?.kind==="offline"?"Offline":a?.kind==="auth"?"Approval needed":a?.kind==="device"?"Set up this device":a?"Needs attention":Rx(i.status),l=t.createEl("section",{cls:"mdbase-sync-status"});l.setAttr("data-state",i.status?.state??"checking");let u=l.createDiv({cls:"mdbase-sync-heading"});u.createEl("h2",{text:n.name}),u.createDiv({cls:"mdbase-muted",text:`${c} \xB7 ${Tx(i.status?.last_synced_at)}`});let d=u.createDiv({cls:"mdbase-muted mdbase-sync-scope"});d.createSpan({text:this.syncScopeText(n.mode)});let f=d.createEl("button",{cls:"mdbase-link-button",text:"Settings"});if(f.setAttr("aria-label","Open sync settings"),f.onclick=()=>this.ctx.host.openSettings(),i.message&&!i.problem){let b=l.createDiv({cls:"mdbase-inline-message mdbase-notice"});b.createSpan({text:i.message}).setAttr("role","status");let v=this.ctx.iconButton(b,"x","Dismiss sync message");v.onclick=()=>this.session.clearMessage()}if(s){let b=l.createDiv({cls:"mdbase-sync-progress",attr:{"aria-live":"polite"}}),v=i.fileProgress?.totalBytes??i.progress?.total??null,S=i.fileProgress?.transferredBytes??i.progress?.completed??0,_=b.createEl("progress");_.max=v??1,_.value=v==null?0:S,v==null&&_.removeAttribute("value"),b.createDiv({cls:"mdbase-progress-label",text:i.fileProgress?`${i.fileProgress.direction==="upload"?"Uploading":"Downloading"} ${i.fileProgress.path} \xB7 ${pr(S)} of ${pr(v??0)}`:`${i.progress?.phase==="uploading"?"Uploading local changes":i.progress?.phase==="downloading"?"Downloading collection files":"Applying changes"} \xB7 ${S}${v==null?"":` of ${v}`}`});let E=b.createEl("button",{text:"Stop"});E.onclick=()=>this.session.cancel()}let p=this.ctx.host.otherSyncServices();p.length&&l.createDiv({cls:"mdbase-inline-message mdbase-sync-coexistence",text:`${p.join(" and ")} also ${p.length===1?"syncs":"sync"} this vault. Two services syncing the same notes can duplicate them or bring deleted ones back; let only one of them sync this vault's notes.`}),a&&this.renderRecoveryCard(l,a);let m=this.ctx.busy||i.busy||s,h=i.preview;h!==this.comparedPreview&&(this.previewComparisons.clear(),this.comparedPreview=h,this.transferPages.clear());let y=this.session.safety(),g=!!(h?.plan.actions.length||h?.entries.length);if(!s&&!a){let b=l.createDiv({cls:"mdbase-sync-actions"});if(g&&h){let v=ry(h.plan,h.entries.length,m);if(h.plan.actions.length&&!v.actionDisabled){let _=b.createEl("button",{text:v.actionLabel,cls:"mod-cta"});_.disabled=v.actionDisabled,_.onclick=()=>void this.session.apply()}let S=this.ctx.iconButton(b,"refresh-cw","Refresh review");S.disabled=m,S.onclick=()=>void this.session.review()}else{let v=b.createEl("button",{text:i.busy?"Checking\u2026":"Sync now",cls:"mod-cta"});v.disabled=m,v.onclick=()=>void this.session.syncNow()}}g&&y&&!y.safe&&h?.plan.actions.length&&l.createDiv({cls:"mdbase-muted mdbase-review-reasons",text:`Review needed: ${y.reasons.join(", ").toLowerCase()}.`}),h&&g&&this.renderMirrorPreview(t,h),i.status?.conflicts.length&&this.renderConflicts(t,i.status),i.status?.local_issues.length&&!g&&this.renderLocalMirrorIssues(t,i.status),this.renderHistory(t),window.setTimeout(()=>this.focusPendingSyncSection(),0)}syncScopeText(e){let t=this.ctx.host.connectSync.getSelectiveSync().excluded_folders,n=t.length?`Whole vault except ${t.length>2?`${t.slice(0,2).join(", ")} +${t.length-2}`:t.join(", ")}`:"Whole vault";return`${e==="read_only"?"Read only":"Read and write"} \xB7 ${n}`}renderRecoveryCard(e,t){let n=e.createDiv({cls:"mdbase-recovery-card"});n.setAttr("data-kind",t.kind);let i=n.createDiv();i.createEl("strong",{text:t.title}),i.createDiv({text:t.message});let s=this.session.state.retryAt;if(s&&(t.kind==="offline"||t.kind==="internal")){let c=Math.max(0,Math.round((s-Date.now())/1e3));i.createDiv({cls:"mdbase-muted",text:c<=1?"Trying again now\u2026":c<60?`Trying again in ${c}s.`:`Trying again in ${Math.round(c/60)} min.`})}let o=n.createDiv({cls:"mdbase-recovery-actions"}),a=o.createEl("button",{text:t.actionLabel,cls:"mod-cta"});if(a.disabled=this.ctx.busy||this.session.state.busy,a.onclick=()=>{t.kind==="auth"?this.reconnectCollection():t.action==="reauthorize"?this.ctx.perform(()=>this.reauthorizeCollection()):t.action==="review"?this.session.review():this.session.syncNow()},t.kind==="internal"||t.kind==="recovery"){let c=o.createEl("button",{text:"Copy diagnostics"});c.onclick=()=>void this.ctx.host.copySyncDiagnostics()}}async reauthorizeCollection(){this.enrollmentAbort?.abort();let e=new AbortController;this.enrollmentAbort=e;try{await this.session.reauthorize({signal:e.signal,onVerification:t=>{this.enrollmentVerification=t.verificationUri,this.ctx.message="Approve this vault again in Connect. Its local files and checkpoint remain unchanged.",window.open(t.verificationUri,"_blank","noopener,noreferrer"),this.ctx.render()},onStatus:t=>{this.ctx.message=t.state==="waiting_for_approval"?"Waiting for approval in Connect\u2026":`Connect is retrying approval (attempt ${t.attempt}).`,this.ctx.render()}}),this.enrollmentVerification="",this.ctx.message=""}finally{this.enrollmentAbort===e&&(this.enrollmentAbort=null)}}renderHistory(e){let t=this.session.historyRuns();if(!t.length)return;let n=t.filter(l=>l.needsAcknowledgement),i=this.ctx.disclosure(e,"sync-activity","History",n.length>0);i.addClass("mdbase-activity"),i.id="mdbase-sync-activity";for(let l of[...n].reverse())this.renderEventRow(i,l);let s=i.createDiv({cls:"mdbase-section-header mdbase-history-controls"}),o=s.createEl("input",{type:"search"});if(o.setAttr("aria-label","Filter history by path"),o.setAttr("data-focus-key","history-search"),o.placeholder="Filter by path",o.value=this.historyQuery,o.oninput=()=>{this.historyQuery=o.value,this.historyLimit=xa,this.ctx.render()},t.length>n.length){let l=s.createEl("button",{text:"Clear history"});l.disabled=this.ctx.busy,l.onclick=()=>void this.session.clearHistory()}let a=this.historyQuery.trim().toLowerCase(),c=K$(t.filter(l=>!l.needsAcknowledgement),a).sort((l,u)=>u.finishedAt.localeCompare(l.finishedAt));if(!c.length){i.createDiv({cls:"mdbase-muted",text:a?"No synced files match.":"No completed syncs."});return}for(let l of c.slice(0,this.historyLimit))U$(l)?this.renderEventRow(i,l):this.renderHistoryRun(i,l,a!=="");if(c.length>this.historyLimit){let l=i.createEl("button",{cls:"mdbase-link-button",text:`Show ${Math.min(xa,c.length-this.historyLimit)} more`});l.setAttr("data-focus-key","history-more"),l.onclick=()=>{this.historyLimit+=xa,this.ctx.render()}}}renderHistoryRun(e,t,n){let i=e.createEl("details",{cls:"mdbase-history-run"}),s=`history-run-${t.id}`;n?i.open=!0:(i.dataset.disclosure=s,i.open=this.ctx.disclosures.get(s)??!1);let o=i.createEl("summary",{cls:"mdbase-activity-row"});o.setAttr("data-focus-key",`disclosure-${s}`);let a=t.outcome==="applied"?"success":t.outcome==="failed"?"error":"attention";o.setAttr("data-tone",a),(0,Is.setIcon)(o.createSpan(),a==="success"?"check":"circle-alert");let c=o.createDiv();c.createEl("strong",{text:H$(t)});let l=Mx[t.outcome];c.createSpan({cls:"mdbase-muted",text:l?`${ks(t.finishedAt)} \xB7 ${l}`:ks(t.finishedAt)}),t.message&&t.outcome!=="applied"&&c.createDiv({text:t.message}),(0,Is.setIcon)(o.createSpan({cls:"mdbase-history-chevron"}),"chevron-right");let u=i.createDiv({cls:"mdbase-transfer-ledger mdbase-history-files"});for(let d of t.files.slice(0,250)){let f=u.createDiv({cls:"mdbase-transfer-row"});f.setAttr("title",new Date(d.at).toLocaleString()),f.createSpan({cls:"mdbase-transfer-action",text:d.action}).setAttr("data-action",d.status==="completed"?d.action:"fix");let m=f.createDiv({cls:"mdbase-transfer-body"}),h=m.createDiv({cls:"mdbase-transfer-path"}),y=h.createSpan({cls:"mdbase-history-direction"}),g=d.direction==="download"?"Downloaded":d.direction==="upload"?"Uploaded":"Needs attention";if(y.setAttr("aria-label",g),y.setAttr("title",g),(0,Is.setIcon)(y,d.direction==="download"?"download":d.direction==="upload"?"upload":"circle-alert"),d.action!=="delete"&&this.ctx.app.vault.getAbstractFileByPath(d.path)){let b=h.createEl("button",{cls:"mdbase-link-button mdbase-transfer-open"});b.createEl("code",{text:d.path}),b.setAttr("title",`Open ${d.path}`),b.onclick=()=>void this.ctx.host.openFileByPath(d.path)}else h.createEl("code",{text:d.path});d.fromPath&&m.createDiv({cls:"mdbase-muted",text:`From ${d.fromPath}`}),d.status!=="completed"&&m.createDiv({text:d.message?`${ey(d.status)}: ${d.message}`:ey(d.status)})}t.files.length>250&&u.createDiv({cls:"mdbase-transfer-more",text:`${t.files.length-250} more files are recorded in this sync.`})}renderEventRow(e,t){let n=t.tone??"info",i=e.createDiv({cls:"mdbase-activity-row"});i.setAttr("data-tone",n),(0,Is.setIcon)(i.createSpan(),n==="success"?"check":n==="info"?"info":"circle-alert");let s=i.createDiv(),o=t.summary??"";if(t.message&&t.message!==o){let a=s.createEl("details");a.createEl("summary",{text:o}),a.createDiv({text:t.message})}else s.createEl("strong",{text:o});if(s.createSpan({cls:"mdbase-muted",text:ks(t.finishedAt)}),t.needsAcknowledgement){let a=i.createEl("button",{text:"Dismiss"});a.disabled=this.ctx.busy,a.onclick=()=>void this.session.dismissEvent(t.id)}}focusPendingSyncSection(){if(!this.pendingSyncFocus)return;let e=this.pendingSyncFocus==="activity"?"mdbase-sync-activity":"mdbase-sync-conflicts",t=this.ctx.containerEl.querySelector(`#${e}`);if(!t)return;this.pendingSyncFocus=null;let n=t.closest("details");n&&(n.open=!0),t.scrollIntoView({block:"nearest"})}filePolicy(){return this.filePolicyDraft??=JSON.parse(JSON.stringify(this.ctx.host.connectSync.getSelectiveSync())),this.filePolicyDraft}renderFilePolicyControls(e){let t=this.filePolicy(),n=e.createEl("section",{cls:"mdbase-editor-section mdbase-file-policy"});n.createEl("h3",{text:"Attachments"});let i=n.createDiv({cls:"mdbase-file-class-grid"}),s=[["image","Images"],["audio","Audio"],["video","Video"],["pdf","PDFs"],["other","Other files"]];for(let[o,a]of s){let c=i.createEl("label"),l=c.createEl("input",{type:"checkbox"});l.setAttr("data-focus-key",`file-class-${o}`),l.checked=t.file_classes.includes(o),l.onchange=()=>{t.file_classes=l.checked?[...new Set([...t.file_classes,o])]:t.file_classes.filter(u=>u!==o),this.ctx.render()},c.createSpan({text:a})}n.createDiv({cls:"mdbase-form-description",text:Sd}),n.createEl("h4",{text:"Excluded folders"}),$d(this.ctx.app,n,t.excluded_folders,o=>{t.excluded_folders=o}),t.file_classes.includes("other")&&n.createDiv({cls:"mdbase-inline-message",text:"Other files includes all remaining visible file formats."})}renderEnrollment(e){if(this.ctx.schema||this.ctx.host.connectSync.getAdoptionMarker()){this.renderLocalAdoption(e);return}let t=e.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});if(t.createEl("h3",{text:"Copy a collection from Connect"}),t.createEl("p",{cls:"mdbase-muted",text:"Connect holds the collection; this vault syncs a copy. Choose a collection in Connect, then review the first sync."}),this.enrollmentVerification){let p=t.createDiv({cls:"mdbase-approval-link"});p.createSpan({text:"Waiting for approval \xB7 "});let m=p.createEl("a",{text:"Open Connect",href:this.enrollmentVerification});m.setAttr("target","_blank"),m.setAttr("rel","noopener noreferrer")}if(this.enrollmentAbort&&this.enrollmentVerification){let p=t.createEl("button",{text:"Stop waiting"});p.onclick=()=>this.enrollmentAbort?.abort();return}Tt(t,"Device name",this.enrollmentMirrorName,p=>{this.enrollmentMirrorName=p});let n=t.createDiv({cls:"mdbase-form-row"}),i=n.createEl("label",{text:"Access"}),s=n.createEl("select");i.htmlFor=s.id="mdbase-enrollment-access",s.createEl("option",{value:"read_write",text:"Read and write"}),s.createEl("option",{value:"read_only",text:"Read only"}),s.value=this.enrollmentMode,s.onchange=()=>{this.enrollmentMode=s.value==="read_only"?"read_only":"read_write",this.ctx.render()};let o=t.createDiv({cls:"mdbase-form-row mdbase-sync-target"});o.createEl("label",{text:"Syncs"});let a=o.createDiv({cls:"mdbase-sync-target-value"}),c=this.filePolicy().excluded_folders;a.createSpan({text:`Whole vault \u201C${this.ctx.app.vault.getName()}\u201D${c.length?` except ${c.join(", ")}`:""}`});let l=a.createEl("button",{cls:"mdbase-link-button",text:"Exclude folders"});l.onclick=()=>{this.ctx.disclosures.set("enrollment-options",!0),this.ctx.render()},t.createEl("p",{cls:"mdbase-form-description",text:this.enrollmentMode==="read_write"?"Existing notes may upload. Nothing moves until you review and sync.":"Downloads only. Existing local changes must be resolved or excluded."});let u=this.ctx.disclosure(t,"enrollment-options","Advanced");Tt(u,"Connect URL",this.enrollmentControlUrl,p=>{this.enrollmentControlUrl=p},{placeholder:wd}),Tt(u,"Collection ID",this.enrollmentCollectionId,p=>{this.enrollmentCollectionId=p},{placeholder:"Choose during approval"}),this.renderFilePolicyControls(u);let d=t.createDiv({cls:"mdbase-actions mdbase-enrollment-actions"}),f=d.createEl("button",{text:this.enrollmentAbort?"Waiting for approval\u2026":"Connect"});if(f.setAttr("title","Opens Connect in your browser to choose a collection"),f.addClass("mod-cta"),f.disabled=this.ctx.busy,f.onclick=()=>void this.ctx.perform(async()=>{this.enrollmentAbort?.abort();let p=new AbortController;this.enrollmentAbort=p;try{await this.ctx.host.connectSync.enroll({controlUrl:this.enrollmentControlUrl,mirrorName:this.enrollmentMirrorName,mode:this.enrollmentMode,selectiveSync:this.filePolicy(),...this.enrollmentCollectionId.trim()?{collectionId:this.enrollmentCollectionId.trim()}:{}},{signal:p.signal,onVerification:g=>{this.enrollmentVerification=g.verificationUri,this.ctx.message="",window.open(g.verificationUri,"_blank","noopener,noreferrer"),this.ctx.render()},onStatus:g=>{this.ctx.message=g.state==="waiting_for_approval"?"Waiting for approval in Connect\u2026":`Connect is retrying enrollment (attempt ${g.attempt}).`,this.ctx.render()}}),this.enrollmentVerification="";let m=await this.session.review(),h=m?.entries.reduce((g,b)=>g+(b.estimatedBytes??0),0)??0,y=m?.entries.length??0;this.ctx.message=`Connected. Review ${y} ${y===1?"item":"items"}${h?` \xB7 ${pr(h)}`:""} before syncing.`,this.ctx.render()}catch(m){if(!ty(m))throw m;this.enrollmentVerification="",this.ctx.message="Cancelled. No files synced."}finally{this.enrollmentAbort===p&&(this.enrollmentAbort=null)}}),this.enrollmentAbort){let p=d.createEl("button",{text:"Stop waiting"});p.onclick=()=>{this.enrollmentAbort?.abort(),this.enrollmentVerification="",this.ctx.message="Cancelled. No files synced.",this.ctx.render()}}}renderLocalAdoption(e){let t=this.ctx.host.connectSync.getAdoptionMarker(),n=t?this.ctx.host.connectSync.getAdoptionRecovery():null,i=!t||["waiting_for_approval","uploading"].includes(t.phase),s=i?this.adoptionPreview?.conflicts??[]:[],o=e.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});o.createEl("h3",{text:"Upload to Connect"}),o.createEl("p",{cls:"mdbase-muted",text:n?n.canReset?"This upload expired and its device authorization is missing. Reset setup to start again. Your files stay local.":n.canReconnect?"Device authorization is unavailable. Reconnect to the hosted collection through Connect. This vault stays protected until approval succeeds.":`Device authorization is unavailable. Restore Obsidian's secret storage, or reset setup after ${new Date(t?.session.expiresAt??"").toLocaleString()}.`:this.ctx.busy&&this.adoptionStage?this.adoptionStage:t?t.phase==="waiting_for_approval"?"Not connected yet. Approval is pending in Connect.":t.phase==="adopted"?"Collection is hosted. Finish connecting this device.":t.phase==="activating"?"Activation outcome is pending. Resume to check it safely.":s.length||this.adoptionFailed?"Approval received. Upload stopped; this vault is not connected yet.":"Approval received. Transfer is not running; resume to continue.":"This vault holds the collection. Upload it to Connect to sync it with other devices; Connect then holds the collection and this vault syncs a copy.",attr:{role:"status","aria-live":"polite"}});let a=this.enrollmentVerification||(!n&&t?.phase==="waiting_for_approval"?t.session.verificationUri:void 0);if(a){let u=o.createDiv({cls:"mdbase-approval-link"});u.createSpan({text:"Approval page: "});let d=u.createEl("a",{text:"Open Connect",href:a});d.setAttr("target","_blank"),d.setAttr("rel","noopener noreferrer")}if(t&&(this.enrollmentControlUrl=t.session.controlUrl,this.enrollmentMirrorName=t.session.requested.mirrorName??"Obsidian"),t){let u=this.ctx.disclosure(o,"adoption-details","Details");zt(u,"Collection",t.session.requested.collectionId),zt(u,"Phase",t.phase.replace(/_/g," ")),zt(u,"Connect",t.session.controlUrl);let d=this.ctx.host.connectSync.getSelectiveSync();zt(u,"Files",d.file_classes.length?d.file_classes.join(", "):"Markdown only")}else{Tt(o,"Device name",this.enrollmentMirrorName,d=>{this.enrollmentMirrorName=d});let u=this.ctx.disclosure(o,"adoption-options","Advanced");Tt(u,"Connect URL",this.enrollmentControlUrl,d=>{this.enrollmentControlUrl=d},{placeholder:wd}),this.renderFilePolicyControls(u)}!n&&i&&(this.adoptionPreview&&o.createEl("p",{cls:"mdbase-muted",text:`${this.adoptionPreview.records.toLocaleString()} notes \xB7 ${this.adoptionPreview.files.toLocaleString()} attachments`}),s.length&&(o.createEl("h4",{text:`${s.length} filename conflicts`}),this.renderAdoptionRenameReview(o,s))),n||o.createEl("p",{cls:"mdbase-form-description",text:"Sync starts only after the upload completes."});let c=o.createDiv({cls:"mdbase-actions mdbase-enrollment-actions"});if(!n&&i){let u=c.createEl("button",{text:"Check files"});u.disabled=this.ctx.busy,u.onclick=()=>void this.ctx.perform(async()=>{this.adoptionRenamePlan=null,this.adoptionPreview=await this.ctx.host.connectSync.previewAdoption(this.filePolicy()),this.ctx.message=this.adoptionPreview.conflicts.length?"Resolve the listed filename conflicts before continuing.":"Files checked. No filename conflicts."})}if(n&&!n.canReconnect){if(n.canReset){let u=c.createEl("button",{text:"Reset setup",cls:"mod-cta"});u.disabled=this.ctx.busy,u.onclick=()=>void this.ctx.perform(async()=>{this.filePolicyDraft=this.ctx.host.connectSync.getSelectiveSync(),await this.ctx.host.connectSync.resetExpiredAdoption(),this.enrollmentVerification="",this.ctx.message="Expired setup cleared. Your files and collection identity are unchanged. Start a new upload to approve this device again.",await this.ctx.refresh(!0)})}else{let u=c.createEl("button",{text:"Check again"});u.disabled=this.ctx.busy,u.onclick=()=>this.ctx.render()}return}if(t&&!n&&!["activating","adopted"].includes(t.phase)){let u=c.createEl("button",{text:"Cancel upload"});u.disabled=this.ctx.busy,u.onclick=()=>void this.ctx.perform(async()=>{await this.ctx.host.connectSync.cancelAdoption(),this.enrollmentVerification="",this.ctx.message="Upload cancelled. The collection is still local.",await this.ctx.refresh(!0)})}if(this.enrollmentAbort){let u=c.createEl("button",{text:t?.phase==="waiting_for_approval"?"Stop waiting":"Pause upload"});u.onclick=()=>{this.enrollmentAbort?.abort(),this.ctx.message="Upload paused. Resume when ready.",this.ctx.render()}}let l=c.createEl("button",{text:n?"Reconnect collection":t?"Resume upload":"Upload to Connect"});l.addClass("mod-cta"),l.disabled=this.ctx.busy||!n&&s.length>0,l.onclick=()=>void this.ctx.perform(async()=>{this.adoptionFailed=!1,this.adoptionStage="Checking files\u2026",this.enrollmentAbort?.abort();let u=new AbortController;this.enrollmentAbort=u;let d=y=>{this.enrollmentVerification=y.verificationUri,this.adoptionStage="Waiting for approval in Connect\u2026",this.ctx.message="Approve the upload in Connect.",this.ctx.render()},f=y=>{this.ctx.message=y.state==="waiting_for_approval"?"Waiting for upload approval in Connect\u2026":`Connect is retrying (attempt ${y.attempt}).`,this.ctx.render()},p=y=>{this.adoptionStage=y.stage==="checking"?"Checking files\u2026":y.stage==="uploading"?`Approval received. Uploading ${y.records?.toLocaleString()??""} notes\u2026`:y.stage==="activating"?"Activating hosted collection. Keep this vault open\u2026":"Finishing this device's connection\u2026",this.enrollmentVerification="",this.ctx.message="",this.ctx.render()},m=(y,g,b)=>{this.adoptionFileProgress=`${y} \xB7 ${pr(g)} of ${pr(b)}`,this.adoptionStage=`Uploading ${this.adoptionFileProgress}`,this.ctx.render()},h={signal:u.signal,onVerification:d,onStatus:f,onFileProgress:m,onProgress:p};try{n?await this.ctx.host.connectSync.reconnectAdoption(h):t?await this.ctx.host.connectSync.resumeAdoption(h):await this.ctx.host.connectSync.adoptLocalCollection({controlUrl:this.enrollmentControlUrl,mirrorName:this.enrollmentMirrorName,selectiveSync:this.filePolicy()},h),this.enrollmentVerification="",this.ctx.message="Collection hosted. This vault is now connected.",await this.ctx.refresh(!0)}catch(y){if(this.ctx.host.connectSync.getAdoptionMarker()?.phase!=="waiting_for_approval"&&(this.enrollmentVerification=""),!ty(y))throw this.adoptionFailed=!0,await this.ctx.host.connectSync.previewAdoption(this.filePolicy()).then(g=>{this.adoptionPreview=g}).catch(()=>{}),y;this.ctx.message="Upload paused. Resume when ready."}finally{this.adoptionStage="",this.enrollmentAbort===u&&(this.enrollmentAbort=null)}})}renderAdoptionRenameReview(e,t){let n=this.adoptionRenamePlan;e.createEl("p",{text:n?"Keep both files with distinct names. Nothing is merged or deleted. Link updates follow your Obsidian settings.":"Names must also be distinct on case-insensitive devices. Review suggested names, or rename the files yourself."});let i=e.createEl("ul",{cls:"mdbase-adoption-conflicts"}),s=n?n.renames.map(l=>[l.from,l.to]):t;for(let l of s){let u=i.createEl("li");l.forEach((d,f)=>{f&&u.appendText(n?" \u2192 ":" \u2194 "),u.createEl("code",{text:d})})}n?.manual.length&&e.createEl("p",{text:"Collection-resource conflicts need manual review: "+n.manual.map(l=>l.join(" \u2194 ")).join("; ")});let o=e.createDiv({cls:"mdbase-actions"});if(!n){let l=o.createEl("button",{text:"Review renames\u2026"});l.disabled=this.ctx.busy,l.onclick=()=>void this.ctx.perform(async()=>{this.adoptionRenamePlan=await this.ctx.host.connectSync.planAdoptionRenames(this.filePolicy())});return}let a=o.createEl("button",{text:`Rename ${n.renames.length} ${n.renames.length===1?"file":"files"}`,cls:"mod-cta"});a.disabled=this.ctx.busy||!n.renames.length,a.onclick=()=>void this.ctx.perform(async()=>{try{let l=await this.ctx.host.connectSync.applyAdoptionRenames(n,this.filePolicy(),(u,d)=>{this.adoptionStage=`Renaming ${u} of ${d} files\u2026`,this.ctx.render()});this.ctx.message=`Renamed ${l} ${l===1?"file":"files"}. Review the file check, then resume the upload.`}finally{this.adoptionStage="",this.adoptionRenamePlan=null,await this.ctx.host.connectSync.previewAdoption(this.filePolicy()).then(l=>{this.adoptionPreview=l}).catch(()=>{})}});let c=o.createEl("button",{text:"Cancel"});c.disabled=this.ctx.busy,c.onclick=()=>{this.adoptionRenamePlan=null,this.ctx.render()}}renderMirrorPreview(e,t){let n=e.createEl("section",{cls:"mdbase-transfer-review"}),i=n.createDiv({cls:"mdbase-transfer-heading"});i.createDiv().createEl("h3",{text:t.phase==="initial"?"First sync":"Changes"});let o=t.entries.reduce((p,m)=>p+(m.estimatedBytes??0),0);i.createSpan({cls:"mdbase-transfer-total",text:t.entries.length?`${t.entries.length} ${t.entries.length===1?"item":"items"}${o?` \xB7 ${pr(o)}`:""}`:"No changes"});let a=n.createDiv({cls:"mdbase-issue-controls"}),c=a.createEl("input",{type:"search",placeholder:"Search transfer paths"});c.setAttr("aria-label","Search transfer paths"),c.setAttr("data-focus-key","transfer-search"),c.value=this.transferQuery,c.oninput=()=>{this.transferQuery=c.value,this.transferPages.clear(),this.ctx.render()};let l=a.createEl("select");l.setAttr("aria-label","Filter transfers");for(let[p,m]of[["all","All changes"],["delete","Deletes"],["replace","Replacements"],["upload","Uploads"],["download","Downloads"],["attention","Needs attention"]])l.createEl("option",{value:p,text:m});l.value=this.transferFilter,l.onchange=()=>{this.transferFilter=l.value,this.transferPages.clear(),this.ctx.render()};let u=this.transferQuery.trim().toLowerCase(),d=t.entries.filter(p=>(!u||`${p.path} ${p.detail}`.toLowerCase().includes(u))&&(this.transferFilter==="all"||p.action===this.transferFilter||p.direction===this.transferFilter));d.length||n.createDiv({cls:"mdbase-muted",text:"No changes match these filters."}),n.createDiv({cls:"mdbase-muted",text:`Showing ${d.length} of ${t.entries.length} items. Approval always applies to the entire reviewed plan, not just these filters.`});let f=[{direction:"download",title:"Downloads"},{direction:"upload",title:"Uploads"},{direction:"attention",title:"Needs attention"}];for(let p of f){let m=d.filter(_=>_.direction===p.direction);if(!m.length)continue;let h=n.createEl("section",{cls:"mdbase-transfer-group"});h.setAttr("data-direction",p.direction);let y=h.createDiv({cls:"mdbase-transfer-group-heading"}),g=y.createSpan({cls:"mdbase-transfer-group-icon"});(0,Is.setIcon)(g,p.direction==="download"?"download":p.direction==="upload"?"upload":"circle-alert"),y.createEl("h4",{text:p.title}),y.createSpan({text:String(m.length),cls:"mdbase-transfer-count"});let b=h.createDiv({cls:"mdbase-transfer-ledger"}),v=Math.min(this.transferPages.get(p.direction)??0,Math.floor((m.length-1)/250)),S=v*250;for(let _ of m.slice(S,S+250)){let E=b.createDiv({cls:"mdbase-transfer-row"});E.createSpan({cls:"mdbase-transfer-action",text:_.action}).setAttr("data-action",_.action);let $=E.createDiv({cls:"mdbase-transfer-body"}),M=$.createDiv({cls:"mdbase-transfer-path"}),x=this.ctx.app.vault.getAbstractFileByPath(_.path)?_.path:null;if(x){let T=M.createEl("button",{cls:"mdbase-link-button mdbase-transfer-open"});T.createEl("code",{text:_.path}),T.setAttr("title",`Open ${_.path}`),T.onclick=()=>void this.ctx.host.openFileByPath(x)}else M.createEl("code",{text:_.path});_.estimatedBytes!==void 0&&M.createSpan({cls:"mdbase-transfer-size",text:pr(_.estimatedBytes)}),_.direction==="attention"||["rename","replace","delete"].includes(_.action)?$.createDiv({text:_.detail}):E.setAttr("title",_.detail);let q=_.recordId;if(q&&_.kind==="document"&&_.action==="update"&&x){let T=`${q}:${_.path}`,V=this.previewComparisons.get(T),P=E.createEl("button",{text:V?"Hide":this.loadingPreviewComparisons.has(T)?"Loading\u2026":"Compare"});P.setAttr("data-focus-key",`preview-compare-${T}`),P.disabled=this.loadingPreviewComparisons.has(T),P.onclick=()=>{V?(this.previewComparisons.delete(T),this.ctx.render()):this.loadPreviewComparison(T,q,_.path)},V&&this.renderConflictComparison($,V)}}if(m.length>250){let _=b.createDiv({cls:"mdbase-actions"});_.createSpan({cls:"mdbase-muted",text:`Showing ${S+1}\u2013${Math.min(S+250,m.length)} of ${m.length}`});let E=_.createEl("button",{text:`Previous ${p.title.toLowerCase()}`});E.disabled=v===0,E.setAttr("data-focus-key",`transfer-previous-${p.direction}`),E.onclick=()=>{this.transferPages.set(p.direction,v-1),this.ctx.render()};let k=_.createEl("button",{text:`Next ${p.title.toLowerCase()}`});k.disabled=S+250>=m.length,k.setAttr("data-focus-key",`transfer-next-${p.direction}`),k.onclick=()=>{this.transferPages.set(p.direction,v+1),this.ctx.render()}}}t.collisions.length?n.createDiv({cls:"mdbase-inline-error",text:"Colliding files and related moves are left unchanged. Independent files can still sync. Move or rename the obstruction, then review again."}):t.local_issues.length&&n.createDiv({cls:"mdbase-inline-message",text:t.plan.summary.blocking_issues>0?ry(t.plan,t.entries.length).message:"These diagnostics do not block synchronization. Document bytes are preserved unchanged."})}renderConflicts(e,t){let n=e.createEl("section",{cls:"mdbase-editor-section"});n.id="mdbase-sync-conflicts",n.createEl("h3",{text:"Conflicts"});for(let i of t.conflicts){let s=n.createDiv({cls:"mdbase-conflict-row"}),o=s.createDiv({cls:"mdbase-conflict-summary"});o.createEl("strong",{text:i.path??i.object_id}),o.createDiv({text:i.message});let a=s.createDiv({cls:"mdbase-actions"}),c=`${i.object_id}:${i.decision_id}`,l=this.conflictComparisons.get(c),u=a.createEl("button",{text:l?"Hide":this.loadingConflictComparisons.has(c)?"Loading\u2026":"Resolve\u2026"});if(u.setAttr("data-focus-key",`compare-${c}`),u.disabled=this.ctx.busy||this.loadingConflictComparisons.has(c),u.onclick=()=>{if(l){this.conflictComparisons.delete(c),this.ctx.render();return}this.loadConflictComparison(i,c)},l){for(let d of["local","remote"]){let f=a.createEl("button",{text:d==="local"?"Keep local":"Use hosted"});f.disabled=this.ctx.busy,f.onclick=()=>void this.resolveMirrorConflict(i,d,!1)}if(i.path){let d=a.createEl("button",{text:"Keep both"});d.disabled=this.ctx.busy,d.onclick=()=>void this.resolveMirrorConflict(i,"remote",!0)}this.renderConflictComparison(s,l)}}}async loadPreviewComparison(e,t,n){this.loadingPreviewComparisons.add(e),this.ctx.render();try{this.previewComparisons.set(e,await this.ctx.host.connectSync.recordComparison(t,n))}catch(i){this.ctx.message=Rt(i).message}finally{this.loadingPreviewComparisons.delete(e),this.ctx.render()}}async loadConflictComparison(e,t){this.loadingConflictComparisons.add(t),this.ctx.render();try{this.conflictComparisons.set(t,await this.ctx.host.connectSync.conflictComparison(e))}catch(n){this.session.reportProblem(n).code==="conflict_decision_stale"&&await this.session.refreshStatus()}finally{this.loadingConflictComparisons.delete(t),this.ctx.render()}}renderConflictComparison(e,t){let n=e.createDiv({cls:"mdbase-conflict-comparison"});if(t.entity==="record"){let s=Ox(t.local.document??"",t.remote.document??""),o=n.createDiv({cls:"mdbase-conflict-legend"});o.createSpan({text:"\u2212 Local only",cls:"is-local"}),o.createSpan({text:"+ Hosted only",cls:"is-remote"});let a=n.createEl("pre",{cls:"mdbase-conflict-diff"});for(let c of s.lines){let l=a.createEl("div",{cls:`is-${c.kind}`});l.createSpan({text:c.kind==="local"?"\u2212":c.kind==="remote"?"+":" "}),l.createSpan({text:c.value||" "})}s.truncated&&n.createDiv({cls:"mdbase-muted",text:"Diff shortened for a responsive review. Open the local note to inspect it in full."});return}let i=n.createDiv({cls:"mdbase-conflict-sides"});this.renderConflictSide(i,"Local",t.local),this.renderConflictSide(i,"Hosted",t.remote)}renderConflictSide(e,t,n){let i=e.createDiv({cls:"mdbase-conflict-side"});if(i.createEl("h4",{text:t}),n.state==="absent"){i.createDiv({cls:"mdbase-muted",text:"File is absent in this version."});return}if(n.path&&i.createEl("code",{text:n.path}),n.size!==void 0&&i.createDiv({text:`Size: ${pr(n.size)}`}),n.modifiedAt&&i.createDiv({text:`Modified: ${new Date(n.modifiedAt).toLocaleString()}`}),n.revision&&i.createDiv({cls:"mdbase-conflict-digest",text:`Digest: ${n.revision}`}),n.resourceUrl&&n.path&&/\.(?:avif|gif|jpe?g|png|svg|webp)$/i.test(n.path)){let s=i.createEl("img",{cls:"mdbase-conflict-image-preview"});s.src=n.resourceUrl,s.alt=`${t} preview of ${n.path}`}else t==="Hosted"&&i.createDiv({cls:"mdbase-muted",text:"Hosted binary preview is materialized only after you choose it."})}async resolveMirrorConflict(e,t,n){await this.ctx.perform(async()=>{await this.session.resolveConflict(e,t,n)&&this.conflictComparisons.delete(`${e.object_id}:${e.decision_id}`)})}renderLocalMirrorIssues(e,t){let n=e.createEl("section",{cls:"mdbase-editor-section"});n.createEl("h3",{text:"Local files needing attention"}),n.createEl("p",{text:"Review these file diagnostics. The sync preview identifies which issues block synchronization; a diagnostic alone does not mean syncing is paused."});for(let i of t.local_issues){let s=n.createDiv({cls:"mdbase-conflict-row"}),o=s.createDiv();o.createEl("strong",{text:i.path}),o.createDiv({text:i.message});let c=s.createDiv({cls:"mdbase-actions"}).createEl("button",{text:"Open file"});c.disabled=this.ctx.busy,c.onclick=()=>void this.ctx.host.openFileByPath(i.path)}}async refresh(){if(!this.session.isSyncing()){if(!this.ctx.host.getMirrorProfile()){if(!this.ctx.schema||this.enrollmentAbort)return;try{this.adoptionPreview=await this.ctx.host.connectSync.previewAdoption(this.filePolicy())}catch(e){this.ctx.message=Rt(e).message}return}await this.session.refreshStatus()}}};var Qe=require("obsidian");qt();function Fx(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Os(r){return typeof r=="number"&&Number.isFinite(r)?r:null}function ny(r,e,t=""){let n=t?` ${t}`:"";return r!==null&&e!==null?r===e?`${r}${n}`:`${r}\u2013${e}${n}`:r!==null?`\u2265 ${r}${n}`:e!==null?`\u2264 ${e}${n}`:null}function sn(r){return typeof r=="string"?r:typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r):JSON.stringify(r)??""}function iy(r){let e=sn(r);return e.length>24?`${e.slice(0,23)}\u2026`:e}function jx(r){let e=typeof r.type=="string"?r.type:"any",t=[];if(e==="enum"&&Array.isArray(r.values)){let n=r.values.map(iy);t.push(n.length>3?`${n.slice(0,3).join(", ")}, +${n.length-3}`:n.join(", ")||"no values")}if(e==="integer"||e==="number"){let n=ny(Os(r.min),Os(r.max));n&&t.push(n)}if(e==="list"){let n=ny(Os(r.min_length),Os(r.max_length),"items");n&&t.push(n),Fx(r.items)&&typeof r.items.type=="string"&&t.push(`of ${r.items.type}`)}else{let n=ny(Os(r.min_length),Os(r.max_length),"chars");n&&t.push(n)}if(typeof r.pattern=="string"&&r.pattern&&t.push(`/${iy(r.pattern)}/`),e==="link"&&typeof r.target=="string"&&r.target&&t.push(`\u2192 ${r.target}`),e==="object"&&Fx(r.fields)){let n=Object.keys(r.fields).length;t.push(`${n} ${n===1?"field":"fields"}`)}return r.default!==void 0&&t.push(`default ${iy(r.default)}`),r.unique===!0&&t.push("unique"),r.deprecated===!0&&t.push("deprecated"),t}function qx(r,e,t){if(e!==void 0&&sn(e)===r)return e;let n=r.trim()!==""&&Number.isFinite(Number(r)),i=r==="true"||r==="false",s=o=>t.length>0&&t.every(a=>typeof a===o);return n&&(typeof e=="number"||typeof e!="boolean"&&s("number"))?Number(r):i&&(typeof e=="boolean"||typeof e!="number"&&s("boolean"))?r==="true":r}function Bx(r,e){if(r==="")return{};if(e==="integer"||e==="number"){let t=Number(r);return Number.isFinite(t)?e==="integer"&&!Number.isInteger(t)?{error:"Default must be a whole number."}:{value:t}:{error:"Default must be a number."}}return e==="boolean"?r==="true"?{value:!0}:r==="false"?{value:!1}:{error:"Default must be true or false."}:{value:r}}var Un=require("@codemirror/commands"),Vn=require("@codemirror/language"),Kt=require("@codemirror/state"),$t=require("@codemirror/view"),Bn=require("@lezer/highlight"),ej=Vn.StreamLanguage.define({startState:()=>({section:"start"}),copyState:r=>({...r}),token(r,e){return r.sol()&&r.match(/^---\s*$/)?(e.section=e.section==="start"?"yaml":"body","meta"):e.section==="body"?(r.skipToEnd(),null):(e.section==="start"&&(e.section="yaml"),r.eatSpace()?null:r.match("#")?(r.skipToEnd(),"comment"):r.match(/^-(?=\s|$)/)?"punctuation":r.match(/^(?:[^\s:#'"[\]{},][^:#]*?|"[^"]*"|'[^']*')(?=\s*:(?:\s|$))/)?"propertyName":r.match(/^"(?:[^"\\]|\\.)*"?/)||r.match(/^'(?:[^']|'')*'?/)?"string":r.match(/^-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?(?=[\s,\]}]|$)/)?"number":r.match(/^(?:true|false|null|~)(?=[\s,\]}]|$)/)?"atom":r.match(/^[:[\]{},|>]/)?"punctuation":(r.eatWhile(/[^\s#:,[\]{}]/),r.current()===""&&r.next(),"string"))}}),tj=Vn.HighlightStyle.define([{tag:Bn.tags.propertyName,color:"var(--text-accent)"},{tag:Bn.tags.string,color:"var(--text-normal)"},{tag:Bn.tags.number,color:"var(--color-orange)"},{tag:Bn.tags.atom,color:"var(--color-purple)"},{tag:Bn.tags.comment,color:"var(--text-faint)",fontStyle:"italic"},{tag:Bn.tags.meta,color:"var(--text-faint)"},{tag:Bn.tags.punctuation,color:"var(--text-muted)"}]),Ux=Kt.StateEffect.define(),rj=Kt.StateField.define({create:()=>$t.Decoration.none,update(r,e){let t=r.map(e.changes);for(let n of e.effects){if(!n.is(Ux))continue;let i=new Kt.RangeSetBuilder,s=[...new Set(n.value.map(o=>o.line).filter(o=>o!==null&&o>=1&&o<=e.state.doc.lines))].sort((o,a)=>o-a);for(let o of s){let a=e.state.doc.line(o),c=n.value.find(l=>l.line===o)?.severity??"error";i.add(a.from,a.from,$t.Decoration.line({class:`mdbase-yaml-problem-line is-${c}`}))}t=i.finish()}return t},provide:r=>$t.EditorView.decorations.from(r)}),Ed=class{constructor(e){this.editable=new Kt.Compartment;this.applyingExternalChange=!1;this.view=new $t.EditorView({state:Kt.EditorState.create({doc:e.doc,extensions:[(0,$t.lineNumbers)(),(0,Un.history)(),Vn.indentUnit.of(" "),Kt.EditorState.tabSize.of(2),$t.keymap.of([...Un.defaultKeymap,...Un.historyKeymap,Un.indentWithTab]),ej,(0,Vn.syntaxHighlighting)(tj),rj,$t.EditorView.lineWrapping,this.editable.of(this.editability(e.readOnly)),$t.EditorView.contentAttributes.of({"aria-labelledby":e.labelledBy,"data-focus-key":"yaml-editor",spellcheck:"false"}),$t.EditorView.updateListener.of(t=>{t.docChanged&&!this.applyingExternalChange&&e.onChange(t.state.doc.toString())})]})}),this.dom=this.view.dom,this.dom.addClass("mdbase-yaml-editor")}get value(){return this.view.state.doc.toString()}setValue(e){if(e!==this.value){this.applyingExternalChange=!0;try{this.view.dispatch({changes:{from:0,to:this.view.state.doc.length,insert:e}})}finally{this.applyingExternalChange=!1}}}setReadOnly(e){this.view.dispatch({effects:this.editable.reconfigure(this.editability(e))})}setProblems(e){this.view.dispatch({effects:Ux.of(e)})}revealLine(e){if(e<1||e>this.view.state.doc.lines)return;let t=this.view.state.doc.line(e).from;this.view.dispatch({selection:{anchor:t},scrollIntoView:!0}),this.view.focus()}destroy(){this.view.destroy()}editability(e){return[Kt.EditorState.readOnly.of(e),$t.EditorView.editable.of(!e)]}};function Vx(r,e=2){let t=r.match(/line (\d+)/i)??r.match(/\((\d+):\d+\)/);return t?Number(t[1])+e-1:null}function sy(r,e){if(!e)return null;let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^\\s*(?:-\\s+)?["']?${t}["']?\\s*:`),s=r.split(` -`).findIndex(o=>n.test(o));return s===-1?null:s+1}var Ad=class{constructor(e){this.ctx=e;this.editorMode="design";this.query="";this.selectedPath=null;this.model=null;this.originalModel=null;this.yamlDraft="";this.dirty=!1;this.migrationPlan=null;this.allowLossy=!1;this.statsCache=null;this.impact=null;this.impactVersion=0;this.impactTimer=null;this.showAllMatches=!1;this.pendingFieldReveal=null;this.sessionDrafts=new Set;this.yamlEditor=null;this.yamlProblemTimer=null;this.draftSaveTimer=null;this.fieldQuery="";this.expandedFields=new Set;this.fieldIds=new WeakMap;this.nextFieldId=1;this.typeSelectionVersion=0}async onSchemaLoaded(e,t){if(this.selectedPath&&!this.typeEntries().some(n=>n.filePath===this.selectedPath)&&(this.selectedPath=null,this.model=null,this.originalModel=null),!this.selectedPath&&this.typeEntries().length&&!Qe.Platform.isMobile&&(this.selectedPath=this.typeEntries()[0].filePath),this.selectedPath&&(!this.model||e)){if(this.dirty&&await this.flushTypeDraft(),!t())return;await this.selectType(this.selectedPath,!1)}}onRecordsLoaded(e){(e||!this.impact)&&this.scheduleImpact(0)}afterRender(e){if(!this.pendingFieldReveal)return;let t=e.querySelector(`[data-field-id="${this.pendingFieldReveal}"]`);t&&(t.scrollIntoView({block:"nearest"}),(!e.contains(e.ownerDocument.activeElement)||e.ownerDocument.activeElement===e.ownerDocument.body)&&t.querySelector("summary")?.focus({preventScroll:!0}),t.addClass("is-revealed")),this.pendingFieldReveal=null}getState(){return{selectedPath:this.selectedPath,editorMode:this.editorMode,query:this.query,fieldQuery:this.fieldQuery}}async setState(e){for(let t of["query","fieldQuery"])typeof e[t]=="string"&&(this[t]=e[t].slice(0,2e3));typeof e.selectedPath=="string"&&e.selectedPath!==this.selectedPath&&(await this.leaveCurrentType(),this.selectedPath=e.selectedPath,this.model=null,this.originalModel=null)}restoreEditorMode(e){e==="yaml"&&this.editorMode!=="yaml"&&this.switchEditorMode("yaml")}async dispose(){this.impactTimer!==null&&window.clearTimeout(this.impactTimer),this.yamlProblemTimer!==null&&window.clearTimeout(this.yamlProblemTimer),this.impactVersion++,await this.flushTypeDraft(),this.yamlEditor?.destroy(),this.yamlEditor=null}async openTypeField(e,t){this.ctx.destination="types",(e!==this.selectedPath||!this.model)&&await this.selectType(e),!(!this.model||this.selectedPath!==e)&&(t&&this.revealField(t),this.ctx.render())}revealField(e){if(!this.model)return;let t=e.split(".").filter(Boolean),n=t.shift()?.replace(/\[\]$/g,"")??"",i=this.model.fields.find(s=>s.name===n)?.definition;if(i){this.editorMode="design",this.fieldQuery="",this.expandedFields.add(this.fieldId(i));for(let s of t){let o=s.replace(/\[\]$/g,""),a=Se(i.items)?i.items:i,c=Se(a.fields)?a.fields[o]:void 0;if(!Se(c))break;a!==i&&this.expandedFields.add(this.fieldId(a)),i=c,this.expandedFields.add(this.fieldId(i))}this.pendingFieldReveal=this.fieldId(i)}}currentStats(){let e=this.ctx.host.getIssues(),t=this.ctx.schema?.types??null,n=this.statsCache;if(n&&n.records===this.ctx.records&&n.types===t&&n.issues===e)return n;let i=this.ctx.records&&this.ctx.schema?$x(this.ctx.records,this.ctx.schema.config,this.ctx.schema.types):new Map;return this.statsCache={records:this.ctx.records,types:t,issues:e,recordTypes:i,stats:xx(i,e)},this.statsCache}scheduleImpact(e=400){this.impactTimer!==null&&window.clearTimeout(this.impactTimer),this.impactTimer=window.setTimeout(()=>{this.impactTimer=null,this.computeImpact().then(t=>{t!==void 0&&(this.impact=t,this.updateImpactRegions())})},e)}async computeImpact(){let e=++this.impactVersion,t=this.editorMode==="yaml"?this.modelFromYamlDraft():null;if(t&&"error"in t)return{error:t.error};let n=t?.model??this.model;if(!n||!this.ctx.schema||!this.ctx.records||n.specProfile!=="v0.3"||n.readOnlyReason)return null;let i=this.selectedPath?[...this.ctx.schema.types.values()].find(o=>o.filePath===this.selectedPath)?.name??null:null,s=await Ex({records:this.ctx.records,config:this.ctx.schema.config,types:this.ctx.schema.types,draft:n,savedName:i,filePath:this.selectedPath,isCurrent:()=>e===this.impactVersion});return e===this.impactVersion&&s!==null?s:void 0}updateImpactRegions(){let e=this.ctx.containerEl.querySelector(".mdbase-match-preview");e&&(e.empty(),this.fillMatchPreview(e));let t=this.ctx.containerEl.querySelector("[data-disclosure='type-matching'] > summary");t&&(t.textContent=this.matchingLabel());let n=this.ctx.containerEl.querySelector(".mdbase-impact");n&&(n.empty(),this.fillImpact(n));let i=this.ctx.containerEl.querySelector(".mdbase-type-editor-pane"),s=i?.querySelector(".mdbase-draft-bar");i&&s&&this.model&&(s.remove(),this.renderDraftBar(i,this.model))}createNewType(){this.ctx.destination="types",this.createType()}async editType(e){this.ctx.destination="types",await this.selectType(e)}typeEntries(){return this.ctx.schema?[...this.ctx.schema.types.values()].sort((e,t)=>e.name.localeCompare(t.name)):[]}renderSetup(e){let t=e.createDiv({cls:"mdbase-empty-state mdbase-setup"});if(this.ctx.host.getMirrorProfile()){t.createEl("h2",{text:"Waiting for the first sync"}),t.createEl("p",{text:"Types appear here once the hosted collection has synced."});let s=t.createEl("button",{text:"Open sync",cls:"mod-cta"});s.onclick=()=>this.ctx.showDestination("sync");return}t.createEl("h2",{text:"Set up mdbase"});let n=t.createDiv({cls:"mdbase-setup-choices"}),i=(s,o,a,c)=>{let l=n.createDiv({cls:"mdbase-setup-choice"}),u=l.createDiv();u.createEl("strong",{text:s}),u.createDiv({cls:"mdbase-muted",text:o});let d=l.createEl("button",{text:s,cls:a?"mod-cta":""});d.disabled=this.ctx.busy,d.onclick=c};i("Start a collection","This vault holds the collection. You can upload it to Connect later.",!0,()=>{this.ctx.perform(async()=>{await this.ctx.host.initializeCollection(),await this.ctx.refresh(!0)})}),i("Copy from Connect","Connect holds the collection. This vault syncs a copy.",!1,()=>{this.ctx.showDestination("sync")})}render(e){if(!this.ctx.schema){this.renderSetup(e);return}if(this.ctx.schema.config.spec_version.startsWith("0.2.")&&this.renderLegacyBanner(e),!this.typeEntries().length&&!this.model){let n=e.createDiv({cls:"mdbase-empty-state"});n.createEl("h2",{text:"Add your first type"}),n.createEl("p",{text:"Install ready-made types and application contracts from mdbase-contracts, or design your own type."});let i=n.createDiv({cls:"mdbase-actions"}),s=i.createEl("button",{text:"Browse ready-made types",cls:"mod-cta"});s.disabled=this.ctx.busy||this.ctx.schema.config.spec_version.startsWith("0.2.")||this.ctx.host.getMirrorProfile()!==null,s.onclick=()=>void this.ctx.perform(()=>this.ctx.host.openContractCatalog());let o=i.createEl("button",{text:"Design a custom type"});o.disabled=this.ctx.schema.config.spec_version.startsWith("0.2.")||this.ctx.host.getMirrorProfile()?.mode==="read_only",o.onclick=()=>void this.createType();return}let t=e.createDiv({cls:"mdbase-types-layout"});this.model&&t.addClass("has-selection"),this.renderTypeList(t),this.renderTypeEditor(t)}renderLegacyBanner(e){let t=e.createDiv({cls:"mdbase-legacy-banner"}),n=t.createDiv();if(n.createEl("strong",{text:"Read-only \xB7 v0.2 collection"}),n.createEl("p",{text:"Migrate to edit types."}),!this.migrationPlan){let i=t.createEl("button",{text:"Review migration"});i.disabled=this.ctx.busy||this.ctx.host.getMirrorProfile()!==null,i.onclick=()=>void this.ctx.perform(async()=>{this.migrationPlan=await this.ctx.host.analyzeMigration(),this.ctx.render()})}this.ctx.host.getMirrorProfile()&&t.createDiv({cls:"mdbase-form-description",text:"Hosted resources must be migrated at the collection authority."}),this.migrationPlan&&this.renderMigrationReview(e,this.migrationPlan)}renderMigrationReview(e,t){let n=e.createDiv({cls:"mdbase-migration-review"}),i=n.createDiv({cls:"mdbase-section-header"});i.createEl("h3",{text:"Migration review"}),i.createSpan({cls:"mdbase-spec-badge",text:`${t.sourceVersion} \u2192 ${t.targetVersion}`});let s=n.createDiv({cls:"mdbase-status-list"});zt(s,"Files replaced",String(t.operations.length)),zt(s,"Type definitions",String(t.typeSummaries.length)),zt(s,"Record reads verified",String(t.recordsVerified)),t.recordsSkipped&&zt(s,"Records skipped",String(t.recordsSkipped)),zt(s,"Record files rewritten","0"),zt(s,"Recovery backup",t.backupLocation);let o=n.createDiv({cls:"mdbase-review-list"});t.diagnostics.length||o.createDiv({cls:"mdbase-review-ok",text:"No migration diagnostics."});for(let u of t.diagnostics.slice(0,250)){let d=o.createDiv({cls:"mdbase-review-item"});d.setAttr("data-severity",u.severity),d.createDiv({cls:"mdbase-review-code",text:`${u.severity} \xB7 ${u.path}`}),d.createDiv({text:u.message})}if(t.diagnostics.length>250&&o.createDiv({cls:"mdbase-form-description",text:`Showing 250 of ${t.diagnostics.length} diagnostics.`}),!t.applicable){let u=n.createEl("label",{cls:"mdbase-consent"}),d=u.createEl("input",{type:"checkbox"});d.checked=this.allowLossy,d.onchange=()=>{this.allowLossy=d.checked,this.ctx.render()},u.createSpan({text:"I reviewed the lossy diagnostics and want to apply this migration."})}let a=n.createDiv({cls:"mdbase-actions"}),c=a.createEl("button",{text:"Apply migration"});c.addClass("mod-warning"),c.disabled=this.ctx.busy||!t.applicable&&!this.allowLossy,c.onclick=()=>void this.ctx.perform(async()=>{await this.ctx.host.applyMigration(t,this.allowLossy),this.migrationPlan=null,this.allowLossy=!1,this.model=null,this.originalModel=null,await this.ctx.refresh(!0)});let l=a.createEl("button",{text:"Close review"});l.onclick=()=>{this.migrationPlan=null,this.ctx.render()}}renderTypeList(e){let t=e.createDiv({cls:"mdbase-type-list-pane"}),n=t.createDiv({cls:"mdbase-pane-header"});n.createEl("h2",{text:"Types"});let i=this.ctx.iconButton(n,"download","Browse ready-made types");i.disabled=this.ctx.busy||this.ctx.schema?.config.spec_version.startsWith("0.2.")===!0||this.ctx.host.getMirrorProfile()!==null,i.onclick=()=>void this.ctx.perform(()=>this.ctx.host.openContractCatalog());let s=this.ctx.schema?.config.spec_version.startsWith("0.2.")??!0?"Migrate to v0.3 to create types":this.ctx.host.getMirrorProfile()?.mode==="read_only"?"Read-only mirror":"",o=this.ctx.iconButton(n,"plus",s?`Create type \xB7 ${s}`:"Create type");o.disabled=!!s,o.onclick=()=>void this.createType();let a=t.createEl("input",{type:"search"});a.addClass("mdbase-type-search"),a.placeholder="Search types",a.setAttr("aria-label","Search types"),a.setAttr("data-focus-key","type-search"),a.value=this.query,a.oninput=()=>{this.query=a.value,this.ctx.render();let f=this.ctx.containerEl.querySelector(".mdbase-type-search");f?.focus(),f?.setSelectionRange(f.value.length,f.value.length)};let c=t.createDiv({cls:"mdbase-type-list"});c.setAttr("data-scroll-key","type-list");let l=this.query.trim().toLowerCase(),u=this.typeEntries().filter(f=>`${f.name} ${f.description??""} ${f.filePath}`.toLowerCase().includes(l));if(!u.length){c.createDiv({cls:"mdbase-empty-list",text:l?"No matching types.":"No type definitions."});return}let{stats:d}=this.currentStats();for(let f of u){let p=c.createEl("button",{cls:"mdbase-type-row"});f.filePath===this.selectedPath&&p.addClass("is-active"),p.setAttr("aria-current",f.filePath===this.selectedPath?"true":"false");let m=p.createDiv({cls:"mdbase-type-name-line"});if(m.createSpan({cls:"mdbase-type-name",text:f.name}),f.filePath===this.selectedPath?this.dirty:this.ctx.host.loadTypeDraft(f.filePath)!==null){let g=m.createSpan({cls:"mdbase-unsaved-dot"});g.setAttr("aria-label","Unsaved changes"),g.setAttr("title","Unsaved changes")}let y=d.get(f.name);if(this.ctx.records){let g=p.createDiv({cls:"mdbase-type-meta"}),b=y?.notes??0;g.createSpan({text:`${b.toLocaleString()} ${b===1?"note":"notes"}`}),y?.issues&&g.createSpan({cls:"mdbase-type-issues",text:`${y.issues.toLocaleString()} ${y.issues===1?"issue":"issues"}`})}p.onclick=()=>void this.selectType(f.filePath)}}renderTypeEditor(e){let t=e.createDiv({cls:"mdbase-type-editor-pane"});if(t.setAttr("data-scroll-key","type-editor"),!this.model){t.createDiv({cls:"mdbase-empty-state"}).createEl("p",{text:"Select a type"});return}let n=this.ctx.host.getMirrorProfile()?.mode==="read_only",i=this.model.specProfile==="v0.2"||n||!!this.model.readOnlyReason,s=this.model.readOnlyReason??(n?"Read-only mirror. Reconnect with write access to edit.":"Migrate this v0.2 collection to edit types."),o=t.createDiv({cls:"mdbase-editor-header"}),a=this.ctx.iconButton(o,"arrow-left","Back to type list");a.addClass("mdbase-mobile-back"),a.onclick=()=>void this.leaveCurrentType().then(()=>{this.selectedPath=null,this.model=null,this.originalModel=null,this.ctx.render()});let c=o.createDiv({cls:"mdbase-editor-heading"});c.createDiv({cls:"mdbase-editor-title-line"}).createEl("h2",{text:this.model.name||"Untitled type"}),c.createDiv({cls:"mdbase-editor-path",text:this.selectedPath??"New type"});let u=o.createDiv({cls:"mdbase-editor-actions"});if(this.selectedPath){let p=this.selectedPath,m=this.ctx.iconButton(u,"file-code","Open source");m.onclick=()=>void this.ctx.host.openFileByPath(p)}if(this.selectedPath){let p=this.model.name,m=u.createEl("button",{text:"New note"});m.disabled=i||this.ctx.busy,m.onclick=()=>void this.ctx.host.createNoteFromType(p),this.renderStaleDrafts(t)}i&&t.createDiv({cls:"mdbase-readonly-note",text:s});let d=t.createDiv({cls:"mdbase-mode-switch"});d.setAttr("role","tablist");for(let[p,m]of[["design","Design"],["yaml","YAML"]]){let h=d.createEl("button",{text:m});h.id=`mdbase-mode-${p}`,h.setAttr("role","tab"),h.setAttr("aria-selected",String(this.editorMode===p)),this.editorMode===p&&h.addClass("is-active"),h.onclick=()=>this.switchEditorMode(p)}let f=t.createDiv({cls:"mdbase-editor-document"});f.setAttr("data-scroll-key","type-document"),this.editorMode==="design"?this.renderDesignEditor(f,this.model,i):this.renderYamlEditor(f,i),this.dirty&&!i&&this.renderDraftBar(t,this.model)}renderStaleDrafts(e){if(!this.selectedPath||!this.originalModel)return;let t=this.selectedPath,n=this.ctx.host.loadTypeDraft(t),i=[...this.ctx.host.getArchivedTypeDrafts(t),...n&&n.sourceRevision!==(this.originalModel.sourceRevision??null)?[n]:[]];for(let s of i){let o=e.createDiv({cls:"mdbase-recovery-card"});o.createDiv({text:`An older draft from ${new Date(s.updatedAt).toLocaleString()} is available. The source changed; it will not be applied automatically.`});let a=o.createEl("button",{text:"Compare draft"});a.onclick=()=>{let u=new Qe.Modal(this.ctx.app);u.titleEl.setText("Current source and recovered draft");let d=s.yamlDraft;if(d===void 0)try{d=mt(Ea(s.model),s.model.body)}catch{d=JSON.stringify(s.model,null,2)}u.contentEl.createEl("h3",{text:"Current source"}),u.contentEl.createEl("pre",{text:this.originalModel?mt(Ea(this.originalModel),this.originalModel.body):this.yamlDraft}),u.contentEl.createEl("h3",{text:"Recovered draft (read-only)"}),u.contentEl.createEl("pre",{text:d}),u.contentEl.createEl("p",{text:"Copy the parts you want into the current definition, then review before saving."}),u.open()};let c=o.createEl("button",{text:"Export draft"});c.onclick=()=>void this.ctx.perform(async()=>{let u="mdbase-draft-recovery";this.ctx.app.vault.getAbstractFileByPath(u)||await this.ctx.app.vault.createFolder(u);let d=await this.ctx.app.vault.create(`${u}/draft-${crypto.randomUUID()}.txt`,s.yamlDraft??JSON.stringify(s.model,null,2));this.ctx.message=`Exported recovery draft to ${d.path}. The original draft is still retained.`});let l=o.createEl("button",{text:"Discard old draft"});l.onclick=()=>{let u=new Qe.Modal(this.ctx.app);u.titleEl.setText("Discard this recovered draft?"),u.contentEl.createEl("p",{text:"This removes the saved recovery copy, not the current source or your current edits. Export it first if you might need it."}),u.contentEl.createEl("button",{text:"Cancel"}).onclick=()=>u.close(),u.contentEl.createEl("button",{text:"Discard old draft",cls:"mod-warning"}).onclick=()=>{u.close(),this.ctx.perform(async()=>{s===n?await this.ctx.host.clearTypeDraft(t):await this.ctx.host.discardArchivedTypeDraft(s)})},u.open()}}}renderDraftBar(e,t){let n=_a(this.originalModel,t),s=wa(t,{knownTypes:this.typeEntries().map(h=>h.name),contracts:this.ctx.schema?.contracts.values()}).filter(h=>h.severity==="error").length,o=n.filter(h=>h.risk==="high").length,a=this.newlyFailing(),c=this.editorMode==="yaml"?this.yamlProblems().filter(h=>h.severity==="error").length:0,l=e.createDiv({cls:"mdbase-draft-bar"}),u=l.createDiv({cls:"mdbase-draft-summary"}),d=this.editorMode==="yaml"?c:s;u.setAttr("data-tone",d?"error":a||o?"warning":"normal"),u.createSpan({text:d?`${d} ${d===1?"error":"errors"}`:a?`${a} ${a===1?"note":"notes"} would fail`:o?`${o} high-impact ${o===1?"change":"changes"}`:"Unsaved changes"});let f=l.createDiv({cls:"mdbase-actions"});if(this.editorMode==="design"){let h=f.createEl("button",{text:"Review"});h.onclick=()=>{let g=this.ctx.containerEl.querySelector("#mdbase-section-review")?.closest("details");g&&(g.open=!0),this.ctx.render(),this.ctx.containerEl.querySelector("#mdbase-section-review")?.scrollIntoView({block:"nearest"})}}let p=f.createEl("button",{text:"Discard"});p.onclick=()=>void this.discardCurrentType();let m=f.createEl("button",{text:"Save"});m.addClass("mod-cta"),m.disabled=(this.editorMode==="design"?s>0:c>0)||this.ctx.busy,m.onclick=()=>void this.saveCurrentType()}newlyFailing(){return!this.dirty||!this.impact||"error"in this.impact?0:this.impact.impact.failing.filter(e=>e.isNew).length}matchingLabel(){let e=this.impact&&!("error"in this.impact)?this.impact.impact.matched.length:this.savedTypeName()?this.currentStats().stats.get(this.savedTypeName()??"")?.notes:void 0;return e===void 0||!this.ctx.records?"Matching":`Matching \xB7 ${e.toLocaleString()} ${e===1?"note":"notes"}`}savedTypeName(){return!this.selectedPath||!this.ctx.schema?null:[...this.ctx.schema.types.values()].find(e=>e.filePath===this.selectedPath)?.name??null}fillMatchPreview(e){let t=this.impact,n,i=[],s=[];if(t&&!("error"in t))({matched:n,added:i,removed:s}=t.impact);else{let d=this.savedTypeName();if(!this.ctx.records||!d||t&&"error"in t&&this.dirty){e.createDiv({cls:"mdbase-muted",text:this.ctx.records?t&&"error"in t?"Fix errors to preview matching notes.":"Save the type to preview matching notes.":"Counting notes\u2026"});return}n=[...this.currentStats().recordTypes].filter(([,f])=>f.includes(d)).map(([f])=>f)}let o=e.createDiv({cls:"mdbase-match-summary"});o.createSpan({text:`${n.length.toLocaleString()} ${n.length===1?"note matches":"notes match"}`}),i.length&&o.createSpan({cls:"mdbase-match-added",text:`${i.length} added`}),s.length&&o.createSpan({cls:"mdbase-match-removed",text:`${s.length} no longer match`});let a=new Set(i),c=[...i.map(d=>({path:d,change:"added"})),...s.map(d=>({path:d,change:"removed"})),...n.filter(d=>!a.has(d)).map(d=>({path:d,change:null}))];if(!c.length)return;let l=this.showAllMatches?200:5,u=e.createDiv({cls:"mdbase-match-list"});for(let d of c.slice(0,l)){let f=u.createEl("button",{cls:"mdbase-match-row"});d.change&&(f.setAttr("data-change",d.change),f.createSpan({cls:"mdbase-match-marker",text:d.change==="added"?"+":"\u2212",attr:{"aria-label":d.change==="added"?"Added":"No longer matches"}})),f.createSpan({text:d.path}),f.setAttr("title",`Open ${d.path}`),f.onclick=()=>void this.ctx.host.openFileByPath(d.path)}if(c.length>5){let d=e.createEl("button",{cls:"mdbase-link-button",text:this.showAllMatches?"Show fewer":c.length>200?`Show 200 of ${c.length.toLocaleString()}`:`Show all ${c.length.toLocaleString()}`});d.onclick=()=>{this.showAllMatches=!this.showAllMatches,e.empty(),this.fillMatchPreview(e)}}}fillImpact(e){let t=this.impact;if(!t){e.createDiv({cls:"mdbase-muted",text:this.ctx.records?"Checking notes\u2026":"Counting notes\u2026"});return}if("error"in t){e.createDiv({cls:"mdbase-muted",text:"Fix errors to check existing notes."});return}let{impact:n}=t,i=n.failing.filter(l=>l.isNew),s=n.failing.length-i.length,o=e.createDiv({cls:"mdbase-impact-heading"});o.setAttr("data-tone",i.length?"warning":"normal"),o.createEl("strong",{text:i.length?`${i.length} ${i.length===1?"note":"notes"} would fail`:"No notes newly fail"});let a=[`${n.matched.length.toLocaleString()} ${n.matched.length===1?"note":"notes"} checked`];if(n.fixed&&a.push(`${n.fixed} fixed`),s&&a.push(`${s} already failing`),o.createSpan({cls:"mdbase-muted",text:a.join(" \xB7 ")}),!i.length)return;let c=e.createDiv({cls:"mdbase-impact-list"});for(let l of i.slice(0,10)){let u=c.createDiv({cls:"mdbase-impact-row"}),d=u.createEl("button",{cls:"mdbase-link-button",text:l.path});d.onclick=()=>void this.ctx.host.openFileByPath(l.path,l.issues[0]?.field),u.createSpan({cls:"mdbase-muted",text:`${l.issues[0]?.message??""}${l.issues.length>1?` \xB7 +${l.issues.length-1} more`:""}`})}i.length>10&&c.createDiv({cls:"mdbase-muted",text:`${i.length-10} more notes`})}renderDesignEditor(e,t,n){let i=wa(t,{knownTypes:this.typeEntries().map(T=>T.name),contracts:this.ctx.schema?.contracts.values()}),s=e.createEl("section",{cls:"mdbase-editor-section"});s.id="mdbase-section-identity";let o=Tt(s,"Name",t.name,T=>{t.name=T,this.markDirty()});o.disabled=n;let a=Tt(s,"Description",t.description,T=>{t.description=T,this.markDirty()},{multiline:!0});a.disabled=n;let c=this.ctx.disclosure(e,"type-options","Options"),l=c.createDiv({cls:"mdbase-form-row"}),u=l.createEl("label",{text:"Display field"}),d=l.createEl("select");u.htmlFor=d.id="mdbase-display-field",d.createEl("option",{value:"",text:"Use the file name"});for(let T of t.fields)d.createEl("option",{value:T.name,text:T.name||"Unnamed field"});t.displayNameKey&&!t.fields.some(T=>T.name===t.displayNameKey)&&d.createEl("option",{value:t.displayNameKey,text:`${t.displayNameKey} \xB7 missing`}),d.value=t.displayNameKey,d.onchange=()=>{t.displayNameKey=d.value,this.markDirty()},d.disabled=n;let f=c.createEl("label",{cls:"mdbase-checkbox-row"}),p=f.createEl("input",{type:"checkbox"});p.checked=t.strictMode===!0,p.disabled=n,p.onchange=()=>{t.strictMode=p.checked,this.markDirty()},f.createSpan({text:"Reject undeclared fields"});let m=this.ctx.disclosure(e,"type-matching",this.matchingLabel());m.id="mdbase-section-membership",this.fillMatchPreview(m.createDiv({cls:"mdbase-match-preview"}));let h=Tt(m,"Path glob",t.matchPathGlob,T=>{t.matchPathGlob=T,this.markDirty()},{placeholder:"Projects/**/*.md"});h.disabled=n;let y=Tt(m,"Fields present",t.matchFieldsPresent,T=>{t.matchFieldsPresent=T,this.markDirty()},{description:"Comma-separated frontmatter keys."});y.disabled=n;let g=Tt(m,"Where",t.matchWhere,T=>{t.matchWhere=T,this.markDirty()},{multiline:!0,description:"YAML predicate, including contains and nested equality conditions.",placeholder:`tags: - contains: task`});g.disabled=n;let b=e.createEl("section",{cls:"mdbase-editor-section"});b.id="mdbase-section-fields";let v=b.createDiv({cls:"mdbase-section-header"});v.createEl("h3",{text:"Fields"});let S=v.createDiv({cls:"mdbase-section-actions"});if(this.expandedFields.size){let T=this.ctx.iconButton(S,"fold-vertical","Collapse all fields");T.onclick=()=>{this.expandedFields.clear(),this.ctx.render()}}let _=this.ctx.iconButton(S,"plus","Add field");if(_.disabled=n,_.onclick=()=>{let T={type:"string"};t.fields.push({name:"",definition:T}),this.expandedFields.add(this.fieldId(T)),this.markDirty(!0)},t.fields.length>6||this.fieldQuery){let P=b.createDiv({cls:"mdbase-field-toolbar"}).createDiv({cls:"mdbase-field-toolbar-actions"}).createEl("input",{type:"search"});P.placeholder="Filter fields",P.setAttr("aria-label","Filter fields"),P.setAttr("data-focus-key","field-search"),P.value=this.fieldQuery,P.oninput=()=>{this.fieldQuery=P.value,this.ctx.render()}}let E=b.createDiv({cls:"mdbase-fields"}),k=this.fieldQuery.trim().toLowerCase(),$=t.fields.filter(T=>!k||this.fieldMatches(T.name,T.definition,k));for(let T of $){let V=t.fields.indexOf(T);this.renderFieldRow(E,T,V,n)}$.length||E.createDiv({cls:"mdbase-empty-list",text:t.fields.length?"No fields match this filter.":"No fields declared."}),m.parentElement&&e.appendChild(m.parentElement),c.parentElement&&e.appendChild(c.parentElement);let x=Tt(c,"Path pattern",t.pathPattern,T=>{t.pathPattern=T,this.markDirty()},{placeholder:"Notes/{title}.md"});if(x.disabled=n,this.renderContractEditor(e,t,n),!this.dirty&&!i.length)return;let q=this.ctx.disclosure(e,"type-review","Changes",i.some(T=>T.severity==="error"));if(q.id="mdbase-section-review",this.dirty&&this.fillImpact(q.createDiv({cls:"mdbase-impact"})),i.length){let T=q.createDiv({cls:"mdbase-diagnostic-summary"}),V=i.filter(C=>C.severity==="error").length,P=i.length-V;T.createEl("strong",{text:`${V} ${V===1?"error":"errors"} \xB7 ${P} ${P===1?"warning":"warnings"}`});for(let C of i.slice(0,12)){let Be=T.createDiv({cls:"mdbase-diagnostic-item"});Be.setAttr("data-severity",C.severity),Be.createEl("code",{text:C.path}),Be.createSpan({text:C.message})}}if(this.dirty){let T=q.createEl("ul");for(let V of _a(this.originalModel,t))T.createEl("li",{text:V.summary}).setAttr("data-risk",V.risk)}}renderContractEditor(e,t,n){let i=this.ctx.disclosure(e,"type-applications","Applications");i.addClass("mdbase-contracts-section"),i.id="mdbase-section-applications";let s=[...this.ctx.schema?.contracts.values()??[]],o=new Set(t.implementations.map(c=>`${c.contract}@${c.version}`)),a=s.filter(c=>!o.has(Ms(c)));s.length||i.createDiv({cls:"mdbase-contract-empty",text:"No application contracts installed."});for(let c of t.implementations){let l=s.find(u=>u.id===c.contract&&u.version===c.version);this.renderContractImplementation(i,t,c,l,n)}if(a.length){let c=i.createDiv({cls:"mdbase-contract-add"}),l=c.createEl("label",{text:"Installed contract"}),u=c.createEl("select");l.htmlFor=u.id=`mdbase-contract-${Math.random().toString(36).slice(2)}`;for(let f of a)u.createEl("option",{value:Ms(f),text:`${f.id} \xB7 ${f.version}`});let d=c.createEl("button",{text:"Add contract"});d.disabled=n,d.onclick=()=>{let f=a.find(p=>Ms(p)===u.value);if(f)try{px(t,f),this.markDirty(!0)}catch(p){new Qe.Notice(p instanceof Error?p.message:String(p))}}}}renderContractImplementation(e,t,n,i,s){let o=e.createEl("article",{cls:"mdbase-contract-implementation"}),a=o.createDiv({cls:"mdbase-contract-header"}),c=a.createDiv();c.createEl("strong",{text:n.contract}),c.createSpan({cls:"mdbase-contract-version",text:n.version});let l=a.createEl("button",{text:"Remove"});if(l.disabled=s,l.onclick=()=>{hx(t,n.contract,n.version),this.markDirty(!0)},!i){o.createDiv({cls:"mdbase-contract-unavailable",text:"This exact contract is not installed in the collection. Restore it or remove this implementation before saving."});return}let u=ya(i),d=ga(t),f=u.filter(b=>Ts(n,b)),p=u.filter(b=>b.required),m=p.filter(b=>Ts(n,b)).length,h=o.createEl("details");h.open=mx.reference===v),_=ba(b,S),E=g.createDiv({cls:`mdbase-contract-mapping-row ${_.level}`}),k=E.createDiv({cls:"mdbase-contract-field-definition"});k.createEl("code",{text:b.reference}),k.createSpan({cls:b.required?"mdbase-contract-required":"mdbase-contract-optional",text:b.required?"Required":"Optional"}),k.createEl("small",{text:b.description||yx(b.schema)});let $=E.createEl("select");$.setAttr("aria-label",`${n.contract} ${b.reference} source field`),$.setAttr("aria-invalid",_.level==="error"?"true":"false"),$.disabled=s,$.createEl("option",{value:"",text:b.required?"Choose a source field":"Not exposed"});for(let x of d){let q=ba(b,x),T=$.createEl("option",{value:x.reference,text:`${x.reference} \xB7 ${x.type}${q.level==="warning"?" \xB7 review":""}`});T.disabled=q.level==="error"}$.value=v,$.onchange=()=>{mx(n,b.reference,$.value||void 0),this.markDirty(!0)};let M=E.createDiv({cls:"mdbase-contract-mapping-status"});M.createEl("strong",{text:_.label}),M.createEl("small",{text:_.message})}if(i.binding_schema){let b=o.createEl("details",{cls:"mdbase-contract-settings"});b.open=!!n.binding;let v=b.createEl("summary");v.createSpan({text:"Contract settings"}),v.createSpan({cls:"mdbase-contract-summary",text:n.binding?"Configured":"Optional"});let S=b.createDiv({cls:"mdbase-contract-settings-body"});if(S.createEl("p",{cls:"mdbase-form-description",text:"Control how compatible applications interpret this type. Values follow the contract's schema."}),n.binding)this.renderContractSchemaValue(S,i.binding_schema,n.binding,_=>{Se(_)&&(zm(n,_),this.markDirty())},"Settings",s);else{let _=S.createEl("button",{text:"Configure settings"});_.disabled=s,_.onclick=()=>{let E=va(i.binding_schema);Se(E)&&(zm(n,E),this.markDirty(!0))}}}}renderContractSchemaValue(e,t,n,i,s,o){if(jn(t)==="object"){let c=Se(n)?n:{},l=e.createEl("fieldset",{cls:"mdbase-contract-schema-object"});l.createEl("legend",{text:s});let u=Se(t.properties)?t.properties:{},d=new Set(Array.isArray(t.required)?t.required.map(String):[]),f=[...new Set([...d,...Object.keys(c).filter(m=>m in u)])];for(let m of f){let h=u[m];if(!Se(h))continue;let y=l.createDiv({cls:"mdbase-contract-schema-field"}),g=typeof h.description=="string"?h.description:void 0;y.createEl("label",{text:`${m}${d.has(m)?" \xB7 required":""}`}),g&&y.createEl("small",{text:g}),this.renderContractSchemaControl(y,h,c[m],b=>{i({...c,[m]:b})},m,o)}f.length||l.createDiv({cls:"mdbase-empty-list",text:"No settings declared."});let p=Object.keys(u).filter(m=>!f.includes(m));if(p.length){let m=l.createDiv({cls:"mdbase-contract-schema-add"}),h=m.createEl("select");for(let g of p)h.createEl("option",{value:g,text:g});let y=m.createEl("button",{text:"Add optional setting"});y.disabled=o,y.onclick=()=>{let g=h.value,b=u[g];Se(b)&&i({...c,[g]:va(b)})}}return}this.renderContractSchemaControl(e,t,n,i,s,o)}renderContractSchemaControl(e,t,n,i,s,o){let a=jn(t);if(Array.isArray(t.enum)){let l=e.createEl("select");l.setAttr("aria-label",s);for(let u of t.enum)l.createEl("option",{value:JSON.stringify(u),text:String(u)});l.value=JSON.stringify(n),l.disabled=o,l.onchange=()=>i(JSON.parse(l.value));return}if(a==="array"){let l=Se(t.items)?t.items:{type:"string"},u=Array.isArray(n)?n:[],d=e.createDiv({cls:"mdbase-contract-schema-array"});for(let[p,m]of u.entries()){let h=d.createDiv({cls:"mdbase-contract-schema-array-item"});h.createSpan({text:`${p+1}.`}),this.renderContractSchemaControl(h,l,m,g=>{i(u.map((b,v)=>v===p?g:b))},`${s} item ${p+1}`,o);let y=h.createEl("button",{text:"Remove"});y.disabled=o||u.length<=(typeof t.minItems=="number"?t.minItems:0),y.onclick=()=>i(u.filter((g,b)=>b!==p))}let f=e.createEl("button",{text:`Add ${s.toLowerCase()} item`});f.disabled=o||typeof t.maxItems=="number"&&u.length>=t.maxItems,f.onclick=()=>i([...u,va(l)]);return}if(a==="object"){this.renderContractSchemaValue(e,t,n,i,s,o);return}if(a==="boolean"){let l=e.createEl("input",{type:"checkbox"});l.checked=n===!0,l.disabled=o,l.setAttr("aria-label",s),l.onchange=()=>i(l.checked);return}let c=e.createEl("input",{type:a==="number"||a==="integer"?"number":"text"});c.setAttr("aria-label",s),c.value=n==null?"":typeof n=="string"?n:typeof n=="number"||typeof n=="boolean"?String(n):"",c.disabled=o,c.oninput=()=>i(a==="number"||a==="integer"?Number(c.value):c.value)}renderFieldRow(e,t,n,i){let s=this.model?.fields??[];this.renderFieldDefinition(e,t.definition,{name:t.name,nameLabel:`Field ${n+1} name`,onNameInput:o=>{t.name=o,this.markDirty()},required:t.definition.required===!0,onRequiredChange:o=>{t.definition.required=o,this.markDirty()},onRemove:()=>{this.model?.fields.splice(n,1),this.markDirty(!0)},onMove:o=>{let a=n+o;a<0||a>=s.length||([s[n],s[a]]=[s[a],s[n]],this.pendingFieldReveal=this.fieldId(t.definition),this.markDirty(!0))},canMoveUp:n>0,canMoveDown:n{i.open?this.expandedFields.add(s):this.expandedFields.delete(s)};let a=n.name||n.staticLabel||"Unnamed field",c=i.createEl("summary",{cls:"mdbase-field-summary"});c.setAttr("data-focus-key",`field-${s}-summary`);let l=c.createSpan({cls:"mdbase-field-chevron"});l.setAttr("aria-hidden","true"),(0,Qe.setIcon)(l,"chevron-right"),c.createSpan({cls:"mdbase-field-summary-name",text:a}),c.createSpan({cls:"mdbase-field-summary-type",text:Qm($a(t))});let u=c.createSpan({cls:"mdbase-field-summary-rules"}),d=()=>{u.textContent=jx(t).join(" \xB7 ")};d(),n.required&&c.createSpan({cls:"mdbase-field-summary-rule",text:"Required"}),n.onMove&&!n.readOnly&&c.addEventListener("keydown",y=>{!y.altKey||y.key!=="ArrowUp"&&y.key!=="ArrowDown"||(y.preventDefault(),y.key==="ArrowUp"&&n.canMoveUp&&n.onMove?.(-1),y.key==="ArrowDown"&&n.canMoveDown&&n.onMove?.(1))});let f=i.createDiv({cls:"mdbase-field-row"});if(n.staticLabel)f.createDiv({cls:"mdbase-field-role",text:n.staticLabel});else{let y=f.createEl("input",{type:"text",cls:"mdbase-field-name-control"});y.setAttr("data-focus-key",`field-${s}-name`),y.setAttr("aria-label",n.nameLabel),y.placeholder="Field name",y.value=n.name??"",y.disabled=n.readOnly,n.onNameInput&&(y.oninput=()=>n.onNameInput?.(y.value)),n.onNameCommit&&(y.onchange=()=>n.onNameCommit?.(y.value,y))}let p=f.createEl("select",{cls:"mdbase-field-type-control"});p.setAttr("data-focus-key",`field-${s}-type`),p.setAttr("aria-label",`${n.name||n.staticLabel||"Field"} type`);for(let y of kx)p.createEl("option",{value:y,text:Qm(y)});p.value=$a(t),p.disabled=n.readOnly,p.onchange=()=>{t.type=p.value,p.value==="list"&&!Se(t.items)&&(t.items={type:"string"}),p.value==="object"&&!Se(t.fields)&&(t.fields={}),p.value==="enum"&&!Array.isArray(t.values)&&(t.values=[]),p.value!=="integer"&&p.value!=="number"&&(delete t.min,delete t.max),p.value!=="string"&&delete t.pattern,["string","list"].includes(p.value)||(delete t.min_length,delete t.max_length),delete t.default,this.markDirty(!0)};let m=f.createEl("input",{type:"text",cls:"mdbase-field-description-control"});if(m.setAttr("data-focus-key",`field-${s}-description`),m.setAttr("aria-label",`${n.name||n.staticLabel||"Field"} description`),m.placeholder="Description",m.value=typeof t.description=="string"?t.description:"",m.disabled=n.readOnly,m.oninput=()=>{m.value?t.description=m.value:delete t.description,this.markDirty()},n.onRequiredChange){let y=f.createEl("label",{cls:"mdbase-field-required"}),g=y.createEl("input",{type:"checkbox"});g.setAttr("data-focus-key",`field-${s}-required`),g.checked=n.required===!0,g.disabled=n.readOnly,g.onchange=()=>n.onRequiredChange?.(g.checked),y.createSpan({text:"Required"})}if(n.onRemove||n.onMove){let y=this.ctx.iconButton(f,"more-horizontal",`${a} actions`);y.addClass("mdbase-field-menu"),y.setAttr("data-focus-key",`field-${s}-menu`),y.disabled=n.readOnly,y.onclick=g=>{let b=new Qe.Menu;if(n.onMove&&(b.addItem(v=>v.setTitle("Move up").setIcon("arrow-up").setDisabled(!n.canMoveUp).onClick(()=>n.onMove?.(-1))),b.addItem(v=>v.setTitle("Move down").setIcon("arrow-down").setDisabled(!n.canMoveDown).onClick(()=>n.onMove?.(1)))),n.onRemove&&(n.onMove&&b.addSeparator(),b.addItem(v=>{v.setTitle("Remove field").setIcon("trash-2").onClick(()=>n.onRemove?.()),v.setWarning(!0)})),g.detail===0){let v=y.getBoundingClientRect();b.showAtPosition({x:v.left,y:v.bottom})}else b.showAtMouseEvent(g)}}let h=$a(t);this.renderConstraintControls(i,t,h,n,d),h==="enum"&&this.renderEnumFieldDetails(i,t,n,d),h==="link"&&this.renderLinkFieldDetails(i,t,n),h==="list"&&this.renderListFieldDetails(i,t,n),h==="object"&&this.renderObjectFieldDetails(i,t,n)}renderConstraintControls(e,t,n,i,s){let a=n==="integer"||n==="number"?[["min","Minimum"],["max","Maximum"]]:n==="string"?[["min_length","Min length"],["max_length","Max length"]]:n==="list"?[["min_length","Min items"],["max_length","Max items"]]:[],c=!["list","object","any","link"].includes(n);if(!a.length&&n!=="string"&&!c)return;let l=e.createDiv({cls:"mdbase-field-details mdbase-field-constraints"}),u=i.name||i.staticLabel||"Field",d=this.fieldId(t);for(let[g,b]of a){let v=l.createDiv({cls:"mdbase-constraint"}),S=v.createEl("label",{text:b}),_=v.createEl("input",{type:"number"});_.id=`mdbase-${d}-${g}`,S.htmlFor=_.id,_.setAttr("data-focus-key",`field-${d}-${g}`),_.setAttr("aria-label",`${u} ${b.toLowerCase()}`),(g.endsWith("length")||n==="integer")&&(_.step="1"),g.endsWith("length")&&(_.min="0"),_.value=typeof t[g]=="number"?String(t[g]):"",_.disabled=i.readOnly,_.oninput=()=>{let E=_.value.trim()===""?NaN:Number(_.value);Number.isFinite(E)?t[g]=E:delete t[g],s(),this.markDirty()}}if(n==="string"){let g=l.createDiv({cls:"mdbase-constraint mdbase-constraint-wide"}),b=g.createEl("label",{text:"Pattern"}),v=g.createEl("input",{type:"text"});v.id=`mdbase-${d}-pattern`,b.htmlFor=v.id,v.setAttr("data-focus-key",`field-${d}-pattern`),v.setAttr("aria-label",`${u} pattern`),v.placeholder="Regular expression",v.spellcheck=!1,v.value=typeof t.pattern=="string"?t.pattern:"",v.disabled=i.readOnly,v.oninput=()=>{v.value?t.pattern=v.value:delete t.pattern,s(),this.markDirty()}}if(!c)return;let f=l.createDiv({cls:"mdbase-constraint mdbase-constraint-wide"}),p=f.createEl("label",{text:"Default"}),m=`mdbase-${d}-default`;if(p.htmlFor=m,n==="enum"||n==="boolean"){let g=f.createEl("select");g.id=m,g.setAttr("data-focus-key",`field-${d}-default`),g.createEl("option",{value:"",text:"None"});let b=n==="boolean"?[!0,!1]:Array.isArray(t.values)?t.values:[];for(let[S,_]of b.entries())g.createEl("option",{value:String(S),text:sn(_)});let v=b.findIndex(S=>JSON.stringify(S)===JSON.stringify(t.default));t.default!==void 0&&v===-1?(g.createEl("option",{value:"missing",text:`${sn(t.default)} \xB7 not allowed`}),g.value="missing"):g.value=v===-1?"":String(v),g.disabled=i.readOnly,g.onchange=()=>{g.value===""?delete t.default:g.value!=="missing"&&(t.default=b[Number(g.value)]),s(),this.markDirty()};return}let h=f.createEl("input",{type:"text"});h.id=m,h.setAttr("data-focus-key",`field-${d}-default`),h.setAttr("aria-label",`${u} default`),h.placeholder=n==="date"?"YYYY-MM-DD":n==="time"?"HH:MM":"None",h.value=t.default===void 0?"":sn(t.default),h.disabled=i.readOnly;let y=f.createDiv({cls:"mdbase-constraint-error"});h.oninput=()=>{let g=Bx(h.value,n);y.textContent=g.error??"",h.toggleClass("is-invalid",!!g.error),!g.error&&(g.value===void 0?delete t.default:t.default=g.value,s(),this.markDirty())}}fieldId(e){let t=this.fieldIds.get(e);if(t)return t;let n=`field-${this.nextFieldId}`;return this.nextFieldId+=1,this.fieldIds.set(e,n),n}fieldMatches(e,t,n){return`${e} ${$a(t)} ${typeof t.description=="string"?t.description:""}`.toLowerCase().includes(n)||Se(t.items)&&this.fieldMatches("item",t.items,n)?!0:Se(t.fields)?Object.entries(t.fields).some(([s,o])=>Se(o)&&this.fieldMatches(s,o,n)):!1}renderEnumFieldDetails(e,t,n,i){let s=e.createDiv({cls:"mdbase-field-details mdbase-enum-values"}),o=n.name||n.staticLabel||"Enum",a=this.fieldId(t);s.createDiv({cls:"mdbase-field-children-label",text:"Allowed values"});let c=Array.isArray(t.values)?t.values:[];!Array.isArray(t.values)&&!n.readOnly&&(t.values=c);let l=s.createDiv({cls:"mdbase-enum-list"});l.setAttr("role","list");let u=new Set(c.map(f=>typeof f)).size>1;for(let[f,p]of c.entries()){let m=l.createDiv({cls:"mdbase-enum-row"});m.setAttr("role","listitem");let h=m.createEl("input",{type:"text"});h.setAttr("data-focus-key",`field-${a}-value-${f}`),h.setAttr("aria-label",`${o} allowed value ${f+1}`),h.value=sn(p),h.disabled=n.readOnly,h.oninput=()=>{c[f]=qx(h.value,p,c.filter((g,b)=>b!==f)),i(),this.markDirty()},h.onkeydown=g=>{g.key==="Enter"&&(g.preventDefault(),c.splice(f+1,0,""),this.ctx.pendingFocusKey=`field-${a}-value-${f+1}`,this.markDirty(!0))},u&&m.createSpan({cls:"mdbase-enum-kind",text:typeof p});for(let[g,b,v]of[["arrow-up","Move value up",-1],["arrow-down","Move value down",1]]){let S=this.ctx.iconButton(m,g,`${b}: ${sn(p)}`);S.disabled=n.readOnly||f+v<0||f+v>=c.length,S.onclick=()=>{[c[f],c[f+v]]=[c[f+v],c[f]],this.markDirty(!0)}}let y=this.ctx.iconButton(m,"x",`Remove value ${sn(p)}`);y.disabled=n.readOnly,y.onclick=()=>{c.splice(f,1),this.markDirty(!0)}}let d=s.createEl("button",{cls:"mdbase-link-button",text:"Add value"});d.disabled=n.readOnly,d.onclick=()=>{c.push(""),this.ctx.pendingFocusKey=`field-${a}-value-${c.length-1}`,this.markDirty(!0)}}renderLinkFieldDetails(e,t,n){let i=e.createDiv({cls:"mdbase-field-details mdbase-field-options"}),s=this.fieldId(t),o=i.createEl("label",{text:"Target type"}),a=i.createEl("select");a.setAttr("data-focus-key",`field-${s}-target`),a.setAttr("aria-label",`${n.name||n.staticLabel||"Link"} target type`),a.createEl("option",{value:"",text:"Any type"});let c=typeof t.target=="string"?t.target:"";for(let d of this.typeEntries())a.createEl("option",{value:d.name,text:d.name});c&&!this.typeEntries().some(d=>d.name===c)&&a.createEl("option",{value:c,text:`${c} \xB7 missing`}),a.value=c,a.disabled=n.readOnly,a.onchange=()=>{a.value?t.target=a.value:delete t.target,this.markDirty()},o.htmlFor=a.id=`mdbase-${s}-target`;let l=i.createEl("label",{cls:"mdbase-field-required"}),u=l.createEl("input",{type:"checkbox"});u.setAttr("data-focus-key",`field-${s}-exists`),u.checked=t.validate_exists===!0,u.disabled=n.readOnly,u.onchange=()=>{t.validate_exists=u.checked,this.markDirty()},l.createSpan({text:"Validate target exists"})}renderListFieldDetails(e,t,n){let i=e.createDiv({cls:"mdbase-field-children"});i.createDiv({cls:"mdbase-field-children-label",text:"List items"});let s=Se(t.items)?t.items:{type:"any"};!Se(t.items)&&!n.readOnly&&(t.items=s),this.renderFieldDefinition(i,s,{staticLabel:"Item",nameLabel:"List item",readOnly:n.readOnly,depth:n.depth+1})}renderObjectFieldDetails(e,t,n){let i=e.createDiv({cls:"mdbase-field-children"});i.createDiv({cls:"mdbase-field-children-label",text:"Object fields"});let s=Se(t.fields)?t.fields:{};!Se(t.fields)&&!n.readOnly&&(t.fields=s);let o=i.createDiv({cls:"mdbase-nested-fields"}),a=i.createEl("button",{cls:"mdbase-link-button",text:"Add nested field"});a.disabled=n.readOnly,a.onclick=()=>{let l=Cx(s);_d(s,l,{type:"string"}),this.expandedFields.add(this.fieldId(s[l])),this.markDirty(!0)};let c=Object.entries(s).filter(l=>Se(l[1]));if(!c.length){o.createDiv({cls:"mdbase-empty-list",text:"No nested fields."});return}for(let[l,[u,d]]of c.entries()){let f=u;this.renderFieldDefinition(o,d,{name:f,nameLabel:`${f} nested field name`,onNameCommit:(p,m)=>{let h=p.trim();if(!h){new Qe.Notice("Nested field name is required."),m.value=f;return}if(h!==f&&Object.prototype.hasOwnProperty.call(s,h)){new Qe.Notice(`Nested field already exists: ${h}`),m.value=f;return}h!==f&&(delete s[f],_d(s,h,d),f=h,this.markDirty())},required:d.required===!0,onRequiredChange:p=>{d.required=p,this.markDirty()},onRemove:()=>{delete s[f],this.markDirty(!0)},onMove:p=>{let m=Object.keys(s),h=m.indexOf(f),y=h+p;if(h===-1||y<0||y>=m.length)return;[m[h],m[y]]=[m[y],m[h]];let g=m.map(b=>[b,s[b]]);for(let b of m)delete s[b];for(let[b,v]of g)Se(v)&&_d(s,b,v);this.pendingFieldReveal=this.fieldId(d),this.markDirty(!0)},canMoveUp:l>0,canMoveDown:lthis.onYamlInput(s.value)}}ensureYamlEditor(e){try{return this.yamlEditor?(this.yamlEditor.setValue(this.yamlDraft),this.yamlEditor.setReadOnly(e)):this.yamlEditor=new Ed({doc:this.yamlDraft,readOnly:e,labelledBy:"mdbase-mode-yaml",onChange:t=>this.onYamlInput(t)}),this.yamlEditor.setProblems(this.yamlProblems()),this.yamlEditor}catch(t){return console.error("mdbase: YAML editor unavailable",t),this.yamlEditor=null,null}}onYamlInput(e){this.yamlDraft=e,this.markDirty(!1),this.yamlProblemTimer!==null&&window.clearTimeout(this.yamlProblemTimer),this.yamlProblemTimer=window.setTimeout(()=>{this.yamlProblemTimer=null;let t=this.yamlProblems();this.yamlEditor?.setProblems(t);let n=this.ctx.containerEl.querySelector(".mdbase-yaml-problems");n&&(n.empty(),this.fillYamlProblems(n,t))},250)}fillYamlProblems(e,t=this.yamlProblems()){if(!(!this.dirty||!t.length))for(let n of t.slice(0,20)){let i=e.createEl("button",{cls:"mdbase-yaml-problem"});if(i.setAttr("data-severity",n.severity),i.createSpan({cls:"mdbase-yaml-problem-line-number",text:n.line?`Line ${n.line}`:"Type"}),i.createSpan({text:n.message}),i.disabled=n.line===null,n.line!==null){let s=n.line;i.onclick=()=>this.yamlEditor?.revealLine(s)}}}async leaveCurrentType(){this.dirty&&await this.flushTypeDraft(),this.yamlEditor?.destroy(),this.yamlEditor=null,this.impact=null,this.showAllMatches=!1}async selectType(e,t=!0){t&&e!==this.selectedPath&&await this.leaveCurrentType();let n=++this.typeSelectionVersion,i=await this.ctx.host.loadTypeModel(e);if(n!==this.typeSelectionVersion)return;let s=this.ctx.host.loadTypeDraft(e),o=s?.version===1&&s.sourceRevision===(i.sourceRevision??null),a=o?qn(s.model):i;this.selectedPath=e,this.model=a,this.originalModel=qn(i),this.yamlDraft=o&&s.yamlDraft!==void 0?s.yamlDraft:`${mt(Ea(i),i.body)} -`,this.dirty=!bd(this.originalModel,a),this.editorMode=o&&s.editorMode==="yaml"?"yaml":"design",this.editorMode==="yaml"&&(this.dirty=!0),o&&this.dirty?this.sessionDrafts.has(e)||(this.ctx.message=`Recovered unsaved changes for ${e}.`):s&&!o&&(this.ctx.message=`An older draft for ${e} was kept, but the source changed. The current file is shown.`),this.scheduleImpact(0),this.ctx.render()}async createType(){await this.leaveCurrentType(),this.typeSelectionVersion+=1;let e=this.ctx.host.loadTypeDraft(null),t=e?.version===1?qn(e.model):Hm();this.selectedPath=null,this.model=t,this.originalModel=null,this.yamlDraft=e?.yamlDraft??"",this.dirty=!0,e&&!this.sessionDrafts.has("__new__")&&(this.ctx.message="Recovered an unsaved new type."),this.editorMode=e?.editorMode??"design",this.scheduleImpact(0),this.ctx.render()}switchEditorMode(e){if(!(!this.model||e===this.editorMode)){if(e==="yaml")try{this.yamlDraft=`${mt(Ea(this.model),this.model.body)} -`}catch(t){new Qe.Notice(t instanceof Error?t.message:String(t));return}else if(!this.readYamlDraftIntoModel())return;this.editorMode=e,e==="design"&&(this.yamlEditor?.destroy(),this.yamlEditor=null),this.scheduleImpact(0),this.ctx.render()}}modelFromYamlDraft(){let e=Me(this.yamlDraft);if(!e.hasFrontmatter)return{error:"Type YAML must start with a --- frontmatter block.",line:1};if(e.error)return{error:`Invalid YAML: ${e.error.split(` -`)[0].replace(/:$/,"").replace(/ at line \d+, column \d+$/,"")}`,line:Vx(e.error)};if(e.frontmatter.kind!=="mdbase.type")return{error:"Canonical v0.3 type YAML requires kind: mdbase.type.",line:sy(this.yamlDraft,"kind")??2};try{let t=gd(e.frontmatter,e.body,this.model?.name||"type");return this.model?.sourceRevision&&(t.sourceRevision=this.model.sourceRevision),{model:t}}catch(t){return{error:t instanceof Error?t.message:String(t),line:null}}}yamlProblems(){let e=this.modelFromYamlDraft();return"error"in e?[{line:e.line??null,message:e.error,severity:"error"}]:wa(e.model,{knownTypes:this.typeEntries().map(t=>t.name),contracts:this.ctx.schema?.contracts.values()}).map(t=>{let n=t.path.startsWith("fields.")?t.path.slice(7).split(/[.[]/)[0]:t.path==="identity.displayNameKey"?"name_field":t.path.split(".").pop()??"";return{line:sy(this.yamlDraft,n),message:t.message,severity:t.severity==="error"?"error":"warning"}})}readYamlDraftIntoModel(){let e=this.modelFromYamlDraft();return"error"in e?(new Qe.Notice(e.error),e.line&&this.yamlEditor?.revealLine(e.line),!1):(this.model=e.model,!0)}async saveCurrentType(){if(!this.model||this.model.specProfile!=="v0.3"||this.model.readOnlyReason||this.editorMode==="yaml"&&!this.readYamlDraftIntoModel())return;let t=wa(this.model,{knownTypes:this.typeEntries().map(a=>a.name),contracts:this.ctx.schema?.contracts.values()}).filter(a=>a.severity==="error");if(t.length){this.ctx.message=`${t.length} ${t.length===1?"error must":"errors must"} be fixed before saving.`,this.ctx.render(),new Qe.Notice(t[0].message);return}let n=_a(this.originalModel,this.model).filter(a=>a.risk==="high"),i=await this.computeImpact();i!==void 0&&(this.impact=i);let s=this.impact&&!("error"in this.impact)?this.impact.impact.failing.filter(a=>a.isNew).map(a=>a.path):[];if(n.length||s.length){let a=n.length?n:_a(this.originalModel,this.model).filter(l=>l.risk!=="safe");if(!await new xc(this.ctx.app).confirm(a,s))return}let o=this.model;await this.flushTypeDraft(),await this.ctx.perform(async()=>{let a=this.selectedPath,c=await this.ctx.host.saveTypeModel(o,a,this.originalModel?.sourceRevision);await this.ctx.host.clearTypeDraft(a),a!==c.path&&await this.ctx.host.clearTypeDraft(c.path),this.selectedPath=c.path,this.originalModel=qn(o),this.dirty=!1,this.ctx.message=`Saved ${c.path}.`,await this.ctx.refresh(!0)})}markDirty(e=!1){let t=this.dirty;if(this.dirty=this.editorMode==="yaml"?!0:!bd(this.originalModel,this.model),this.scheduleTypeDraftSave(),this.scheduleImpact(),this.dirty&&!t&&(this.ctx.message=""),e||t!==this.dirty){this.ctx.render();return}let n=this.ctx.containerEl.querySelector(".mdbase-type-editor-pane"),i=n?.querySelector(".mdbase-draft-bar");if(n&&i&&this.model){i.remove(),this.renderDraftBar(n,this.model);let s=n.querySelector(".mdbase-editor-title-line h2");s&&(s.textContent=this.model.name||"Untitled type")}}scheduleTypeDraftSave(){this.draftSaveTimer!==null&&window.clearTimeout(this.draftSaveTimer),this.draftSaveTimer=window.setTimeout(()=>{this.draftSaveTimer=null,this.flushTypeDraft()},2e3)}async flushTypeDraft(){if(this.draftSaveTimer!==null&&(window.clearTimeout(this.draftSaveTimer),this.draftSaveTimer=null),!this.model)return;if(!this.dirty){let t=this.ctx.host.loadTypeDraft(this.selectedPath);t&&t.sourceRevision===(this.originalModel?.sourceRevision??null)&&await this.ctx.host.clearTypeDraft(this.selectedPath);return}this.sessionDrafts.add(this.selectedPath??"__new__");let e={version:1,path:this.selectedPath,sourceRevision:this.originalModel?.sourceRevision??null,model:qn(this.model),editorMode:this.editorMode,yamlDraft:this.editorMode==="yaml"?this.yamlDraft:void 0,updatedAt:new Date().toISOString()};await this.ctx.host.saveTypeDraft(e)}async discardCurrentType(){let e=this.selectedPath,t=this.ctx.host.loadTypeDraft(e);if((!t||t.sourceRevision===(this.originalModel?.sourceRevision??null))&&await this.ctx.host.clearTypeDraft(e),e){let n=await this.ctx.host.loadTypeModel(e);this.model=n,this.originalModel=qn(n),this.yamlDraft=`${mt(Ea(n),n.body)} -`,this.dirty=!1}else this.model=null,this.originalModel=null,this.yamlDraft="",this.dirty=!1;this.ctx.message="Unsaved changes discarded.",this.ctx.render()}};function Ea(r){return r.specProfile==="v0.3"&&!r.readOnlyReason?Fn(r):qn(r.originalFrontmatter??{name:r.name,fields:Object.fromEntries(r.fields.map(e=>[e.name,e.definition]))})}var Dr="mdbase-workspace-view",kd=class extends Ds.ItemView{constructor(t,n){super(t);this.host=n;this.destination="types";this.message="";this.pendingFocusKey=null;this.busy=!1;this.schema=null;this.records=null;this.disclosures=new Map;this.types=new Ad(this);this.sync=new xd(this);this.issues=new vd(this);this.refreshVersion=0;this.unsubscribeSync=null;this.syncRenderTimer=null}getState(){return this.captureRenderSnapshot(this.containerEl),{destination:this.destination,...this.types.getState(),...this.issues.getState(),...this.sync.getState(),disclosures:Object.fromEntries(this.disclosures)}}async setState(t,n){if(["types","sync","issues"].includes(String(t.destination))&&(this.destination=t.destination),t.disclosures&&typeof t.disclosures=="object")for(let[i,s]of Object.entries(t.disclosures))typeof s=="boolean"&&this.disclosures.set(i,s);await this.types.setState(t),this.issues.setState(t),this.sync.setState(t),await this.refresh(),this.types.restoreEditorMode(t.editorMode),await super.setState(t,n)}refreshValidationControls(){this.destination==="issues"&&this.render()}updateValidationProgress(){this.issues.updateValidationProgress()}getViewType(){return Dr}getDisplayText(){return"mdbase"}getIcon(){return Sa}async onOpen(){this.containerEl.addClass("mdbase-workspace"),this.registerDomEvent(this.containerEl,"keydown",n=>{(n.metaKey||n.ctrlKey)&&n.key.toLowerCase()==="s"&&this.types.dirty&&(n.preventDefault(),this.types.saveCurrentType())});let t=this.host.sync.state;this.unsubscribeSync=this.host.sync.subscribe(()=>{let n=this.host.sync.state,i=Object.keys(n).every(s=>s==="progress"||s==="fileProgress"||t[s]===n[s]);if(t=n,i&&(n.progress||n.fileProgress)){this.destination==="sync"&&this.syncRenderTimer===null&&(this.syncRenderTimer=window.setTimeout(()=>{this.syncRenderTimer=null,this.destination==="sync"&&this.render()},100));return}this.cancelSyncRender(),this.destination==="sync"?this.render():this.renderTopbarOnly()}),await this.refresh(!0)}async onClose(){this.refreshVersion++,this.unsubscribeSync?.(),this.unsubscribeSync=null,this.cancelSyncRender(),await this.types.dispose(),this.sync.dispose()}cancelSyncRender(){this.syncRenderTimer!==null&&window.clearTimeout(this.syncRenderTimer),this.syncRenderTimer=null}async refresh(t=!1){let n=++this.refreshVersion,i=()=>n===this.refreshVersion;try{let s=await this.host.loadWorkspaceSchema(t);if(!i()||(this.schema=s,await this.types.onSchemaLoaded(t,i),!i())||(this.destination==="sync"&&await this.sync.refresh(),!i()))return;let o=s?await this.host.loadCollectionRecords():null;if(!i())return;let a=o!==this.records;this.records=o,this.types.onRecordsLoaded(a||t),this.render()}catch(s){if(!i())return;this.message=s instanceof Error?s.message:String(s),this.render()}}showDestination(t){this.destination=t,this.render(),t==="sync"&&this.sync.refresh().then(()=>this.render())}showIssuesForPath(t){this.issues.filterToPath(t),this.showDestination("issues")}openTypeField(t,n){return this.types.openTypeField(t,n)}recordTypes(){return this.types.currentStats().recordTypes}createNewType(){this.types.createNewType()}editType(t){return this.types.editType(t)}focusSyncSection(t){this.sync.focusSection(t)}reconnectCollection(){return this.sync.reconnectCollection()}render(){let t=this.containerEl,n=this.captureRenderSnapshot(t);t.empty(),t.addClass("mdbase-workspace");let i=t.createDiv({cls:"mdbase-shell"});if(this.renderTopbar(i),this.message){let o=i.createDiv({cls:"mdbase-inline-message mdbase-notice"});o.createSpan({text:this.message}).setAttr("role","status");let a=this.iconButton(o,"x","Dismiss message");a.onclick=()=>{this.message="",this.render()}}let s=i.createDiv({cls:"mdbase-workspace-content"});s.setAttr("data-scroll-key","workspace"),this.destination==="types"?this.types.render(s):this.destination==="sync"?this.sync.render(s):this.issues.render(s),this.restoreRenderSnapshot(t,n),this.app.workspace?.requestSaveLayout(),this.pendingFocusKey&&(t.querySelector(`[data-focus-key="${this.pendingFocusKey}"]`)?.focus(),this.pendingFocusKey=null),this.destination==="types"&&this.types.afterRender(t)}syncAttention(){let{status:t,preview:n}=this.host.sync.state,i=t?.conflicts.length??0;if(i)return{count:i,label:`${i} sync ${i===1?"conflict":"conflicts"}`};let s=this.host.sync.safety(),o=s&&!s.safe?n?.plan.actions.length??0:0;return o?{count:o,label:`${o} ${o===1?"change needs":"changes need"} review`}:null}renderTopbarOnly(){let t=this.containerEl.querySelector(".mdbase-topbar");if(!t)return;let n=this.containerEl.ownerDocument.createElement("div");this.renderTopbar(n);let i=n.firstElementChild;i&&t.replaceWith(i)}captureRenderSnapshot(t){for(let a of Array.from(t.querySelectorAll("details[data-disclosure]"))){let c=a.dataset.disclosure;c&&this.disclosures.set(c,a.open)}let n=t.ownerDocument,i=t.contains(n.activeElement)?n.activeElement:null,s=i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement?i:null,o=new Map;for(let a of Array.from(t.querySelectorAll("[data-scroll-key]"))){let c=a.getAttr("data-scroll-key");c&&o.set(c,{top:a.scrollTop,left:a.scrollLeft})}return{focusKey:i?.getAttr("data-focus-key")??null,selectionStart:s?.selectionStart??null,selectionEnd:s?.selectionEnd??null,scroll:o}}restoreRenderSnapshot(t,n){for(let[s,o]of n.scroll){let a=t.querySelector(`[data-scroll-key="${s}"]`);a&&(a.scrollTop=o.top,a.scrollLeft=o.left)}if(!n.focusKey)return;let i=t.querySelector(`[data-focus-key="${n.focusKey}"]`);i?.focus({preventScroll:!0}),(i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement)&&n.selectionStart!==null&&n.selectionEnd!==null&&i.setSelectionRange(n.selectionStart,n.selectionEnd)}iconButton(t,n,i){let s=t.createEl("button",{cls:"clickable-icon mdbase-icon-button"});return s.setAttr("aria-label",i),s.setAttr("title",i),s.setAttr("data-focus-key",`action-${i.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`),(0,Ds.setIcon)(s,n),s}disclosure(t,n,i,s=!1){let o=t.createEl("details",{cls:"mdbase-disclosure"});return o.dataset.disclosure=n,o.open=this.disclosures.get(n)??s,o.addEventListener("toggle",()=>{this.containerEl.contains(o)&&(this.disclosures.set(n,o.open),this.app.workspace?.requestSaveLayout())}),o.createEl("summary",{text:i}).setAttr("data-focus-key",`disclosure-${n}`),o.createDiv({cls:"mdbase-disclosure-body"})}renderTopbar(t){let i=t.createDiv({cls:"mdbase-topbar"}).createDiv({cls:"mdbase-nav"});i.setAttr("role","tablist");for(let[s,o]of[["types","Types"],["sync","Sync"],["issues","Issues"]]){let a=i.createEl("button",{text:o,cls:"clickable-icon"});if(a.addClass("mdbase-nav-button"),a.setAttr("role","tab"),a.setAttr("data-focus-key",`destination-${s}`),a.setAttr("aria-selected",String(this.destination===s)),this.destination===s&&a.addClass("is-active"),s==="issues"&&this.host.getIssues().length){let l=this.host.getIssues().length;a.createSpan({cls:"mdbase-count",text:Zm(l)}).setAttr("title",`${l} issues`)}let c=s==="sync"?this.syncAttention():null;c&&a.createSpan({cls:"mdbase-count",text:Zm(c.count)}).setAttr("title",c.label),a.onclick=()=>this.showDestination(s)}}async perform(t){if(!this.busy){this.busy=!0,this.message="",this.render();try{await t()}catch(n){let i=n instanceof Error?n.message:String(n);this.message=i,new Ds.Notice(i)}finally{this.busy=!1,this.render()}}}};var Aa=class{constructor(e,t){this.delayMs=e;this.task=t;this.entries=new Map;if(!Number.isFinite(e)||e<0)throw new Error("Debounce delay must be a non-negative finite number.")}has(e){return this.entries.has(e)}schedule(e,t){let n=this.entries.get(e);n||(n={value:t,revision:0,timer:null,ready:!1,running:!1},this.entries.set(e,n)),n.value=t,n.revision+=1,n.ready=!1,n.timer!==null&&clearTimeout(n.timer),n.timer=setTimeout(()=>{this.entries.get(e)===n&&(n.timer=null,n.ready=!0,this.drain(e,n))},this.delayMs)}cancel(e){let t=this.entries.get(e);t&&(t.timer!==null&&clearTimeout(t.timer),this.entries.delete(e))}clear(){for(let e of this.entries.values())e.timer!==null&&clearTimeout(e.timer);this.entries.clear()}async drain(e,t){if(this.entries.get(e)!==t||t.running||!t.ready)return;t.ready=!1,t.running=!0;let n=t.revision,i=t.value,s=()=>this.entries.get(e)===t&&t.revision===n;try{await this.task(i,s)}finally{t.running=!1,this.entries.get(e)===t&&(t.ready?this.drain(e,t):t.timer===null&&t.revision===n&&this.entries.delete(e))}}};var Hx=require("obsidian");var Pd=class extends Hx.Modal{constructor(t,n,i){super(t);this.path=n;this.runs=i}onOpen(){this.titleEl.setText(`Sync history \xB7 ${this.path.split("/").pop()??this.path}`),this.contentEl.addClass("mdbase-note-history");let t=z$(this.runs,this.path).map(({run:i,file:s})=>({at:s.at,label:i.summary??W$(s),detail:i.summary===void 0&&s.fromPath?`From ${s.fromPath}`:s.message}));if(!t.length){this.contentEl.createEl("p",{cls:"mdbase-muted",text:"No syncs of this note are recorded on this device."});return}let n=this.contentEl.createDiv({cls:"mdbase-transfer-ledger"});for(let i of t){let s=n.createDiv({cls:"mdbase-note-history-row"});s.createSpan({cls:"mdbase-muted",text:ks(i.at)});let o=s.createDiv();o.createDiv({text:i.label}),i.detail&&o.createDiv({cls:"mdbase-muted",text:i.detail})}}onClose(){this.contentEl.empty()}};var Ne=require("obsidian");var nj=[["image","Images"],["audio","Audio"],["video","Video"],["pdf","PDFs"],["other","Other files"]],Cd=class extends Ne.PluginSettingTab{constructor(t,n){super(t,n);this.plugin=n}display(){let{containerEl:t,plugin:n}=this;t.empty(),new Ne.Setting(t).setName("Validate notes automatically").setDesc("Check notes against their types when they are opened or saved.").addToggle(i=>i.setValue(n.settings.validateOnSave||n.settings.validateOnOpen).onChange(async s=>{n.settings.validateOnSave=s,n.settings.validateOnOpen=s,await n.saveSettings(),this.display()})),n.settings.validateOnSave&&new Ne.Setting(t).setName("Show validation notices").setDesc("Notify when saving a note with issues.").addToggle(i=>i.setValue(n.settings.showNoticeOnSave).onChange(async s=>{n.settings.showNoticeOnSave=s,await n.saveSettings()})),new Ne.Setting(t).setName("Allow plugin integrations").setDesc("Let other installed plugins exchange mdbase events and actions in this vault.").addToggle(i=>i.setValue(n.settings.interopEnabled).onChange(async s=>{n.settings.interopEnabled=s,await n.saveSettings()})),this.displaySync(t)}displaySync(t){let{plugin:n}=this,i=n.getMirrorProfile();if(new Ne.Setting(t).setName("Sync").setHeading(),!i){new Ne.Setting(t).setName("Not connected").setDesc("Connect this vault to mdbase Connect from the sync tab of the mdbase workspace.").addButton(l=>l.setButtonText("Open sync").onClick(()=>{n.openWorkspace("sync")}));return}new Ne.Setting(t).setName(i.name).setDesc(`${i.mode==="read_write"?"Read and write":"Read only"} \xB7 ${new URL(i.controlUrl).host}`).addButton(l=>l.setButtonText("Reconnect").onClick(async()=>{l.setDisabled(!0),await n.openWorkspace("sync").then(u=>u.reconnectCollection()),l.setDisabled(!1)})),new Ne.Setting(t).setName("Sync automatically").setDesc("Keep this vault in sync in the background. Deleted files go to the trash, and conflicting edits are merged or kept as two files. Deleting many files at once on this device waits for your review.").addToggle(l=>l.setValue(n.settings.autoSync).onChange(async u=>{n.settings.autoSync=u,await n.saveSettings(),n.requestSync()}));let s=n.connectSync.getSelectiveSync(),o=async l=>{try{await n.sync.configureSelectiveSync(l)}catch(u){new Ne.Notice(u instanceof Error?u.message:String(u)),this.display()}};for(let[l,u]of nj)new Ne.Setting(t).setName(`Sync ${u.toLowerCase()}`).setDesc(l==="other"?"All remaining visible file formats. Markdown always syncs.":"").addToggle(d=>d.setValue(s.file_classes.includes(l)).onChange(async f=>{let p=n.connectSync.getSelectiveSync();await o({...p,file_classes:f?[...new Set([...p.file_classes,l])]:p.file_classes.filter(m=>m!==l)})}));let a=[...s.excluded_folders],c=new Ne.Setting(t).setName("Excluded folders").setDesc(Sd);$d(this.app,c.controlEl,a,l=>{a=l}),c.addButton(l=>l.setButtonText("Apply").onClick(async()=>{await o({...n.connectSync.getSelectiveSync(),excluded_folders:a}),new Ne.Notice("Excluded folders updated. The next sync applies them.")})),new Ne.Setting(t).setName("Disconnect").setDesc("Stop syncing this vault. The hosted collection is not deleted.").addButton(l=>l.setButtonText("Disconnect\u2026").setWarning().setDisabled(n.sync.isSyncing()).onClick(async()=>{let u=await new Ac(this.app).choose(i.name);if(u){try{await n.sync.disconnect(i,u==="remove"),new Ne.Notice(n.sync.state.message)}catch(d){new Ne.Notice(d instanceof Error?d.message:String(d))}this.display()}}))}};async function zx(r,e,t,n){let i=await r.resolveConflict(e,t,n),s=await r.preview();return{status:i,preview:s}}var ij=4,Kx={status:null,preview:null,progress:null,fileProgress:null,problem:null,message:"",localChangeObserved:!1,busy:!1,paused:!1,retryAt:null},Md=class{constructor(e,t,n,i=()=>{}){this.controller=e;this.getProfile=t;this.history=n;this.notify=i;this.current={...Kx};this.listeners=new Set;this.safetyPreview=null;this.previewSafety=null;this.pinnedFailure=null}get state(){return this.current}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}update(e){this.current={...this.current,...e};for(let t of this.listeners)t()}reset(){this.update({...Kx})}isSyncing(){return this.controller.isSyncing()}clearMessage(){this.current.message&&this.update({message:""})}observeLocalChange(){this.current.localChangeObserved||this.update({localChangeObserved:!0})}historyRuns(){let e=this.getProfile()?.collectionId;return e?this.history?.list(e)??[]:[]}async recordEvent(e,t=this.getProfile()?.collectionId){if(!(!t||!this.history)){try{await this.history.append(cd(t,e))}catch(n){console.error("mdbase: could not save sync history",n)}this.update({})}}async dismissEvent(e){await this.history?.remove(e),this.update({})}async clearHistory(){await this.history?.clear(),this.update({})}async refreshStatus(){let e=this.getProfile();if(!e)return this.reset(),null;if(this.controller.isSyncing())return this.current.status;try{let t=await this.controller.status();return Wx(e,this.getProfile())?(this.update({status:t,problem:null}),t):null}catch(t){return Wx(e,this.getProfile())&&this.update({problem:Rt(t)}),null}}async review(){return this.getProfile()?await this.exclusive(async()=>(await this.loadPreview(),this.current.preview))??null:null}async apply(){if(!this.current.preview){await this.review();return}await this.exclusive(()=>this.applyReviewed())}async syncNow(e={}){return this.getProfile()?this.current.busy||this.controller.isSyncing()?"busy":e.automatic&&this.current.paused?"paused":(!e.automatic&&this.current.paused&&this.update({paused:!1}),await this.exclusive(async()=>{let n=!1;for(let i=0;it.outcome!=="unresolved")}safety(){let e=this.current.preview;return e!==this.safetyPreview&&(this.safetyPreview=e,this.previewSafety=e?D$(e):null),this.previewSafety}cancel(){this.update({paused:!0}),this.controller.isSyncing()&&(this.controller.cancelSync(),this.update({message:"Stopping\u2026"}))}async reconnect(){return await this.exclusive(async()=>{try{let t=await this.controller.reconnect();return this.update({status:t,problem:null,message:"Connection restored."}),await this.recordEvent({summary:"Collection reconnected",message:"Connect credentials were renewed and the mirror checkpoint was preserved.",tone:"success"}),"connected"}catch(t){let n=Rt(t);return this.update({problem:n,message:n.action==="reauthorize"?"":n.message}),n.action==="reauthorize"?"reauthorize":"failed"}})??"failed"}async reauthorize(e){let t=await this.controller.reauthorize(e);this.update({status:t,problem:null,message:"Approval restored. The mirror checkpoint was preserved."}),await this.recordEvent({summary:"Connect approval restored",message:"The existing mirror checkpoint and local files were preserved.",tone:"success"})}async disconnect(e,t){let n=await this.controller.disconnect(t),i=t?`${n.removed.length} unchanged synced ${n.removed.length===1?"file was":"files were"} removed. ${n.preserved.length} locally changed ${n.preserved.length===1?"file was":"files were"} preserved.`:"All local files were retained as an unsynced copy.";return this.reset(),this.update({message:`Disconnected from ${e.name}. ${i}`}),n}async configureSelectiveSync(e){await this.controller.configureSelectiveSync(e),this.update({preview:null,message:"Sync settings updated."})}async resolveConflict(e,t,n){let i=null;try{n&&(i=await this.controller.preserveConflictCopy(e.path??"")),this.update({preview:null});let s=await zx(this.controller,e.object_id,e.decision_id,t),o=i?`Local copy saved to ${i}. Sync to apply the hosted version.`:"Conflict resolved. Sync to continue.";return this.update({status:s.status,preview:s.preview,problem:null,message:o}),await this.recordEvent({summary:i?"Conflict kept as two files":`Conflict resolved with ${t==="local"?"local":"hosted"} version`,message:o,...e.path?{path:e.path}:{},tone:"info"}),!0}catch(s){let o=Rt(s);return i&&(o.message=`The local copy at ${i} is safe, but the original changed again. Review the newest versions before deciding.`),this.update({problem:o,message:o.message}),o.code==="conflict_decision_stale"&&(this.update({preview:null}),await this.refreshStatus()),await this.recordEvent({summary:o.title,message:o.message,...e.path?{path:e.path}:{},tone:"attention",needsAcknowledgement:!0}),!1}}reportProblem(e){let t=Rt(e);return this.update({problem:t,message:t.message}),t}async exclusive(e,t=!1){if(!this.current.busy){this.update({busy:!0,...t?{}:{message:""}});try{return await e()}finally{this.update({busy:!1})}}}async loadPreview(){try{let{preview:e,status:t}=await this.controller.inspect();return this.update({preview:e,status:t,problem:null}),e}catch(e){let t=Rt(e);return this.update({problem:t,message:t.message}),null}}async applyReviewed(){let e=this.current.preview;if(!e)return"failed";let t=this.getProfile()?.collectionId,n=new Date().toISOString(),i=[],s="failed",o;try{let a=await this.controller.sync(e,m=>this.update({progress:m}),m=>this.update({fileProgress:m}),(m,h)=>{let y=V$(m,h,new Date().toISOString());y&&i.push(y)});s=a.status,o=a.failure?.message;let{preview:c,status:l}=await this.controller.inspect(),u=a.status==="cancelled"?Rt(new DOMException("Synchronization stopped.","AbortError")):a.status==="failed"||a.status==="blocked"?Nx(a.failure??{code:"sync_failed",message:"Synchronization stopped."}):null,d=a.status==="applied"?"Sync complete.":a.status==="attention"?a.applied>0?"Available changes synced. Remaining items need attention.":"No available changes. Resolve the listed items and review again.":a.status==="cancelled"?`Sync paused after ${a.applied} ${a.applied===1?"change":"changes"}. Resume to finish the rest.`:a.status==="stale"?"Files changed during sync; checking again.":u?.message??`Sync stopped: ${a.failure?.message??a.status}.`;this.update({status:l,preview:c.plan.actions.length||c.entries.length?c:null,problem:u,message:d,...a.status==="applied"&&a.pending===0?{localChangeObserved:!1}:{}});let f=u?`${u.kind}:${u.code}`:null,p=a.status==="stale"||u?.kind==="offline"||a.status==="attention"&&l.conflicts.length>0||f!==null&&f===this.pinnedFailure;return a.status==="applied"?this.pinnedFailure=null:f&&!p&&(this.pinnedFailure=f),!p&&(a.status!=="applied"||!i.length)&&await this.recordEvent({summary:a.status==="applied"?`Synchronized ${a.applied} ${a.applied===1?"change":"changes"}`:a.status==="cancelled"?"Synchronization paused safely":a.applied>0?"Synced available changes":"Synchronization needs attention",message:d,tone:a.status==="applied"?"success":"attention",needsAcknowledgement:a.status!=="applied"&&a.status!=="attention"},t),a.status==="blocked"?"failed":a.status}catch(a){let c=Rt(a);s=c.kind==="paused"?"cancelled":"failed",o=c.message,this.update({problem:c,message:c.message});let l=`${c.kind}:${c.code}`;return c.kind!=="offline"&&l!==this.pinnedFailure&&(this.pinnedFailure=l,await this.recordEvent({summary:c.title,message:c.message,tone:c.kind==="paused"?"attention":"error",needsAcknowledgement:c.kind!=="paused"},t)),c.kind==="paused"?"cancelled":"failed"}finally{if(this.update({progress:null,fileProgress:null}),t&&i.length&&this.history){try{await this.history.append({id:crypto.randomUUID(),collectionId:t,startedAt:n,finishedAt:new Date().toISOString(),outcome:s,files:i,...o?{message:o}:{}})}catch(a){console.error("mdbase: could not save sync history",a)}this.update({})}}}};function Wx(r,e){return r?.collectionId===e?.collectionId}function sj(r){let e=r.path.split("/").pop()??r.path;switch(r.outcome){case"merged":return{summary:`Merged edits to ${e}`,message:"Changes made here and on another device were combined.",path:r.path,tone:"success"};case"kept_both":return{summary:`Kept both versions of ${e}`,message:`The same part was edited on two devices. The other device's version is in place and this device's version was saved as ${r.copyPath??"a copy"}.`,path:r.path,tone:"attention",needsAcknowledgement:!0};case"restored":return{summary:`Restored ${e}`,message:"It was deleted here but edited on another device, so the edited version was kept.",path:r.path,tone:"info"};case"kept_local":return{summary:`Kept ${e}`,message:"It was deleted on another device but edited here, so this version was uploaded again.",path:r.path,tone:"info"};case"took_hosted":return{summary:`Settled ${e}`,message:"The hosted version was kept.",path:r.path,tone:"info"};case"unresolved":return{summary:`Couldn't sync ${e}`,message:r.reason??"This change needs a decision.",path:r.path,tone:"attention",needsAcknowledgement:!0}}}var oj={localQuietMs:3e3,localMaxWaitMs:2e4,probeVisibleMs:3e4,probeHiddenMs:5*6e4,safetyNetMs:15*6e4,retryBaseMs:5e3,retryMaxMs:5*6e4,unexpectedRetryMaxMs:30*6e4},Gx=new Set(["auth","device","paused"]),Td=class{constructor(e,t=aj,n=oj){this.host=e;this.clock=t;this.timing=n;this.timer=null;this.dueAt=null;this.dueIsDebounce=!1;this.firstLocalChangeAt=null;this.changed=!0;this.failures=0;this.running=!1;this.rerun=!1;this.visible=!0;this.stopped=!0;this.lastSyncAt=t.now()}start(){this.stopped=!1,this.schedule(this.clock.now())}stop(){this.stopped=!0,this.timer!==null&&this.clock.clearTimeout(this.timer),this.timer=null,this.dueAt=null}noteLocalChange(){let e=this.clock.now();this.firstLocalChangeAt??=e,this.changed=!0,this.schedule(Math.min(e+this.timing.localQuietMs,this.firstLocalChangeAt+this.timing.localMaxWaitMs),!0)}noteVisibility(e){let t=this.visible;this.visible=e,e&&!t&&this.schedule(this.clock.now())}noteOnline(){this.failures>0&&(this.changed=!0),this.failures=0,this.host.setRetryAt(null),this.schedule(this.clock.now())}requestSoon(){this.schedule(this.clock.now())}async tick(){if(this.stopped)return;if(this.running){this.rerun=!0;return}this.running=!0,this.dueAt=null;let e=null;try{e=await this.decide()}finally{this.running=!1;let t=this.clock.now();this.rerun?(this.rerun=!1,this.schedule(t)):e!==null?this.schedule(t+e):this.schedule(t+(this.visible?this.timing.probeVisibleMs:this.timing.probeHiddenMs))}}async decide(){if(!this.host.connected())return null;let e=this.host.problemKind();if(e&&Gx.has(e))return null;let t=this.clock.now(),n=this.changed;if(this.changed=!1,this.firstLocalChangeAt=null,!this.host.automatic())return(n||await this.probe()===!0)&&await this.host.refreshStatus(),null;let i=n||this.failures>0||t-this.lastSyncAt>=this.timing.safetyNetMs;if(!i){let o=await this.probe();if(o===null)return this.failed(!0);i=o}if(!i)return null;this.lastSyncAt=t;let s=await this.host.autoSync();if(s==="busy")return this.changed||=n,2e3;if(s==="failed"){this.changed||=n;let o=this.host.problemKind();return o&&Gx.has(o)?this.settled():this.failed(o==="offline")}return this.settled()}async probe(){try{return await this.host.remoteChangesWaiting()}catch(e){return this.host.reportProblem(e),oa(e)?null:!0}}failed(e){let t=km(this.failures,{baseDelayMs:this.timing.retryBaseMs,maxDelayMs:e?this.timing.retryMaxMs:this.timing.unexpectedRetryMaxMs,random:()=>this.clock.random()});return this.failures+=1,this.host.setRetryAt(this.clock.now()+t),t}settled(){return this.failures=0,this.host.setRetryAt(null),null}schedule(e,t=!1){if(this.stopped)return;let n=this.timer===null?null:this.dueAt;n!==null&&n<=e&&!(t&&this.dueIsDebounce)||(this.timer!==null&&this.clock.clearTimeout(this.timer),this.dueAt=e,this.dueIsDebounce=t,this.timer=this.clock.setTimeout(()=>{this.timer=null,this.dueAt=null,this.tick()},Math.max(0,e-this.clock.now())))}},aj={now:()=>Date.now(),setTimeout:(r,e)=>window.setTimeout(r,e),clearTimeout:r=>window.clearTimeout(r),random:()=>Math.random()};function Yx(r){let{profile:e,state:t}=r,n=["mdbase sync diagnostics",`Generated: ${r.generatedAt}`,`Plugin ${r.pluginVersion} \xB7 Obsidian ${r.obsidianVersion} \xB7 ${r.platform}`,"","Connection"];e?n.push(` Collection: ${e.collectionId}`,` Replica: ${e.replicaId} (${e.mode})`,` Connect: ${Jx(e.controlUrl)} \xB7 sync ${Jx(e.syncUrl)}`,` Access token expires: ${e.accessTokenExpiresAt}`,` Enrolled on this device: ${r.otherDevice?"no \u2014 copied from another device or vault":"yes"}`,` File classes: ${e.selectiveSync?.file_classes.join(", ")||"notes only"}`,` Excluded folders: ${e.selectiveSync?.excluded_folders.length??0}`):n.push(" Not connected"),n.push(` Automatic sync: ${r.automatic?"on":"off"}${t.paused?" (paused)":""}`,` Other sync services on this vault: ${r.otherSyncServices.join(", ")||"none detected"}`,"","State",` Engine state: ${t.status?.state??"unknown"} \xB7 pending ${t.status?.pending??"?"} \xB7 conflicts ${t.status?.conflicts.length??0} \xB7 local issues ${t.status?.local_issues.length??0}`,` Last synced: ${t.status?.last_synced_at??"never"}`,` Problem: ${t.problem?`${t.problem.kind}/${t.problem.code} \u2014 ${t.problem.message}`:"none"}`,` Next automatic attempt: ${t.retryAt?new Date(t.retryAt).toISOString():"not scheduled"}`,` Plan on screen: ${t.preview?`${t.preview.plan.kind}, ${t.preview.plan.actions.length} actions, ${t.preview.plan.summary.blocking_issues} blocking issues`:"none"}`,` Checkpoint: ${r.checkpoint?`cursor ${r.checkpoint.cursor}, generation ${r.checkpoint.generation}`:"none"}`,` Interrupted batch: ${r.checkpoint?.batch??"none"}${r.checkpoint?.failure?` (${r.checkpoint.failure})`:""}`,"","Recent history (newest first)");let i=[...r.history].sort((s,o)=>o.finishedAt.localeCompare(s.finishedAt)).slice(0,25);i.length||n.push(" none");for(let s of i){let o=s.summary??`${s.files.length} ${s.files.length===1?"file":"files"}`;n.push(` ${s.finishedAt} \xB7 ${s.outcome}${s.tone?`/${s.tone}`:""} \xB7 ${o}${s.message?` \u2014 ${s.message}`:""}`)}return`${n.join(` +`),i=t.length>200||n.length>200,s=t.slice(0,200),o=n.slice(0,200),a=Array.from({length:s.length+1},()=>new Uint16Array(o.length+1));for(let d=s.length-1;d>=0;d-=1)for(let f=o.length-1;f>=0;f-=1)a[d][f]=s[d]===o[f]?a[d+1][f+1]+1:Math.max(a[d+1][f],a[d][f+1]);let c=[],l=0,u=0;for(;(l=300);)l=o.length||l=a[l][u+1]?(c.push({kind:"local",value:s[l]}),l+=1):(c.push({kind:"remote",value:o[u]}),u+=1);return{lines:c,truncated:i||l0&&!r.actions.some(o=>o.command!=="advance_checkpoint"))return{actionLabel:"Resolve issues",actionDisabled:!0,message:"Synchronization is paused. Resolve the blocking issues, then refresh the review."};let n=r.actions.filter(o=>o.command!=="advance_checkpoint").length,i=r.actions.some(o=>o.command==="advance_checkpoint"),s=r.issues.some(o=>o.code==="invalid_frontmatter"&&!o.blocking);return{actionLabel:n?`Sync ${n}${r.summary.blocking_issues?" available":""} ${n===1?"change":"changes"}`:i?"Confirm sync":"Up to date",actionDisabled:t||r.actions.length===0,message:r.summary.blocking_issues>0?"Sync available changes. Unresolved items are isolated and remain for the next review; they do not stop independent transfers.":s?"Frontmatter warnings do not block this sync. Document bytes are preserved; synchronization does not repair YAML.":e?"Review each transfer below, then sync when ready.":"This vault and the hosted collection are already aligned."}}function pr(r){return r<1024?`${r} B`:r<1024*1024?`${(r/1024).toFixed(r<10*1024?1:0)} KB`:r<1024*1024*1024?`${(r/(1024*1024)).toFixed(r<10*1024*1024?1:0)} MB`:`${(r/(1024*1024*1024)).toFixed(1)} GB`}function j$(r){let{connected:e,status:t,progress:n,fileProgress:i,problem:s,validationIssues:o,localChangeObserved:a}=r,c=r.reviewChanges??0;if(!e)return o?{state:"attention",label:`mdbase: ${o} ${o===1?"issue":"issues"}`,detail:"Open validation issues",destination:"issues"}:{state:"local",label:"mdbase: Local",detail:"This vault is not connected",destination:"sync"};if(i){let u=i.totalBytes>0?Math.min(100,Math.round(i.transferredBytes/i.totalBytes*100)):100;return{state:"syncing",label:`mdbase: ${i.direction==="upload"?"Uploading":"Downloading"} ${u}%`,detail:`${i.path} \xB7 ${pr(i.transferredBytes)} of ${pr(i.totalBytes)}`,destination:"sync"}}if(n)return{state:"syncing",label:`mdbase: Syncing${n.total==null?"":` ${n.completed}/${n.total}`}`,detail:"Open synchronization progress",destination:"sync"};if(s&&s.kind!=="busy")return{state:s.kind==="paused"?"paused":s.kind==="offline"?"offline":"attention",label:s.kind==="paused"?"mdbase: Paused":s.kind==="offline"?"mdbase: Offline":s.kind==="device"?"mdbase: Set up sync":"mdbase: Needs attention",detail:s.kind==="offline"?`${s.title}. Changes will sync when it's back.`:s.title,destination:"sync"};if(c>0)return{state:"attention",label:`mdbase: Review ${c} ${c===1?"change":"changes"}`,detail:"Some changes need review before syncing",destination:"sync"};if(t?.recovery_required||t?.conflicts.length||t?.local_issues.length||["attention","blocked","failed","stale"].includes(t?.state??""))return{state:"attention",label:"mdbase: Needs attention",detail:"Review synchronization",destination:"sync"};if(t?.state==="cancelled")return{state:"paused",label:"mdbase: Paused",detail:"Review and resume synchronization",destination:"sync"};let l=t?.pending??0;return a||l>0||t?.state==="changes_waiting"||t?.state==="planned"?{state:"waiting",label:l>0?`mdbase: ${l} ${l===1?"change":"changes"}`:"mdbase: Changes waiting",detail:"Review local and hosted changes",destination:"sync"}:t?.state==="up_to_date"?{state:"synced",label:"mdbase: Synced",detail:"Local and hosted collections are aligned",destination:"sync"}:{state:"waiting",label:"mdbase: Ready to sync",detail:"Review the first synchronization",destination:"sync"}}var QF=new Set(["mirror_credentials_missing","invalid_mirror_enrollment","mirror_enrollment_expired","mirror_pairing_not_found","invalid_mirror_pairing","mirror_access_rejected","replica_revoked"]);function Rt(r){let e=ej(r);return e==="mirror_busy"?{code:e,kind:"busy",title:"Synchronization is already running",message:"The active transfer is still using this vault. Its progress is shown below.",action:"resume",actionLabel:"Show progress"}:e==="mirror_other_device"?{code:e,kind:"device",title:"Set up sync on this device",message:"This vault's sync settings came from another device or another copy of the vault, probably through a different sync service. Approve this copy to give it its own connection. Your files stay as they are.",action:"reauthorize",actionLabel:"Set up this device"}:QF.has(e)?{code:e,kind:"auth",title:"Connect approval is required again",message:"Your local files and mirror checkpoint are safe. Approve this vault again to restore access.",action:"reauthorize",actionLabel:"Sign in again"}:["operation_cancelled","cancelled","sync_cancelled","AbortError"].includes(e)?{code:e,kind:"paused",title:"Synchronization paused",message:"Completed changes are saved. Sync resumes from the same point when you continue.",action:"resume",actionLabel:"Resume sync"}:["stale","stale_mirror_plan","mirror_plan_stale","sync_plan_stale","conflict_decision_stale"].includes(e)?{code:e,kind:"decision",title:"The collection changed again",message:"No stale decision was applied. Review the newest local and hosted versions.",action:"review",actionLabel:"Review newest changes"}:["enrollment_recovery_required","mirror_recovery_required","pending_mirror_recovery"].includes(e)?{code:e,kind:"recovery",title:"Synchronization needs recovery",message:"Your original files are safe. Resume from the durable checkpoint before disconnecting this vault.",action:"resume",actionLabel:"Resume recovery"}:ks(r)?{code:e,kind:"offline",title:"Can't reach mdbase Connect",message:"Your changes are saved on this device and sync automatically when the connection returns.",action:"retry",actionLabel:"Retry now"}:{code:e,kind:"internal",title:"Sync stopped unexpectedly",message:`${tj(r,"An unexpected error stopped synchronization.")} Your files are safe. Sync tries again automatically; if this keeps happening, copy the diagnostics and report it.`,action:"retry",actionLabel:"Try again"}}function q$(r){return Rt(Object.assign(new Error(r.message),{code:r.code}))}function B$(r){return Array.isArray(r)?r.filter(ZF).slice(-XF):[]}function ZF(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;return typeof e.id=="string"&&typeof e.occurredAt=="string"&&typeof e.summary=="string"&&(e.detail===void 0||typeof e.detail=="string")&&(e.path===void 0||typeof e.path=="string")&&["success","info","attention","error"].includes(e.tone??"")&&typeof e.requiresAcknowledgement=="boolean"}function ej(r){return r instanceof DOMException?r.name:r&&typeof r=="object"&&"code"in r&&typeof r.code=="string"?r.code:r instanceof Error&&r.name?r.name:"sync_failed"}function tj(r,e){return r instanceof Error&&r.message?r.message:e}var Ed=class{constructor(e){this.ctx=e;this.conflictComparisons=new Map;this.loadingConflictComparisons=new Set;this.pendingSyncFocus=null;this.historyQuery="";this.transferQuery="";this.transferFilter="all";this.transferPages=new Map;this.historyLimit=Ea;this.previewComparisons=new Map;this.comparedPreview=null;this.loadingPreviewComparisons=new Set;this.enrollmentVerification="";this.enrollmentAbort=null;this.enrollmentControlUrl=wd;this.enrollmentMirrorName=R$(this.ctx.app.vault.getName());this.enrollmentCollectionId="";this.enrollmentMode="read_write";this.filePolicyDraft=null;this.adoptionFileProgress="";this.adoptionPreview=null;this.adoptionRenamePlan=null;this.adoptionStage="";this.adoptionFailed=!1}getState(){return{historyQuery:this.historyQuery}}setState(e){typeof e.historyQuery=="string"&&(this.historyQuery=e.historyQuery.slice(0,2e3))}get session(){return this.ctx.host.sync}dispose(){this.enrollmentAbort?.abort(),this.enrollmentAbort=null}focusSection(e){this.ctx.destination="sync",this.pendingSyncFocus=e,this.ctx.render(),window.setTimeout(()=>this.focusPendingSyncSection(),0)}async reconnectCollection(){await this.session.reconnect()==="reauthorize"&&await this.ctx.perform(()=>this.reauthorizeCollection())}render(e){let t=e.createDiv({cls:"mdbase-sync-document"}),n=this.ctx.host.getMirrorProfile();if(!n){this.renderEnrollment(t);return}let i=this.session.state,s=!!(i.fileProgress||i.progress),a=(i.problem?.kind==="busy"?null:i.problem)??(i.paused&&!s?{code:"sync_paused",kind:"paused",title:"Sync is paused",message:"Changes on this device and in Connect wait until you resume.",action:"resume",actionLabel:"Resume sync"}:i.status?.recovery_required?{code:"mirror_recovery_required",kind:"recovery",title:"Synchronization needs recovery",message:"Your original files are safe. Resume from the durable checkpoint before disconnecting this vault.",action:"resume",actionLabel:"Resume recovery"}:null),c=!!this.enrollmentAbort,l=i.preview,u=this.session.safety(),d=!!(l?.plan.actions.length||l?.entries.length),f=c?"Waiting for approval":s?"Syncing":i.busy?"Checking\u2026":a?.kind==="paused"?"Paused":a?.kind==="offline"?"Offline":a?.kind==="auth"?"Approval needed":a?.kind==="device"?"Set up this device":a?"Needs attention":d&&u&&!u.safe?"Review needed":l?.plan.actions.length?"Changes waiting":N$(i.status),p=t.createEl("section",{cls:"mdbase-sync-status"});p.setAttr("data-state",i.status?.state??"checking");let h=p.createDiv({cls:"mdbase-sync-heading"});h.createEl("h2",{text:n.name}),h.createDiv({cls:"mdbase-muted",text:`${f} \xB7 ${D$(i.status?.last_synced_at)}`});let m=h.createDiv({cls:"mdbase-muted mdbase-sync-scope"});m.createSpan({text:this.syncScopeText(n.mode)});let y=m.createEl("button",{cls:"mdbase-link-button",text:"Settings"});if(y.setAttr("aria-label","Open sync settings"),y.onclick=()=>this.ctx.host.openSettings(),i.message&&!i.problem){let v=p.createDiv({cls:"mdbase-inline-message mdbase-notice"});v.createSpan({text:i.message}).setAttr("role","status");let S=this.ctx.iconButton(v,"x","Dismiss sync message");S.onclick=()=>this.session.clearMessage()}if(s){let v=p.createDiv({cls:"mdbase-sync-progress",attr:{"aria-live":"polite"}}),S=i.fileProgress?.totalBytes??i.progress?.total??null,_=i.fileProgress?.transferredBytes??i.progress?.completed??0,E=v.createEl("progress");E.setAttr("aria-label","Sync progress"),E.max=S??1,E.value=S==null?0:_,S==null&&E.removeAttribute("value"),v.createDiv({cls:"mdbase-progress-label",text:i.fileProgress?`${i.fileProgress.direction==="upload"?"Uploading":"Downloading"} ${i.fileProgress.path} \xB7 ${pr(_)} of ${pr(S??0)}`:`${i.progress?.phase==="uploading"?"Uploading local changes":i.progress?.phase==="downloading"?"Downloading collection files":"Applying changes"} \xB7 ${_}${S==null?"":` of ${S}`}`});let k=v.createEl("button",{text:"Stop"});k.setAttr("data-focus-key","sync-stop"),k.onclick=()=>this.session.cancel()}let g=this.ctx.host.otherSyncServices();g.length&&p.createDiv({cls:"mdbase-inline-message mdbase-sync-coexistence",text:`${g.join(" and ")} also ${g.length===1?"syncs":"sync"} this vault. Two services syncing the same notes can duplicate them or bring deleted ones back; let only one of them sync this vault's notes.`}),c?this.renderApproval(p,!1):a&&this.renderRecoveryCard(p,a);let b=this.ctx.busy||i.busy||s;if(l!==this.comparedPreview&&(this.previewComparisons.clear(),this.comparedPreview=l,this.transferPages.clear()),d&&u&&!u.safe&&l?.plan.actions.length&&p.createDiv({cls:"mdbase-muted mdbase-review-reasons",text:`${u.reasons.join(", ")}.`}),!s&&!a&&!c){let v=p.createDiv({cls:"mdbase-sync-actions"});if(d&&l){let S=iy(l.plan,l.entries.length,b);if(l.plan.actions.length&&!S.actionDisabled){let E=v.createEl("button",{text:S.actionLabel,cls:"mod-cta"});E.setAttr("data-focus-key","sync-apply"),E.disabled=S.actionDisabled,E.onclick=()=>void this.session.apply()}let _=this.ctx.iconButton(v,"refresh-cw","Refresh review");_.disabled=b,_.onclick=()=>void this.session.review()}else{let S=v.createEl("button",{text:i.busy?"Checking\u2026":"Sync now",cls:"mod-cta"});S.setAttr("data-focus-key","sync-now"),S.disabled=b,S.onclick=()=>void this.session.syncNow()}}l&&d&&this.renderMirrorPreview(t,l),i.status?.conflicts.length&&this.renderConflicts(t,i.status),i.status?.local_issues.length&&!d&&this.renderLocalMirrorIssues(t,i.status),this.renderHistory(t),window.setTimeout(()=>this.focusPendingSyncSection(),0)}syncScopeText(e){let t=this.ctx.host.connectSync.getSelectiveSync().excluded_folders,n=t.length?`Whole vault except ${t.length>2?`${t.slice(0,2).join(", ")} +${t.length-2}`:t.join(", ")}`:"Whole vault";return`${e==="read_only"?"Read only":"Read and write"} \xB7 ${n}`}renderRecoveryCard(e,t){let n=e.createDiv({cls:"mdbase-recovery-card"});n.setAttr("data-kind",t.kind);let i=n.createDiv();i.createEl("strong",{text:t.title}),i.createDiv({text:t.message});let s=this.session.state.retryAt;if(s&&(t.kind==="offline"||t.kind==="internal")){let c=Math.max(0,Math.round((s-Date.now())/1e3));i.createDiv({cls:"mdbase-muted",text:c<=1?"Trying again now\u2026":c<60?`Trying again in ${c}s.`:`Trying again in ${Math.round(c/60)} min.`})}let o=n.createDiv({cls:"mdbase-recovery-actions"}),a=o.createEl("button",{text:t.actionLabel,cls:"mod-cta"});if(a.setAttr("data-focus-key","sync-recovery"),a.disabled=this.ctx.busy||this.session.state.busy,a.onclick=()=>{t.kind==="auth"?this.reconnectCollection():t.action==="reauthorize"?this.ctx.perform(()=>this.reauthorizeCollection()):t.action==="review"?this.session.review():this.session.syncNow()},t.kind==="internal"||t.kind==="recovery"){let c=o.createEl("button",{text:"Copy diagnostics"});c.setAttr("data-focus-key","sync-diagnostics"),c.onclick=()=>void this.ctx.host.copySyncDiagnostics()}}renderApproval(e,t=!0){let n=e.createDiv({cls:"mdbase-approval-link"});if(t&&n.createSpan({text:this.enrollmentVerification?"Waiting for approval \xB7 ":"Connecting\u2026 "}).setAttr("role","status"),this.enrollmentVerification){let s=n.createEl("a",{text:"Open Connect",href:this.enrollmentVerification});s.setAttr("target","_blank"),s.setAttr("rel","noopener noreferrer"),s.setAttr("data-focus-key","approval-link")}let i=n.createEl("button",{text:"Stop waiting"});i.setAttr("data-focus-key","stop-approval"),i.onclick=()=>{this.enrollmentAbort?.abort(),this.enrollmentVerification="",this.ctx.render()}}async reauthorizeCollection(){this.enrollmentAbort?.abort();let e=new AbortController;this.enrollmentAbort=e,this.ctx.pendingFocusKey="stop-approval",this.ctx.render();try{await this.session.reauthorize({signal:e.signal,onVerification:t=>{this.enrollmentVerification=t.verificationUri,this.ctx.message="",window.open(t.verificationUri,"_blank","noopener,noreferrer"),this.ctx.render()},onStatus:t=>{this.ctx.message=t.state==="waiting_for_approval"?"":`Connect is retrying approval (attempt ${t.attempt}).`,this.ctx.render()}}),this.ctx.message=""}catch(t){if(!Sd(t))throw t;this.ctx.message="Cancelled. Your files and connection are unchanged.",this.ctx.pendingFocusKey="sync-recovery"}finally{this.enrollmentAbort===e&&(this.enrollmentAbort=null,this.enrollmentVerification="")}}renderHistory(e){let t=this.session.historyRuns();if(!t.length)return;let n=t.filter(d=>d.needsAcknowledgement),i=this.ctx.disclosure(e,"sync-activity","History",n.length>0);i.addClass("mdbase-activity"),i.id="mdbase-sync-activity";let s=i.parentElement;if(this.renderHistoryOnToggle(s),!s.open)return;for(let d of[...n].reverse())this.renderEventRow(i,d);let o=t.filter(d=>!d.needsAcknowledgement);if(!o.length)return;let a=i.createDiv({cls:"mdbase-section-header mdbase-history-controls"}),c=a.createEl("input",{type:"search"});if(c.setAttr("aria-label","Filter history by path"),c.setAttr("data-focus-key","history-search"),c.placeholder="Filter by path",c.value=this.historyQuery,c.oninput=()=>{this.historyQuery=c.value,this.historyLimit=Ea,this.ctx.render()},t.length>n.length){let d=a.createEl("button",{text:"Clear history"});d.setAttr("data-focus-key","history-clear"),d.disabled=this.ctx.busy,d.onclick=()=>void this.ctx.perform(async()=>{await this.session.clearHistory(),this.ctx.pendingFocusKey=this.session.historyRuns().length?"disclosure-sync-activity":"destination-sync"})}let l=this.historyQuery.trim().toLowerCase(),u=Jx(o,l).sort((d,f)=>f.finishedAt.localeCompare(d.finishedAt));if(!u.length){i.createDiv({cls:"mdbase-muted",text:l?"No synced files match.":"No completed syncs."});return}for(let d of u.slice(0,this.historyLimit))zx(d)?this.renderEventRow(i,d):this.renderHistoryRun(i,d,l!=="");if(u.length>this.historyLimit){let d=i.createEl("button",{cls:"mdbase-link-button",text:`Show ${Math.min(Ea,u.length-this.historyLimit)} more`});d.setAttr("data-focus-key","history-more"),d.onclick=()=>{this.historyLimit+=Ea,this.ctx.render()}}}renderHistoryOnToggle(e){let t=e.open;e.addEventListener("toggle",()=>{this.ctx.containerEl.contains(e)&&e.open!==t&&this.ctx.render()})}renderHistoryRun(e,t,n){let i=e.createEl("details",{cls:"mdbase-history-run"}),s=`history-run-${t.id}`;n?i.open=!0:(i.dataset.disclosure=s,i.open=this.ctx.disclosures.get(s)??!1);let o=i.createEl("summary",{cls:"mdbase-activity-row"});o.setAttr("data-focus-key",`disclosure-${s}`);let a=t.outcome==="applied"?"success":t.outcome==="failed"?"error":"attention";o.setAttr("data-tone",a),(0,Os.setIcon)(o.createSpan(),a==="success"?"check":"circle-alert");let c=o.createDiv();c.createEl("strong",{text:Wx(t)});let l=O$[t.outcome];if(c.createSpan({cls:"mdbase-muted",text:l?`${Ps(t.finishedAt)} \xB7 ${l}`:Ps(t.finishedAt)}),t.message&&t.outcome!=="applied"&&c.createDiv({text:t.message}),(0,Os.setIcon)(o.createSpan({cls:"mdbase-history-chevron"}),"chevron-right"),this.renderHistoryOnToggle(i),!i.open)return;let u=i.createDiv({cls:"mdbase-transfer-ledger mdbase-history-files"});for(let d of t.files.slice(0,250)){let f=u.createDiv({cls:"mdbase-transfer-row"});f.setAttr("title",new Date(d.at).toLocaleString()),f.createSpan({cls:"mdbase-transfer-action",text:d.action}).setAttr("data-action",d.status==="completed"?d.action:"fix");let h=f.createDiv({cls:"mdbase-transfer-body"}),m=h.createDiv({cls:"mdbase-transfer-path"}),y=m.createSpan({cls:"mdbase-history-direction"}),g=d.direction==="download"?"Downloaded":d.direction==="upload"?"Uploaded":"Needs attention";if(y.setAttr("aria-label",g),y.setAttr("title",g),(0,Os.setIcon)(y,d.direction==="download"?"download":d.direction==="upload"?"upload":"circle-alert"),d.action!=="delete"&&this.ctx.app.vault.getAbstractFileByPath(d.path)){let b=m.createEl("button",{cls:"mdbase-link-button mdbase-transfer-open"});b.createEl("code",{text:d.path}),b.setAttr("title",`Open ${d.path}`),b.setAttr("data-focus-key",`history-open-${t.id}-${d.path}`),b.onclick=()=>void this.ctx.host.openFileByPath(d.path)}else m.createEl("code",{text:d.path});d.fromPath&&h.createDiv({cls:"mdbase-muted",text:`From ${d.fromPath}`}),d.status!=="completed"&&h.createDiv({text:d.message?`${ny(d.status)}: ${d.message}`:ny(d.status)})}t.files.length>250&&u.createDiv({cls:"mdbase-transfer-more",text:`${t.files.length-250} more files are recorded in this sync.`})}renderEventRow(e,t){let n=t.tone??"info",i=e.createDiv({cls:"mdbase-activity-row"});i.setAttr("data-tone",n),(0,Os.setIcon)(i.createSpan(),n==="success"?"check":n==="info"?"info":"circle-alert");let s=i.createDiv(),o=t.summary??"";if(t.message&&t.message!==o){let a=s.createEl("details"),c=`history-event-${t.id}`;a.dataset.disclosure=c,a.open=this.ctx.disclosures.get(c)??!!t.needsAcknowledgement,a.createEl("summary",{text:o}).setAttr("data-focus-key",`disclosure-${c}`),a.createDiv({text:t.message})}else s.createEl("strong",{text:o});if(s.createSpan({cls:"mdbase-muted",text:Ps(t.finishedAt)}),t.path&&this.ctx.app.vault.getAbstractFileByPath(t.path)){let a=t.path,c=s.createEl("button",{cls:"mdbase-link-button mdbase-transfer-open",text:a});c.setAttr("title",`Open ${a}`),c.setAttr("data-focus-key",`event-open-${t.id}`),c.onclick=()=>void this.ctx.host.openFileByPath(a)}if(t.needsAcknowledgement){let a=i.createEl("button",{text:"Dismiss"});a.setAttr("data-focus-key",`event-dismiss-${t.id}`),a.disabled=this.ctx.busy,a.onclick=()=>void this.ctx.perform(async()=>{await this.session.dismissEvent(t.id),this.ctx.pendingFocusKey=t.message&&t.message!==o?`disclosure-history-event-${t.id}`:"disclosure-sync-activity"})}}focusPendingSyncSection(){if(!this.pendingSyncFocus)return;let e=this.pendingSyncFocus==="activity"?"mdbase-sync-activity":"mdbase-sync-conflicts",t=this.ctx.containerEl.querySelector(`#${e}`);if(!t)return;this.pendingSyncFocus=null;let n=t.closest("details");n&&(n.open=!0),t.scrollIntoView({block:"nearest"})}filePolicy(){return this.filePolicyDraft??=JSON.parse(JSON.stringify(this.ctx.host.connectSync.getSelectiveSync())),this.filePolicyDraft}renderFilePolicyControls(e){let t=this.filePolicy(),n=e.createEl("section",{cls:"mdbase-editor-section mdbase-file-policy"});n.createEl("h3",{text:"Attachments"});let i=n.createDiv({cls:"mdbase-file-class-grid"}),s=[["image","Images"],["audio","Audio"],["video","Video"],["pdf","PDFs"],["other","Other files"]];for(let[o,a]of s){let c=i.createEl("label"),l=c.createEl("input",{type:"checkbox"});l.setAttr("data-focus-key",`file-class-${o}`),l.checked=t.file_classes.includes(o),l.onchange=()=>{t.file_classes=l.checked?[...new Set([...t.file_classes,o])]:t.file_classes.filter(u=>u!==o),this.ctx.render()},c.createSpan({text:a})}n.createDiv({cls:"mdbase-form-description",text:xd}),n.createEl("h4",{text:"Excluded folders"}),$d(this.ctx.app,n,t.excluded_folders,o=>{t.excluded_folders=o}),t.file_classes.includes("other")&&n.createDiv({cls:"mdbase-inline-message",text:"Other files includes all remaining visible file formats."})}renderEnrollment(e){if(this.ctx.schema||this.ctx.host.connectSync.getAdoptionMarker()){this.renderLocalAdoption(e);return}let t=e.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});if(t.createEl("h3",{text:"Copy a collection from Connect"}),t.createEl("p",{cls:"mdbase-muted",text:"Connect holds the collection; this vault syncs a copy. Choose a collection in Connect, then review the first sync."}),this.enrollmentAbort){this.renderApproval(t);return}Tt(t,"Device name",this.enrollmentMirrorName,p=>{this.enrollmentMirrorName=p});let n=t.createDiv({cls:"mdbase-form-row"}),i=n.createEl("label",{text:"Access"}),s=n.createEl("select");i.htmlFor=s.id="mdbase-enrollment-access",s.setAttr("data-focus-key","enrollment-access"),s.createEl("option",{value:"read_write",text:"Read and write"}),s.createEl("option",{value:"read_only",text:"Read only"}),s.value=this.enrollmentMode,s.onchange=()=>{this.enrollmentMode=s.value==="read_only"?"read_only":"read_write",this.ctx.render()};let o=t.createDiv({cls:"mdbase-form-row mdbase-sync-target"});o.createEl("label",{text:"Syncs"});let a=o.createDiv({cls:"mdbase-sync-target-value"}),c=this.filePolicy().excluded_folders;a.createSpan({text:`Whole vault \u201C${this.ctx.app.vault.getName()}\u201D${c.length?` except ${c.join(", ")}`:""}`});let l=a.createEl("button",{cls:"mdbase-link-button",text:"Exclude folders"});l.onclick=()=>{this.ctx.disclosures.set("enrollment-options",!0),this.ctx.render()},t.createEl("p",{cls:"mdbase-form-description",text:this.enrollmentMode==="read_write"?"Existing notes may upload. Nothing moves until you review and sync.":"Downloads only. Existing local changes must be resolved or excluded."});let u=this.ctx.disclosure(t,"enrollment-options","Advanced");Tt(u,"Connect URL",this.enrollmentControlUrl,p=>{this.enrollmentControlUrl=p},{placeholder:wd}),Tt(u,"Collection ID",this.enrollmentCollectionId,p=>{this.enrollmentCollectionId=p},{placeholder:"Choose during approval"}),this.renderFilePolicyControls(u);let f=t.createDiv({cls:"mdbase-actions mdbase-enrollment-actions"}).createEl("button",{text:"Connect"});f.setAttr("title","Opens Connect in your browser to choose a collection"),f.setAttr("data-focus-key","enrollment-connect"),f.addClass("mod-cta"),f.disabled=this.ctx.busy,f.onclick=()=>void this.ctx.perform(async()=>{this.enrollmentAbort?.abort();let p=new AbortController;this.enrollmentAbort=p,this.ctx.pendingFocusKey="stop-approval",this.ctx.render();try{await this.ctx.host.connectSync.enroll({controlUrl:this.enrollmentControlUrl,mirrorName:this.enrollmentMirrorName,mode:this.enrollmentMode,selectiveSync:this.filePolicy(),...this.enrollmentCollectionId.trim()?{collectionId:this.enrollmentCollectionId.trim()}:{}},{signal:p.signal,onVerification:y=>{this.enrollmentVerification=y.verificationUri,this.ctx.message="",window.open(y.verificationUri,"_blank","noopener,noreferrer"),this.ctx.render()},onStatus:y=>{this.ctx.message=y.state==="waiting_for_approval"?"":`Connect is retrying enrollment (attempt ${y.attempt}).`,this.ctx.render()}}),this.enrollmentVerification="",this.enrollmentAbort===p&&(this.enrollmentAbort=null);let h=await this.session.syncNow(),m=this.session.state.preview;if(h==="needs_review"&&m){let y=m.entries.reduce((b,v)=>b+(v.estimatedBytes??0),0),g=m.entries.length;this.ctx.message=`Connected. Review ${g} ${g===1?"item":"items"}${y?` \xB7 ${pr(y)}`:""} before syncing.`,this.ctx.pendingFocusKey="sync-apply"}else this.ctx.message="",this.ctx.pendingFocusKey=this.session.state.problem?"sync-recovery":h==="busy"?"sync-stop":"sync-now"}catch(h){if(this.ctx.pendingFocusKey="enrollment-connect",!Sd(h))throw h;this.enrollmentVerification="",this.ctx.message="Cancelled. No files synced."}finally{this.enrollmentAbort===p&&(this.enrollmentAbort=null,this.enrollmentVerification="")}})}renderLocalAdoption(e){let t=this.ctx.host.connectSync.getAdoptionMarker(),n=t?this.ctx.host.connectSync.getAdoptionRecovery():null,i=!t||["waiting_for_approval","uploading"].includes(t.phase),s=i?this.adoptionPreview?.conflicts??[]:[],o=e.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});o.createEl("h3",{text:"Upload to Connect"}),o.createEl("p",{cls:"mdbase-muted",text:n?n.canReset?"This upload expired and its device authorization is missing. Reset setup to start again. Your files stay local.":n.canReconnect?"Device authorization is unavailable. Reconnect to the hosted collection through Connect. This vault stays protected until approval succeeds.":`Device authorization is unavailable. Restore Obsidian's secret storage, or reset setup after ${new Date(t?.session.expiresAt??"").toLocaleString()}.`:this.ctx.busy&&this.adoptionStage?this.adoptionStage:t?t.phase==="waiting_for_approval"?"Not connected yet. Approval is pending in Connect.":t.phase==="adopted"?"Collection is hosted. Finish connecting this device.":t.phase==="activating"?"Activation outcome is pending. Resume to check it safely.":s.length||this.adoptionFailed?"Approval received. Upload stopped; this vault is not connected yet.":"Approval received. Transfer is not running; resume to continue.":"This vault holds the collection. Upload it to Connect to sync it with other devices; Connect then holds the collection and this vault syncs a copy.",attr:{role:"status","aria-live":"polite"}});let a=this.enrollmentVerification||(!n&&t?.phase==="waiting_for_approval"?t.session.verificationUri:void 0);if(a){let u=o.createDiv({cls:"mdbase-approval-link"});u.createSpan({text:"Approval page: "});let d=u.createEl("a",{text:"Open Connect",href:a});d.setAttr("target","_blank"),d.setAttr("rel","noopener noreferrer")}if(t&&(this.enrollmentControlUrl=t.session.controlUrl,this.enrollmentMirrorName=t.session.requested.mirrorName??"Obsidian"),t){let u=this.ctx.disclosure(o,"adoption-details","Details");Kt(u,"Collection",t.session.requested.collectionId),Kt(u,"Phase",t.phase.replace(/_/g," ")),Kt(u,"Connect",t.session.controlUrl);let d=this.ctx.host.connectSync.getSelectiveSync();Kt(u,"Files",d.file_classes.length?d.file_classes.join(", "):"Markdown only")}else{Tt(o,"Device name",this.enrollmentMirrorName,d=>{this.enrollmentMirrorName=d});let u=this.ctx.disclosure(o,"adoption-options","Advanced");Tt(u,"Connect URL",this.enrollmentControlUrl,d=>{this.enrollmentControlUrl=d},{placeholder:wd}),this.renderFilePolicyControls(u)}!n&&i&&(this.adoptionPreview&&o.createEl("p",{cls:"mdbase-muted",text:`${this.adoptionPreview.records.toLocaleString()} notes \xB7 ${this.adoptionPreview.files.toLocaleString()} attachments`}),s.length&&(o.createEl("h4",{text:`${s.length} filename conflicts`}),this.renderAdoptionRenameReview(o,s))),n||o.createEl("p",{cls:"mdbase-form-description",text:"Sync starts only after the upload completes."});let c=o.createDiv({cls:"mdbase-actions mdbase-enrollment-actions"});if(!n&&i){let u=c.createEl("button",{text:"Check files"});u.disabled=this.ctx.busy,u.onclick=()=>void this.ctx.perform(async()=>{this.adoptionRenamePlan=null,this.adoptionPreview=await this.ctx.host.connectSync.previewAdoption(this.filePolicy()),this.ctx.message=this.adoptionPreview.conflicts.length?"Resolve the listed filename conflicts before continuing.":"Files checked. No filename conflicts."})}if(n&&!n.canReconnect){if(n.canReset){let u=c.createEl("button",{text:"Reset setup",cls:"mod-cta"});u.disabled=this.ctx.busy,u.onclick=()=>void this.ctx.perform(async()=>{this.filePolicyDraft=this.ctx.host.connectSync.getSelectiveSync(),await this.ctx.host.connectSync.resetExpiredAdoption(),this.enrollmentVerification="",this.ctx.message="Expired setup cleared. Your files and collection identity are unchanged. Start a new upload to approve this device again.",await this.ctx.refresh(!0)})}else{let u=c.createEl("button",{text:"Check again"});u.disabled=this.ctx.busy,u.onclick=()=>this.ctx.render()}return}if(t&&!n&&!["activating","adopted"].includes(t.phase)){let u=c.createEl("button",{text:"Cancel upload"});u.disabled=this.ctx.busy,u.onclick=()=>void this.ctx.perform(async()=>{await this.ctx.host.connectSync.cancelAdoption(),this.enrollmentVerification="",this.ctx.message="Upload cancelled. The collection is still local.",await this.ctx.refresh(!0)})}if(this.enrollmentAbort){let u=c.createEl("button",{text:t?.phase==="waiting_for_approval"?"Stop waiting":"Pause upload"});u.onclick=()=>{this.enrollmentAbort?.abort(),this.ctx.message="Upload paused. Resume when ready.",this.ctx.render()}}let l=c.createEl("button",{text:n?"Reconnect collection":t?"Resume upload":"Upload to Connect"});l.addClass("mod-cta"),l.disabled=this.ctx.busy||!n&&s.length>0,l.onclick=()=>void this.ctx.perform(async()=>{this.adoptionFailed=!1,this.adoptionStage="Checking files\u2026",this.enrollmentAbort?.abort();let u=new AbortController;this.enrollmentAbort=u;let d=y=>{this.enrollmentVerification=y.verificationUri,this.adoptionStage="Waiting for approval in Connect\u2026",this.ctx.message="Approve the upload in Connect.",this.ctx.render()},f=y=>{this.ctx.message=y.state==="waiting_for_approval"?"Waiting for upload approval in Connect\u2026":`Connect is retrying (attempt ${y.attempt}).`,this.ctx.render()},p=y=>{this.adoptionStage=y.stage==="checking"?"Checking files\u2026":y.stage==="uploading"?`Approval received. Uploading ${y.records?.toLocaleString()??""} notes\u2026`:y.stage==="activating"?"Activating hosted collection. Keep this vault open\u2026":"Finishing this device's connection\u2026",this.enrollmentVerification="",this.ctx.message="",this.ctx.render()},h=(y,g,b)=>{this.adoptionFileProgress=`${y} \xB7 ${pr(g)} of ${pr(b)}`,this.adoptionStage=`Uploading ${this.adoptionFileProgress}`,this.ctx.render()},m={signal:u.signal,onVerification:d,onStatus:f,onFileProgress:h,onProgress:p};try{n?await this.ctx.host.connectSync.reconnectAdoption(m):t?await this.ctx.host.connectSync.resumeAdoption(m):await this.ctx.host.connectSync.adoptLocalCollection({controlUrl:this.enrollmentControlUrl,mirrorName:this.enrollmentMirrorName,selectiveSync:this.filePolicy()},m),this.enrollmentVerification="",this.ctx.message="Collection hosted. This vault is now connected.",await this.ctx.refresh(!0)}catch(y){if(this.ctx.host.connectSync.getAdoptionMarker()?.phase!=="waiting_for_approval"&&(this.enrollmentVerification=""),!Sd(y))throw this.adoptionFailed=!0,await this.ctx.host.connectSync.previewAdoption(this.filePolicy()).then(g=>{this.adoptionPreview=g}).catch(()=>{}),y;this.ctx.message="Upload paused. Resume when ready."}finally{this.adoptionStage="",this.enrollmentAbort===u&&(this.enrollmentAbort=null)}})}renderAdoptionRenameReview(e,t){let n=this.adoptionRenamePlan;e.createEl("p",{text:n?"Keep both files with distinct names. Nothing is merged or deleted. Link updates follow your Obsidian settings.":"Names must also be distinct on case-insensitive devices. Review suggested names, or rename the files yourself."});let i=e.createEl("ul",{cls:"mdbase-adoption-conflicts"}),s=n?n.renames.map(l=>[l.from,l.to]):t;for(let l of s){let u=i.createEl("li");l.forEach((d,f)=>{f&&u.appendText(n?" \u2192 ":" \u2194 "),u.createEl("code",{text:d})})}n?.manual.length&&e.createEl("p",{text:"Collection-resource conflicts need manual review: "+n.manual.map(l=>l.join(" \u2194 ")).join("; ")});let o=e.createDiv({cls:"mdbase-actions"});if(!n){let l=o.createEl("button",{text:"Review renames\u2026"});l.disabled=this.ctx.busy,l.onclick=()=>void this.ctx.perform(async()=>{this.adoptionRenamePlan=await this.ctx.host.connectSync.planAdoptionRenames(this.filePolicy())});return}let a=o.createEl("button",{text:`Rename ${n.renames.length} ${n.renames.length===1?"file":"files"}`,cls:"mod-cta"});a.disabled=this.ctx.busy||!n.renames.length,a.onclick=()=>void this.ctx.perform(async()=>{try{let l=await this.ctx.host.connectSync.applyAdoptionRenames(n,this.filePolicy(),(u,d)=>{this.adoptionStage=`Renaming ${u} of ${d} files\u2026`,this.ctx.render()});this.ctx.message=`Renamed ${l} ${l===1?"file":"files"}. Review the file check, then resume the upload.`}finally{this.adoptionStage="",this.adoptionRenamePlan=null,await this.ctx.host.connectSync.previewAdoption(this.filePolicy()).then(l=>{this.adoptionPreview=l}).catch(()=>{})}});let c=o.createEl("button",{text:"Cancel"});c.disabled=this.ctx.busy,c.onclick=()=>{this.adoptionRenamePlan=null,this.ctx.render()}}renderMirrorPreview(e,t){let n=e.createEl("section",{cls:"mdbase-transfer-review"}),i=n.createDiv({cls:"mdbase-transfer-heading"});i.createDiv().createEl("h3",{text:t.phase==="initial"?"First sync":"Changes"});let o=t.entries.reduce((p,h)=>p+(h.estimatedBytes??0),0);i.createSpan({cls:"mdbase-transfer-total",text:t.entries.length?`${t.entries.length} ${t.entries.length===1?"item":"items"}${o?` \xB7 ${pr(o)}`:""}`:"No changes"});let a=n.createDiv({cls:"mdbase-issue-controls"}),c=a.createEl("input",{type:"search",placeholder:"Search transfer paths"});c.setAttr("aria-label","Search transfer paths"),c.setAttr("data-focus-key","transfer-search"),c.value=this.transferQuery,c.oninput=()=>{this.transferQuery=c.value,this.transferPages.clear(),this.ctx.render()};let l=a.createEl("select");l.setAttr("aria-label","Filter transfers"),l.setAttr("data-focus-key","transfer-filter");for(let[p,h]of[["all","All changes"],["delete","Deletes"],["replace","Replacements"],["upload","Uploads"],["download","Downloads"],["attention","Needs attention"]])l.createEl("option",{value:p,text:h});l.value=this.transferFilter,l.onchange=()=>{this.transferFilter=l.value,this.transferPages.clear(),this.ctx.render()};let u=this.transferQuery.trim().toLowerCase(),d=t.entries.filter(p=>(!u||`${p.path} ${p.detail}`.toLowerCase().includes(u))&&(this.transferFilter==="all"||p.action===this.transferFilter||p.direction===this.transferFilter));d.length||n.createDiv({cls:"mdbase-muted",text:"No changes match these filters."}),n.createDiv({cls:"mdbase-muted",text:`Showing ${d.length} of ${t.entries.length} items. Approval always applies to the entire reviewed plan, not just these filters.`});let f=[{direction:"download",title:"Downloads"},{direction:"upload",title:"Uploads"},{direction:"attention",title:"Needs attention"}];for(let p of f){let h=d.filter(_=>_.direction===p.direction);if(!h.length)continue;let m=n.createEl("section",{cls:"mdbase-transfer-group"});m.setAttr("data-direction",p.direction);let y=m.createDiv({cls:"mdbase-transfer-group-heading"}),g=y.createSpan({cls:"mdbase-transfer-group-icon"});(0,Os.setIcon)(g,p.direction==="download"?"download":p.direction==="upload"?"upload":"circle-alert"),y.createEl("h4",{text:p.title}),y.createSpan({text:String(h.length),cls:"mdbase-transfer-count"});let b=m.createDiv({cls:"mdbase-transfer-ledger"}),v=Math.min(this.transferPages.get(p.direction)??0,Math.floor((h.length-1)/250)),S=v*250;for(let _ of h.slice(S,S+250)){let E=b.createDiv({cls:"mdbase-transfer-row"});E.createSpan({cls:"mdbase-transfer-action",text:_.action}).setAttr("data-action",_.action);let x=E.createDiv({cls:"mdbase-transfer-body"}),T=x.createDiv({cls:"mdbase-transfer-path"}),$=this.ctx.app.vault.getAbstractFileByPath(_.path)?_.path:null;if($){let C=T.createEl("button",{cls:"mdbase-link-button mdbase-transfer-open"});C.createEl("code",{text:_.path}),C.setAttr("title",`Open ${_.path}`),C.setAttr("data-focus-key",`preview-open-${_.path}`),C.onclick=()=>void this.ctx.host.openFileByPath($)}else T.createEl("code",{text:_.path});_.estimatedBytes!==void 0&&T.createSpan({cls:"mdbase-transfer-size",text:pr(_.estimatedBytes)}),_.direction==="attention"||["rename","replace","delete"].includes(_.action)?x.createDiv({text:_.detail}):E.setAttr("title",_.detail);let q=_.recordId;if(q&&_.kind==="document"&&_.action==="update"&&$){let C=`${q}:${_.path}`,V=this.previewComparisons.get(C),P=E.createEl("button",{text:V?"Hide":this.loadingPreviewComparisons.has(C)?"Loading\u2026":"Compare"});P.setAttr("data-focus-key",`preview-compare-${C}`),P.disabled=this.loadingPreviewComparisons.has(C),P.onclick=()=>{V?(this.previewComparisons.delete(C),this.ctx.render()):this.loadPreviewComparison(C,q,_.path)},V&&this.renderConflictComparison(x,V)}}if(h.length>250){let _=b.createDiv({cls:"mdbase-actions"});_.createSpan({cls:"mdbase-muted",text:`Showing ${S+1}\u2013${Math.min(S+250,h.length)} of ${h.length}`});let E=_.createEl("button",{text:`Previous ${p.title.toLowerCase()}`});E.disabled=v===0,E.setAttr("data-focus-key",`transfer-previous-${p.direction}`),E.onclick=()=>{this.transferPages.set(p.direction,v-1),this.ctx.render()};let k=_.createEl("button",{text:`Next ${p.title.toLowerCase()}`});k.disabled=S+250>=h.length,k.setAttr("data-focus-key",`transfer-next-${p.direction}`),k.onclick=()=>{this.transferPages.set(p.direction,v+1),this.ctx.render()}}}t.collisions.length?n.createDiv({cls:"mdbase-inline-error",text:"Colliding files and related moves are left unchanged. Independent files can still sync. Move or rename the obstruction, then review again."}):t.local_issues.length&&n.createDiv({cls:"mdbase-inline-message",text:t.plan.summary.blocking_issues>0?iy(t.plan,t.entries.length).message:"These diagnostics do not block synchronization. Document bytes are preserved unchanged."})}renderConflicts(e,t){let n=e.createEl("section",{cls:"mdbase-editor-section"});n.id="mdbase-sync-conflicts",n.createEl("h3",{text:"Conflicts"});for(let i of t.conflicts){let s=n.createDiv({cls:"mdbase-conflict-row"}),o=s.createDiv({cls:"mdbase-conflict-summary"});o.createEl("strong",{text:i.path??i.object_id}),o.createDiv({text:i.message});let a=s.createDiv({cls:"mdbase-actions"}),c=`${i.object_id}:${i.decision_id}`,l=this.conflictComparisons.get(c),u=a.createEl("button",{text:l?"Hide":this.loadingConflictComparisons.has(c)?"Loading\u2026":"Resolve\u2026"});if(u.setAttr("data-focus-key",`compare-${c}`),u.disabled=this.ctx.busy||this.loadingConflictComparisons.has(c),u.onclick=()=>{if(l){this.conflictComparisons.delete(c),this.ctx.render();return}this.loadConflictComparison(i,c)},l){for(let d of["local","remote"]){let f=a.createEl("button",{text:d==="local"?"Keep local":"Use hosted"});f.disabled=this.ctx.busy,f.onclick=()=>void this.resolveMirrorConflict(i,d,!1)}if(i.path){let d=a.createEl("button",{text:"Keep both"});d.disabled=this.ctx.busy,d.onclick=()=>void this.resolveMirrorConflict(i,"remote",!0)}this.renderConflictComparison(s,l)}}}async loadPreviewComparison(e,t,n){this.loadingPreviewComparisons.add(e),this.ctx.render();try{this.previewComparisons.set(e,await this.ctx.host.connectSync.recordComparison(t,n))}catch(i){this.ctx.message=Rt(i).message}finally{this.loadingPreviewComparisons.delete(e),this.ctx.render()}}async loadConflictComparison(e,t){this.loadingConflictComparisons.add(t),this.ctx.render();try{this.conflictComparisons.set(t,await this.ctx.host.connectSync.conflictComparison(e))}catch(n){this.session.reportProblem(n).code==="conflict_decision_stale"&&await this.session.refreshStatus()}finally{this.loadingConflictComparisons.delete(t),this.ctx.render()}}renderConflictComparison(e,t){let n=e.createDiv({cls:"mdbase-conflict-comparison"});if(t.entity==="record"){let s=F$(t.local.document??"",t.remote.document??""),o=n.createDiv({cls:"mdbase-conflict-legend"});o.createSpan({text:"\u2212 Local only",cls:"is-local"}),o.createSpan({text:"+ Hosted only",cls:"is-remote"});let a=n.createEl("pre",{cls:"mdbase-conflict-diff"});for(let c of s.lines){let l=a.createEl("div",{cls:`is-${c.kind}`});l.createSpan({text:c.kind==="local"?"\u2212":c.kind==="remote"?"+":" "}),l.createSpan({text:c.value||" "})}s.truncated&&n.createDiv({cls:"mdbase-muted",text:"Diff shortened for a responsive review. Open the local note to inspect it in full."});return}let i=n.createDiv({cls:"mdbase-conflict-sides"});this.renderConflictSide(i,"Local",t.local),this.renderConflictSide(i,"Hosted",t.remote)}renderConflictSide(e,t,n){let i=e.createDiv({cls:"mdbase-conflict-side"});if(i.createEl("h4",{text:t}),n.state==="absent"){i.createDiv({cls:"mdbase-muted",text:"File is absent in this version."});return}if(n.path&&i.createEl("code",{text:n.path}),n.size!==void 0&&i.createDiv({text:`Size: ${pr(n.size)}`}),n.modifiedAt&&i.createDiv({text:`Modified: ${new Date(n.modifiedAt).toLocaleString()}`}),n.revision&&i.createDiv({cls:"mdbase-conflict-digest",text:`Digest: ${n.revision}`}),n.resourceUrl&&n.path&&/\.(?:avif|gif|jpe?g|png|svg|webp)$/i.test(n.path)){let s=i.createEl("img",{cls:"mdbase-conflict-image-preview"});s.src=n.resourceUrl,s.alt=`${t} preview of ${n.path}`}else t==="Hosted"&&i.createDiv({cls:"mdbase-muted",text:"Hosted binary preview is materialized only after you choose it."})}async resolveMirrorConflict(e,t,n){await this.ctx.perform(async()=>{await this.session.resolveConflict(e,t,n)&&this.conflictComparisons.delete(`${e.object_id}:${e.decision_id}`)})}renderLocalMirrorIssues(e,t){let n=e.createEl("section",{cls:"mdbase-editor-section"});n.createEl("h3",{text:"Local files needing attention"}),n.createEl("p",{text:"Review these file diagnostics. The sync preview identifies which issues block synchronization; a diagnostic alone does not mean syncing is paused."});for(let i of t.local_issues){let s=n.createDiv({cls:"mdbase-conflict-row"}),o=s.createDiv();o.createEl("strong",{text:i.path}),o.createDiv({text:i.message});let c=s.createDiv({cls:"mdbase-actions"}).createEl("button",{text:"Open file"});c.disabled=this.ctx.busy,c.onclick=()=>void this.ctx.host.openFileByPath(i.path)}}async refresh(){if(!this.session.isSyncing()){if(!this.ctx.host.getMirrorProfile()){if(!this.ctx.schema||this.enrollmentAbort)return;try{this.adoptionPreview=await this.ctx.host.connectSync.previewAdoption(this.filePolicy())}catch(e){this.ctx.message=Rt(e).message}return}await this.session.refreshStatus()}}};var Ze=require("obsidian");qt();function U$(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Ds(r){return typeof r=="number"&&Number.isFinite(r)?r:null}function sy(r,e,t=""){let n=t?` ${t}`:"";return r!==null&&e!==null?r===e?`${r}${n}`:`${r}\u2013${e}${n}`:r!==null?`\u2265 ${r}${n}`:e!==null?`\u2264 ${e}${n}`:null}function sn(r){return typeof r=="string"?r:typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r):JSON.stringify(r)??""}function oy(r){let e=sn(r);return e.length>24?`${e.slice(0,23)}\u2026`:e}function V$(r){let e=typeof r.type=="string"?r.type:"any",t=[];if(e==="enum"&&Array.isArray(r.values)){let n=r.values.map(oy);t.push(n.length>3?`${n.slice(0,3).join(", ")}, +${n.length-3}`:n.join(", ")||"no values")}if(e==="integer"||e==="number"){let n=sy(Ds(r.min),Ds(r.max));n&&t.push(n)}if(e==="list"){let n=sy(Ds(r.min_length),Ds(r.max_length),"items");n&&t.push(n),U$(r.items)&&typeof r.items.type=="string"&&t.push(`of ${r.items.type}`)}else{let n=sy(Ds(r.min_length),Ds(r.max_length),"chars");n&&t.push(n)}if(typeof r.pattern=="string"&&r.pattern&&t.push(`/${oy(r.pattern)}/`),e==="link"&&typeof r.target=="string"&&r.target&&t.push(`\u2192 ${r.target}`),e==="object"&&U$(r.fields)){let n=Object.keys(r.fields).length;t.push(`${n} ${n===1?"field":"fields"}`)}return r.default!==void 0&&t.push(`default ${oy(r.default)}`),r.unique===!0&&t.push("unique"),r.deprecated===!0&&t.push("deprecated"),t}function H$(r,e,t){if(e!==void 0&&sn(e)===r)return e;let n=r.trim()!==""&&Number.isFinite(Number(r)),i=r==="true"||r==="false",s=o=>t.length>0&&t.every(a=>typeof a===o);return n&&(typeof e=="number"||typeof e!="boolean"&&s("number"))?Number(r):i&&(typeof e=="boolean"||typeof e!="number"&&s("boolean"))?r==="true":r}function z$(r,e){if(r==="")return{};if(e==="integer"||e==="number"){let t=Number(r);return Number.isFinite(t)?e==="integer"&&!Number.isInteger(t)?{error:"Default must be a whole number."}:{value:t}:{error:"Default must be a number."}}return e==="boolean"?r==="true"?{value:!0}:r==="false"?{value:!1}:{error:"Default must be true or false."}:{value:r}}var Un=require("@codemirror/commands"),Vn=require("@codemirror/language"),Wt=require("@codemirror/state"),xt=require("@codemirror/view"),Bn=require("@lezer/highlight"),rj=Vn.StreamLanguage.define({startState:()=>({section:"start"}),copyState:r=>({...r}),token(r,e){return r.sol()&&r.match(/^---\s*$/)?(e.section=e.section==="start"?"yaml":"body","meta"):e.section==="body"?(r.skipToEnd(),null):(e.section==="start"&&(e.section="yaml"),r.eatSpace()?null:r.match("#")?(r.skipToEnd(),"comment"):r.match(/^-(?=\s|$)/)?"punctuation":r.match(/^(?:[^\s:#'"[\]{},][^:#]*?|"[^"]*"|'[^']*')(?=\s*:(?:\s|$))/)?"propertyName":r.match(/^"(?:[^"\\]|\\.)*"?/)||r.match(/^'(?:[^']|'')*'?/)?"string":r.match(/^-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?(?=[\s,\]}]|$)/)?"number":r.match(/^(?:true|false|null|~)(?=[\s,\]}]|$)/)?"atom":r.match(/^[:[\]{},|>]/)?"punctuation":(r.eatWhile(/[^\s#:,[\]{}]/),r.current()===""&&r.next(),"string"))}}),nj=Vn.HighlightStyle.define([{tag:Bn.tags.propertyName,color:"var(--text-accent)"},{tag:Bn.tags.string,color:"var(--text-normal)"},{tag:Bn.tags.number,color:"var(--color-orange)"},{tag:Bn.tags.atom,color:"var(--color-purple)"},{tag:Bn.tags.comment,color:"var(--text-faint)",fontStyle:"italic"},{tag:Bn.tags.meta,color:"var(--text-faint)"},{tag:Bn.tags.punctuation,color:"var(--text-muted)"}]),K$=Wt.StateEffect.define(),ij=Wt.StateField.define({create:()=>xt.Decoration.none,update(r,e){let t=r.map(e.changes);for(let n of e.effects){if(!n.is(K$))continue;let i=new Wt.RangeSetBuilder,s=[...new Set(n.value.map(o=>o.line).filter(o=>o!==null&&o>=1&&o<=e.state.doc.lines))].sort((o,a)=>o-a);for(let o of s){let a=e.state.doc.line(o),c=n.value.find(l=>l.line===o)?.severity??"error";i.add(a.from,a.from,xt.Decoration.line({class:`mdbase-yaml-problem-line is-${c}`}))}t=i.finish()}return t},provide:r=>xt.EditorView.decorations.from(r)}),Ad=class{constructor(e){this.editable=new Wt.Compartment;this.applyingExternalChange=!1;this.view=new xt.EditorView({state:Wt.EditorState.create({doc:e.doc,extensions:[(0,xt.lineNumbers)(),(0,Un.history)(),Vn.indentUnit.of(" "),Wt.EditorState.tabSize.of(2),xt.keymap.of([...Un.defaultKeymap,...Un.historyKeymap,Un.indentWithTab]),rj,(0,Vn.syntaxHighlighting)(nj),ij,xt.EditorView.lineWrapping,this.editable.of(this.editability(e.readOnly)),xt.EditorView.contentAttributes.of({"aria-labelledby":e.labelledBy,"data-focus-key":"yaml-editor",spellcheck:"false"}),xt.EditorView.updateListener.of(t=>{t.docChanged&&!this.applyingExternalChange&&e.onChange(t.state.doc.toString())})]})}),this.dom=this.view.dom,this.dom.addClass("mdbase-yaml-editor")}get value(){return this.view.state.doc.toString()}setValue(e){if(e!==this.value){this.applyingExternalChange=!0;try{this.view.dispatch({changes:{from:0,to:this.view.state.doc.length,insert:e}})}finally{this.applyingExternalChange=!1}}}setReadOnly(e){this.view.dispatch({effects:this.editable.reconfigure(this.editability(e))})}setProblems(e){this.view.dispatch({effects:K$.of(e)})}revealLine(e){if(e<1||e>this.view.state.doc.lines)return;let t=this.view.state.doc.line(e).from;this.view.dispatch({selection:{anchor:t},scrollIntoView:!0}),this.view.focus()}destroy(){this.view.destroy()}editability(e){return[Wt.EditorState.readOnly.of(e),xt.EditorView.editable.of(!e)]}};function W$(r,e=2){let t=r.match(/line (\d+)/i)??r.match(/\((\d+):\d+\)/);return t?Number(t[1])+e-1:null}function ay(r,e){if(!e)return null;let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^\\s*(?:-\\s+)?["']?${t}["']?\\s*:`),s=r.split(` +`).findIndex(o=>n.test(o));return s===-1?null:s+1}var kd=class{constructor(e){this.ctx=e;this.editorMode="design";this.query="";this.selectedPath=null;this.model=null;this.originalModel=null;this.yamlDraft="";this.dirty=!1;this.migrationPlan=null;this.allowLossy=!1;this.statsCache=null;this.impact=null;this.impactVersion=0;this.impactTimer=null;this.showAllMatches=!1;this.pendingFieldReveal=null;this.sessionDrafts=new Set;this.yamlEditor=null;this.yamlProblemTimer=null;this.draftSaveTimer=null;this.fieldQuery="";this.expandedFields=new Set;this.fieldIds=new WeakMap;this.nextFieldId=1;this.typeSelectionVersion=0}async onSchemaLoaded(e,t){if(this.selectedPath&&!this.typeEntries().some(n=>n.filePath===this.selectedPath)&&(this.selectedPath=null,this.model=null,this.originalModel=null),!this.selectedPath&&this.typeEntries().length&&!Ze.Platform.isMobile&&(this.selectedPath=this.typeEntries()[0].filePath),this.selectedPath&&(!this.model||e)){if(this.dirty&&await this.flushTypeDraft(),!t())return;await this.selectType(this.selectedPath,!1)}}onRecordsLoaded(e){(e||!this.impact)&&this.scheduleImpact(0)}afterRender(e){if(!this.pendingFieldReveal)return;let t=e.querySelector(`[data-field-id="${this.pendingFieldReveal}"]`);t&&(t.scrollIntoView({block:"nearest"}),(!e.contains(e.ownerDocument.activeElement)||e.ownerDocument.activeElement===e.ownerDocument.body)&&t.querySelector("summary")?.focus({preventScroll:!0}),t.addClass("is-revealed")),this.pendingFieldReveal=null}getState(){return{selectedPath:this.selectedPath,editorMode:this.editorMode,query:this.query,fieldQuery:this.fieldQuery}}async setState(e){for(let t of["query","fieldQuery"])typeof e[t]=="string"&&(this[t]=e[t].slice(0,2e3));typeof e.selectedPath=="string"&&e.selectedPath!==this.selectedPath&&(await this.leaveCurrentType(),this.selectedPath=e.selectedPath,this.model=null,this.originalModel=null)}restoreEditorMode(e){e==="yaml"&&this.editorMode!=="yaml"&&this.switchEditorMode("yaml")}async dispose(){this.impactTimer!==null&&window.clearTimeout(this.impactTimer),this.yamlProblemTimer!==null&&window.clearTimeout(this.yamlProblemTimer),this.impactVersion++,await this.flushTypeDraft(),this.yamlEditor?.destroy(),this.yamlEditor=null}async openTypeField(e,t){this.ctx.destination="types",(e!==this.selectedPath||!this.model)&&await this.selectType(e),!(!this.model||this.selectedPath!==e)&&(t&&this.revealField(t),this.ctx.render())}revealField(e){if(!this.model)return;let t=e.split(".").filter(Boolean),n=t.shift()?.replace(/\[\]$/g,"")??"",i=this.model.fields.find(s=>s.name===n)?.definition;if(i){this.editorMode="design",this.fieldQuery="",this.expandedFields.add(this.fieldId(i));for(let s of t){let o=s.replace(/\[\]$/g,""),a=Se(i.items)?i.items:i,c=Se(a.fields)?a.fields[o]:void 0;if(!Se(c))break;a!==i&&this.expandedFields.add(this.fieldId(a)),i=c,this.expandedFields.add(this.fieldId(i))}this.pendingFieldReveal=this.fieldId(i)}}currentStats(){let e=this.ctx.host.getIssues(),t=this.ctx.schema?.types??null,n=this.statsCache;if(n&&n.records===this.ctx.records&&n.types===t&&n.issues===e)return n;let i=this.ctx.records&&this.ctx.schema?k$(this.ctx.records,this.ctx.schema.config,this.ctx.schema.types):new Map;return this.statsCache={records:this.ctx.records,types:t,issues:e,recordTypes:i,stats:P$(i,e)},this.statsCache}scheduleImpact(e=400){this.impactTimer!==null&&window.clearTimeout(this.impactTimer),this.impactTimer=window.setTimeout(()=>{this.impactTimer=null,this.computeImpact().then(t=>{t!==void 0&&(this.impact=t,this.updateImpactRegions())})},e)}async computeImpact(){let e=++this.impactVersion,t=this.editorMode==="yaml"?this.modelFromYamlDraft():null;if(t&&"error"in t)return{error:t.error};let n=t?.model??this.model;if(!n||!this.ctx.schema||!this.ctx.records||n.specProfile!=="v0.3"||n.readOnlyReason)return null;let i=this.selectedPath?[...this.ctx.schema.types.values()].find(o=>o.filePath===this.selectedPath)?.name??null:null,s=await M$({records:this.ctx.records,config:this.ctx.schema.config,types:this.ctx.schema.types,draft:n,savedName:i,filePath:this.selectedPath,isCurrent:()=>e===this.impactVersion});return e===this.impactVersion&&s!==null?s:void 0}updateImpactRegions(){let e=this.ctx.containerEl.querySelector(".mdbase-match-preview");e&&(e.empty(),this.fillMatchPreview(e));let t=this.ctx.containerEl.querySelector("[data-disclosure='type-matching'] > summary");t&&(t.textContent=this.matchingLabel());let n=this.ctx.containerEl.querySelector(".mdbase-impact");n&&(n.empty(),this.fillImpact(n));let i=this.ctx.containerEl.querySelector(".mdbase-type-editor-pane"),s=i?.querySelector(".mdbase-draft-bar");i&&s&&this.model&&(s.remove(),this.renderDraftBar(i,this.model))}createNewType(){this.ctx.destination="types",this.createType()}async editType(e){this.ctx.destination="types",await this.selectType(e)}typeEntries(){return this.ctx.schema?[...this.ctx.schema.types.values()].sort((e,t)=>e.name.localeCompare(t.name)):[]}renderSetup(e){let t=e.createDiv({cls:"mdbase-empty-state mdbase-setup"});if(this.ctx.host.getMirrorProfile()){t.createEl("h2",{text:"Waiting for the first sync"}),t.createEl("p",{text:"Types appear here once the hosted collection has synced."});let s=t.createEl("button",{text:"Open sync",cls:"mod-cta"});s.onclick=()=>this.ctx.showDestination("sync");return}t.createEl("h2",{text:"Set up mdbase"});let n=t.createDiv({cls:"mdbase-setup-choices"}),i=(s,o,a,c)=>{let l=n.createDiv({cls:"mdbase-setup-choice"}),u=l.createDiv();u.createEl("strong",{text:s}),u.createDiv({cls:"mdbase-muted",text:o});let d=l.createEl("button",{text:s,cls:a?"mod-cta":""});d.disabled=this.ctx.busy,d.onclick=c};i("Start a collection","This vault holds the collection. You can upload it to Connect later.",!0,()=>{this.ctx.perform(async()=>{await this.ctx.host.initializeCollection(),await this.ctx.refresh(!0)})}),i("Copy from Connect","Connect holds the collection. This vault syncs a copy.",!1,()=>{this.ctx.showDestination("sync")})}render(e){if(!this.ctx.schema){this.renderSetup(e);return}if(this.ctx.schema.config.spec_version.startsWith("0.2.")&&this.renderLegacyBanner(e),!this.typeEntries().length&&!this.model){let n=e.createDiv({cls:"mdbase-empty-state"});n.createEl("h2",{text:"Add your first type"}),n.createEl("p",{text:"Install ready-made types and application contracts from mdbase-contracts, or design your own type."});let i=n.createDiv({cls:"mdbase-actions"}),s=i.createEl("button",{text:"Browse ready-made types",cls:"mod-cta"});s.disabled=this.ctx.busy||this.ctx.schema.config.spec_version.startsWith("0.2.")||this.ctx.host.getMirrorProfile()!==null,s.onclick=()=>void this.ctx.perform(()=>this.ctx.host.openContractCatalog());let o=i.createEl("button",{text:"Design a custom type"});o.disabled=this.ctx.schema.config.spec_version.startsWith("0.2.")||this.ctx.host.getMirrorProfile()?.mode==="read_only",o.onclick=()=>void this.createType();return}let t=e.createDiv({cls:"mdbase-types-layout"});this.model&&t.addClass("has-selection"),this.renderTypeList(t),this.renderTypeEditor(t)}renderLegacyBanner(e){let t=e.createDiv({cls:"mdbase-legacy-banner"}),n=t.createDiv();if(n.createEl("strong",{text:"Read-only \xB7 v0.2 collection"}),n.createEl("p",{text:"Migrate to edit types."}),!this.migrationPlan){let i=t.createEl("button",{text:"Review migration"});i.disabled=this.ctx.busy||this.ctx.host.getMirrorProfile()!==null,i.onclick=()=>void this.ctx.perform(async()=>{this.migrationPlan=await this.ctx.host.analyzeMigration(),this.ctx.render()})}this.ctx.host.getMirrorProfile()&&t.createDiv({cls:"mdbase-form-description",text:"Hosted resources must be migrated at the collection authority."}),this.migrationPlan&&this.renderMigrationReview(e,this.migrationPlan)}renderMigrationReview(e,t){let n=e.createDiv({cls:"mdbase-migration-review"}),i=n.createDiv({cls:"mdbase-section-header"});i.createEl("h3",{text:"Migration review"}),i.createSpan({cls:"mdbase-spec-badge",text:`${t.sourceVersion} \u2192 ${t.targetVersion}`});let s=n.createDiv({cls:"mdbase-status-list"});Kt(s,"Files replaced",String(t.operations.length)),Kt(s,"Type definitions",String(t.typeSummaries.length)),Kt(s,"Record reads verified",String(t.recordsVerified)),t.recordsSkipped&&Kt(s,"Records skipped",String(t.recordsSkipped)),Kt(s,"Record files rewritten","0"),Kt(s,"Recovery backup",t.backupLocation);let o=n.createDiv({cls:"mdbase-review-list"});t.diagnostics.length||o.createDiv({cls:"mdbase-review-ok",text:"No migration diagnostics."});for(let u of t.diagnostics.slice(0,250)){let d=o.createDiv({cls:"mdbase-review-item"});d.setAttr("data-severity",u.severity),d.createDiv({cls:"mdbase-review-code",text:`${u.severity} \xB7 ${u.path}`}),d.createDiv({text:u.message})}if(t.diagnostics.length>250&&o.createDiv({cls:"mdbase-form-description",text:`Showing 250 of ${t.diagnostics.length} diagnostics.`}),!t.applicable){let u=n.createEl("label",{cls:"mdbase-consent"}),d=u.createEl("input",{type:"checkbox"});d.checked=this.allowLossy,d.onchange=()=>{this.allowLossy=d.checked,this.ctx.render()},u.createSpan({text:"I reviewed the lossy diagnostics and want to apply this migration."})}let a=n.createDiv({cls:"mdbase-actions"}),c=a.createEl("button",{text:"Apply migration"});c.addClass("mod-warning"),c.disabled=this.ctx.busy||!t.applicable&&!this.allowLossy,c.onclick=()=>void this.ctx.perform(async()=>{await this.ctx.host.applyMigration(t,this.allowLossy),this.migrationPlan=null,this.allowLossy=!1,this.model=null,this.originalModel=null,await this.ctx.refresh(!0)});let l=a.createEl("button",{text:"Close review"});l.onclick=()=>{this.migrationPlan=null,this.ctx.render()}}renderTypeList(e){let t=e.createDiv({cls:"mdbase-type-list-pane"}),n=t.createDiv({cls:"mdbase-pane-header"});n.createEl("h2",{text:"Types"});let i=this.ctx.iconButton(n,"download","Browse ready-made types");i.disabled=this.ctx.busy||this.ctx.schema?.config.spec_version.startsWith("0.2.")===!0||this.ctx.host.getMirrorProfile()!==null,i.onclick=()=>void this.ctx.perform(()=>this.ctx.host.openContractCatalog());let s=this.ctx.schema?.config.spec_version.startsWith("0.2.")??!0?"Migrate to v0.3 to create types":this.ctx.host.getMirrorProfile()?.mode==="read_only"?"Read-only mirror":"",o=this.ctx.iconButton(n,"plus",s?`Create type \xB7 ${s}`:"Create type");o.disabled=!!s,o.onclick=()=>void this.createType();let a=t.createEl("input",{type:"search"});a.addClass("mdbase-type-search"),a.placeholder="Search types",a.setAttr("aria-label","Search types"),a.setAttr("data-focus-key","type-search"),a.value=this.query,a.oninput=()=>{this.query=a.value,this.ctx.render();let f=this.ctx.containerEl.querySelector(".mdbase-type-search");f?.focus(),f?.setSelectionRange(f.value.length,f.value.length)};let c=t.createDiv({cls:"mdbase-type-list"});c.setAttr("data-scroll-key","type-list");let l=this.query.trim().toLowerCase(),u=this.typeEntries().filter(f=>`${f.name} ${f.description??""} ${f.filePath}`.toLowerCase().includes(l));if(!u.length){c.createDiv({cls:"mdbase-empty-list",text:l?"No matching types.":"No type definitions."});return}let{stats:d}=this.currentStats();for(let f of u){let p=c.createEl("button",{cls:"mdbase-type-row"});f.filePath===this.selectedPath&&p.addClass("is-active"),p.setAttr("aria-current",f.filePath===this.selectedPath?"true":"false");let h=p.createDiv({cls:"mdbase-type-name-line"});if(h.createSpan({cls:"mdbase-type-name",text:f.name}),f.filePath===this.selectedPath?this.dirty:this.ctx.host.loadTypeDraft(f.filePath)!==null){let g=h.createSpan({cls:"mdbase-unsaved-dot"});g.setAttr("aria-label","Unsaved changes"),g.setAttr("title","Unsaved changes")}let y=d.get(f.name);if(this.ctx.records){let g=p.createDiv({cls:"mdbase-type-meta"}),b=y?.notes??0;g.createSpan({text:`${b.toLocaleString()} ${b===1?"note":"notes"}`}),y?.issues&&g.createSpan({cls:"mdbase-type-issues",text:`${y.issues.toLocaleString()} ${y.issues===1?"issue":"issues"}`})}p.onclick=()=>void this.selectType(f.filePath)}}renderTypeEditor(e){let t=e.createDiv({cls:"mdbase-type-editor-pane"});if(t.setAttr("data-scroll-key","type-editor"),!this.model){t.createDiv({cls:"mdbase-empty-state"}).createEl("p",{text:"Select a type"});return}let n=this.ctx.host.getMirrorProfile()?.mode==="read_only",i=this.model.specProfile==="v0.2"||n||!!this.model.readOnlyReason,s=this.model.readOnlyReason??(n?"Read-only mirror. Reconnect with write access to edit.":"Migrate this v0.2 collection to edit types."),o=t.createDiv({cls:"mdbase-editor-header"}),a=this.ctx.iconButton(o,"arrow-left","Back to type list");a.addClass("mdbase-mobile-back"),a.onclick=()=>void this.leaveCurrentType().then(()=>{this.selectedPath=null,this.model=null,this.originalModel=null,this.ctx.render()});let c=o.createDiv({cls:"mdbase-editor-heading"});c.createDiv({cls:"mdbase-editor-title-line"}).createEl("h2",{text:this.model.name||"Untitled type"}),c.createDiv({cls:"mdbase-editor-path",text:this.selectedPath??"New type"});let u=o.createDiv({cls:"mdbase-editor-actions"});if(this.selectedPath){let p=this.selectedPath,h=this.ctx.iconButton(u,"file-code","Open source");h.onclick=()=>void this.ctx.host.openFileByPath(p)}if(this.selectedPath){let p=this.model.name,h=u.createEl("button",{text:"New note"});h.disabled=i||this.ctx.busy,h.onclick=()=>void this.ctx.host.createNoteFromType(p),this.renderStaleDrafts(t)}i&&t.createDiv({cls:"mdbase-readonly-note",text:s});let d=t.createDiv({cls:"mdbase-mode-switch"});d.setAttr("role","tablist");for(let[p,h]of[["design","Design"],["yaml","YAML"]]){let m=d.createEl("button",{text:h});m.id=`mdbase-mode-${p}`,m.setAttr("role","tab"),m.setAttr("aria-selected",String(this.editorMode===p)),this.editorMode===p&&m.addClass("is-active"),m.onclick=()=>this.switchEditorMode(p)}let f=t.createDiv({cls:"mdbase-editor-document"});f.setAttr("data-scroll-key","type-document"),this.editorMode==="design"?this.renderDesignEditor(f,this.model,i):this.renderYamlEditor(f,i),this.dirty&&!i&&this.renderDraftBar(t,this.model)}renderStaleDrafts(e){if(!this.selectedPath||!this.originalModel)return;let t=this.selectedPath,n=this.ctx.host.loadTypeDraft(t),i=[...this.ctx.host.getArchivedTypeDrafts(t),...n&&n.sourceRevision!==(this.originalModel.sourceRevision??null)?[n]:[]];for(let s of i){let o=e.createDiv({cls:"mdbase-recovery-card"});o.createDiv({text:`An older draft from ${new Date(s.updatedAt).toLocaleString()} is available. The source changed; it will not be applied automatically.`});let a=o.createEl("button",{text:"Compare draft"});a.onclick=()=>{let u=new Ze.Modal(this.ctx.app);u.titleEl.setText("Current source and recovered draft");let d=s.yamlDraft;if(d===void 0)try{d=mt(Aa(s.model),s.model.body)}catch{d=JSON.stringify(s.model,null,2)}u.contentEl.createEl("h3",{text:"Current source"}),u.contentEl.createEl("pre",{text:this.originalModel?mt(Aa(this.originalModel),this.originalModel.body):this.yamlDraft}),u.contentEl.createEl("h3",{text:"Recovered draft (read-only)"}),u.contentEl.createEl("pre",{text:d}),u.contentEl.createEl("p",{text:"Copy the parts you want into the current definition, then review before saving."}),u.open()};let c=o.createEl("button",{text:"Export draft"});c.onclick=()=>void this.ctx.perform(async()=>{let u="mdbase-draft-recovery";this.ctx.app.vault.getAbstractFileByPath(u)||await this.ctx.app.vault.createFolder(u);let d=await this.ctx.app.vault.create(`${u}/draft-${crypto.randomUUID()}.txt`,s.yamlDraft??JSON.stringify(s.model,null,2));this.ctx.message=`Exported recovery draft to ${d.path}. The original draft is still retained.`});let l=o.createEl("button",{text:"Discard old draft"});l.onclick=()=>{let u=new Ze.Modal(this.ctx.app);u.titleEl.setText("Discard this recovered draft?"),u.contentEl.createEl("p",{text:"This removes the saved recovery copy, not the current source or your current edits. Export it first if you might need it."}),u.contentEl.createEl("button",{text:"Cancel"}).onclick=()=>u.close(),u.contentEl.createEl("button",{text:"Discard old draft",cls:"mod-warning"}).onclick=()=>{u.close(),this.ctx.perform(async()=>{s===n?await this.ctx.host.clearTypeDraft(t):await this.ctx.host.discardArchivedTypeDraft(s)})},u.open()}}}renderDraftBar(e,t){let n=Sa(this.originalModel,t),s=_a(t,{knownTypes:this.typeEntries().map(m=>m.name),contracts:this.ctx.schema?.contracts.values()}).filter(m=>m.severity==="error").length,o=n.filter(m=>m.risk==="high").length,a=this.newlyFailing(),c=this.editorMode==="yaml"?this.yamlProblems().filter(m=>m.severity==="error").length:0,l=e.createDiv({cls:"mdbase-draft-bar"}),u=l.createDiv({cls:"mdbase-draft-summary"}),d=this.editorMode==="yaml"?c:s;u.setAttr("data-tone",d?"error":a||o?"warning":"normal"),u.createSpan({text:d?`${d} ${d===1?"error":"errors"}`:a?`${a} ${a===1?"note":"notes"} would fail`:o?`${o} high-impact ${o===1?"change":"changes"}`:"Unsaved changes"});let f=l.createDiv({cls:"mdbase-actions"});if(this.editorMode==="design"){let m=f.createEl("button",{text:"Review"});m.onclick=()=>{let g=this.ctx.containerEl.querySelector("#mdbase-section-review")?.closest("details");g&&(g.open=!0),this.ctx.render(),this.ctx.containerEl.querySelector("#mdbase-section-review")?.scrollIntoView({block:"nearest"})}}let p=f.createEl("button",{text:"Discard"});p.onclick=()=>void this.discardCurrentType();let h=f.createEl("button",{text:"Save"});h.addClass("mod-cta"),h.disabled=(this.editorMode==="design"?s>0:c>0)||this.ctx.busy,h.onclick=()=>void this.saveCurrentType()}newlyFailing(){return!this.dirty||!this.impact||"error"in this.impact?0:this.impact.impact.failing.filter(e=>e.isNew).length}matchingLabel(){let e=this.impact&&!("error"in this.impact)?this.impact.impact.matched.length:this.savedTypeName()?this.currentStats().stats.get(this.savedTypeName()??"")?.notes:void 0;return e===void 0||!this.ctx.records?"Matching":`Matching \xB7 ${e.toLocaleString()} ${e===1?"note":"notes"}`}savedTypeName(){return!this.selectedPath||!this.ctx.schema?null:[...this.ctx.schema.types.values()].find(e=>e.filePath===this.selectedPath)?.name??null}fillMatchPreview(e){let t=this.impact,n,i=[],s=[];if(t&&!("error"in t))({matched:n,added:i,removed:s}=t.impact);else{let d=this.savedTypeName();if(!this.ctx.records||!d||t&&"error"in t&&this.dirty){e.createDiv({cls:"mdbase-muted",text:this.ctx.records?t&&"error"in t?"Fix errors to preview matching notes.":"Save the type to preview matching notes.":"Counting notes\u2026"});return}n=[...this.currentStats().recordTypes].filter(([,f])=>f.includes(d)).map(([f])=>f)}let o=e.createDiv({cls:"mdbase-match-summary"});o.createSpan({text:`${n.length.toLocaleString()} ${n.length===1?"note matches":"notes match"}`}),i.length&&o.createSpan({cls:"mdbase-match-added",text:`${i.length} added`}),s.length&&o.createSpan({cls:"mdbase-match-removed",text:`${s.length} no longer match`});let a=new Set(i),c=[...i.map(d=>({path:d,change:"added"})),...s.map(d=>({path:d,change:"removed"})),...n.filter(d=>!a.has(d)).map(d=>({path:d,change:null}))];if(!c.length)return;let l=this.showAllMatches?200:5,u=e.createDiv({cls:"mdbase-match-list"});for(let d of c.slice(0,l)){let f=u.createEl("button",{cls:"mdbase-match-row"});d.change&&(f.setAttr("data-change",d.change),f.createSpan({cls:"mdbase-match-marker",text:d.change==="added"?"+":"\u2212",attr:{"aria-label":d.change==="added"?"Added":"No longer matches"}})),f.createSpan({text:d.path}),f.setAttr("title",`Open ${d.path}`),f.onclick=()=>void this.ctx.host.openFileByPath(d.path)}if(c.length>5){let d=e.createEl("button",{cls:"mdbase-link-button",text:this.showAllMatches?"Show fewer":c.length>200?`Show 200 of ${c.length.toLocaleString()}`:`Show all ${c.length.toLocaleString()}`});d.onclick=()=>{this.showAllMatches=!this.showAllMatches,e.empty(),this.fillMatchPreview(e)}}}fillImpact(e){let t=this.impact;if(!t){e.createDiv({cls:"mdbase-muted",text:this.ctx.records?"Checking notes\u2026":"Counting notes\u2026"});return}if("error"in t){e.createDiv({cls:"mdbase-muted",text:"Fix errors to check existing notes."});return}let{impact:n}=t,i=n.failing.filter(l=>l.isNew),s=n.failing.length-i.length,o=e.createDiv({cls:"mdbase-impact-heading"});o.setAttr("data-tone",i.length?"warning":"normal"),o.createEl("strong",{text:i.length?`${i.length} ${i.length===1?"note":"notes"} would fail`:"No notes newly fail"});let a=[`${n.matched.length.toLocaleString()} ${n.matched.length===1?"note":"notes"} checked`];if(n.fixed&&a.push(`${n.fixed} fixed`),s&&a.push(`${s} already failing`),o.createSpan({cls:"mdbase-muted",text:a.join(" \xB7 ")}),!i.length)return;let c=e.createDiv({cls:"mdbase-impact-list"});for(let l of i.slice(0,10)){let u=c.createDiv({cls:"mdbase-impact-row"}),d=u.createEl("button",{cls:"mdbase-link-button",text:l.path});d.onclick=()=>void this.ctx.host.openFileByPath(l.path,l.issues[0]?.field),u.createSpan({cls:"mdbase-muted",text:`${l.issues[0]?.message??""}${l.issues.length>1?` \xB7 +${l.issues.length-1} more`:""}`})}i.length>10&&c.createDiv({cls:"mdbase-muted",text:`${i.length-10} more notes`})}renderDesignEditor(e,t,n){let i=_a(t,{knownTypes:this.typeEntries().map(C=>C.name),contracts:this.ctx.schema?.contracts.values()}),s=e.createEl("section",{cls:"mdbase-editor-section"});s.id="mdbase-section-identity";let o=Tt(s,"Name",t.name,C=>{t.name=C,this.markDirty()});o.disabled=n;let a=Tt(s,"Description",t.description,C=>{t.description=C,this.markDirty()},{multiline:!0});a.disabled=n;let c=this.ctx.disclosure(e,"type-options","Options"),l=c.createDiv({cls:"mdbase-form-row"}),u=l.createEl("label",{text:"Display field"}),d=l.createEl("select");u.htmlFor=d.id="mdbase-display-field",d.createEl("option",{value:"",text:"Use the file name"});for(let C of t.fields)d.createEl("option",{value:C.name,text:C.name||"Unnamed field"});t.displayNameKey&&!t.fields.some(C=>C.name===t.displayNameKey)&&d.createEl("option",{value:t.displayNameKey,text:`${t.displayNameKey} \xB7 missing`}),d.value=t.displayNameKey,d.onchange=()=>{t.displayNameKey=d.value,this.markDirty()},d.disabled=n;let f=c.createEl("label",{cls:"mdbase-checkbox-row"}),p=f.createEl("input",{type:"checkbox"});p.checked=t.strictMode===!0,p.disabled=n,p.onchange=()=>{t.strictMode=p.checked,this.markDirty()},f.createSpan({text:"Reject undeclared fields"});let h=this.ctx.disclosure(e,"type-matching",this.matchingLabel());h.id="mdbase-section-membership",this.fillMatchPreview(h.createDiv({cls:"mdbase-match-preview"}));let m=Tt(h,"Path glob",t.matchPathGlob,C=>{t.matchPathGlob=C,this.markDirty()},{placeholder:"Projects/**/*.md"});m.disabled=n;let y=Tt(h,"Fields present",t.matchFieldsPresent,C=>{t.matchFieldsPresent=C,this.markDirty()},{description:"Comma-separated frontmatter keys."});y.disabled=n;let g=Tt(h,"Where",t.matchWhere,C=>{t.matchWhere=C,this.markDirty()},{multiline:!0,description:"YAML predicate, including contains and nested equality conditions.",placeholder:`tags: + contains: task`});g.disabled=n;let b=e.createEl("section",{cls:"mdbase-editor-section"});b.id="mdbase-section-fields";let v=b.createDiv({cls:"mdbase-section-header"});v.createEl("h3",{text:"Fields"});let S=v.createDiv({cls:"mdbase-section-actions"});if(this.expandedFields.size){let C=this.ctx.iconButton(S,"fold-vertical","Collapse all fields");C.onclick=()=>{this.expandedFields.clear(),this.ctx.render()}}let _=this.ctx.iconButton(S,"plus","Add field");if(_.disabled=n,_.onclick=()=>{let C={type:"string"};t.fields.push({name:"",definition:C}),this.expandedFields.add(this.fieldId(C)),this.markDirty(!0)},t.fields.length>6||this.fieldQuery){let P=b.createDiv({cls:"mdbase-field-toolbar"}).createDiv({cls:"mdbase-field-toolbar-actions"}).createEl("input",{type:"search"});P.placeholder="Filter fields",P.setAttr("aria-label","Filter fields"),P.setAttr("data-focus-key","field-search"),P.value=this.fieldQuery,P.oninput=()=>{this.fieldQuery=P.value,this.ctx.render()}}let E=b.createDiv({cls:"mdbase-fields"}),k=this.fieldQuery.trim().toLowerCase(),x=t.fields.filter(C=>!k||this.fieldMatches(C.name,C.definition,k));for(let C of x){let V=t.fields.indexOf(C);this.renderFieldRow(E,C,V,n)}x.length||E.createDiv({cls:"mdbase-empty-list",text:t.fields.length?"No fields match this filter.":"No fields declared."}),h.parentElement&&e.appendChild(h.parentElement),c.parentElement&&e.appendChild(c.parentElement);let $=Tt(c,"Path pattern",t.pathPattern,C=>{t.pathPattern=C,this.markDirty()},{placeholder:"Notes/{title}.md"});if($.disabled=n,this.renderContractEditor(e,t,n),!this.dirty&&!i.length)return;let q=this.ctx.disclosure(e,"type-review","Changes",i.some(C=>C.severity==="error"));if(q.id="mdbase-section-review",this.dirty&&this.fillImpact(q.createDiv({cls:"mdbase-impact"})),i.length){let C=q.createDiv({cls:"mdbase-diagnostic-summary"}),V=i.filter(M=>M.severity==="error").length,P=i.length-V;C.createEl("strong",{text:`${V} ${V===1?"error":"errors"} \xB7 ${P} ${P===1?"warning":"warnings"}`});for(let M of i.slice(0,12)){let Be=C.createDiv({cls:"mdbase-diagnostic-item"});Be.setAttr("data-severity",M.severity),Be.createEl("code",{text:M.path}),Be.createSpan({text:M.message})}}if(this.dirty){let C=q.createEl("ul");for(let V of Sa(this.originalModel,t))C.createEl("li",{text:V.summary}).setAttr("data-risk",V.risk)}}renderContractEditor(e,t,n){let i=this.ctx.disclosure(e,"type-applications","Applications");i.addClass("mdbase-contracts-section"),i.id="mdbase-section-applications";let s=[...this.ctx.schema?.contracts.values()??[]],o=new Set(t.implementations.map(c=>`${c.contract}@${c.version}`)),a=s.filter(c=>!o.has(Ts(c)));s.length||i.createDiv({cls:"mdbase-contract-empty",text:"No application contracts installed."});for(let c of t.implementations){let l=s.find(u=>u.id===c.contract&&u.version===c.version);this.renderContractImplementation(i,t,c,l,n)}if(a.length){let c=i.createDiv({cls:"mdbase-contract-add"}),l=c.createEl("label",{text:"Installed contract"}),u=c.createEl("select");l.htmlFor=u.id=`mdbase-contract-${Math.random().toString(36).slice(2)}`;for(let f of a)u.createEl("option",{value:Ts(f),text:`${f.id} \xB7 ${f.version}`});let d=c.createEl("button",{text:"Add contract"});d.disabled=n,d.onclick=()=>{let f=a.find(p=>Ts(p)===u.value);if(f)try{g$(t,f),this.markDirty(!0)}catch(p){new Ze.Notice(p instanceof Error?p.message:String(p))}}}}renderContractImplementation(e,t,n,i,s){let o=e.createEl("article",{cls:"mdbase-contract-implementation"}),a=o.createDiv({cls:"mdbase-contract-header"}),c=a.createDiv();c.createEl("strong",{text:n.contract}),c.createSpan({cls:"mdbase-contract-version",text:n.version});let l=a.createEl("button",{text:"Remove"});if(l.disabled=s,l.onclick=()=>{b$(t,n.contract,n.version),this.markDirty(!0)},!i){o.createDiv({cls:"mdbase-contract-unavailable",text:"This exact contract is not installed in the collection. Restore it or remove this implementation before saving."});return}let u=ga(i),d=ba(t),f=u.filter(b=>Rs(n,b)),p=u.filter(b=>b.required),h=p.filter(b=>Rs(n,b)).length,m=o.createEl("details");m.open=h$.reference===v),_=va(b,S),E=g.createDiv({cls:`mdbase-contract-mapping-row ${_.level}`}),k=E.createDiv({cls:"mdbase-contract-field-definition"});k.createEl("code",{text:b.reference}),k.createSpan({cls:b.required?"mdbase-contract-required":"mdbase-contract-optional",text:b.required?"Required":"Optional"}),k.createEl("small",{text:b.description||w$(b.schema)});let x=E.createEl("select");x.setAttr("aria-label",`${n.contract} ${b.reference} source field`),x.setAttr("aria-invalid",_.level==="error"?"true":"false"),x.disabled=s,x.createEl("option",{value:"",text:b.required?"Choose a source field":"Not exposed"});for(let $ of d){let q=va(b,$),C=x.createEl("option",{value:$.reference,text:`${$.reference} \xB7 ${$.type}${q.level==="warning"?" \xB7 review":""}`});C.disabled=q.level==="error"}x.value=v,x.onchange=()=>{v$(n,b.reference,x.value||void 0),this.markDirty(!0)};let T=E.createDiv({cls:"mdbase-contract-mapping-status"});T.createEl("strong",{text:_.label}),T.createEl("small",{text:_.message})}if(i.binding_schema){let b=o.createEl("details",{cls:"mdbase-contract-settings"});b.open=!!n.binding;let v=b.createEl("summary");v.createSpan({text:"Contract settings"}),v.createSpan({cls:"mdbase-contract-summary",text:n.binding?"Configured":"Optional"});let S=b.createDiv({cls:"mdbase-contract-settings-body"});if(S.createEl("p",{cls:"mdbase-form-description",text:"Control how compatible applications interpret this type. Values follow the contract's schema."}),n.binding)this.renderContractSchemaValue(S,i.binding_schema,n.binding,_=>{Se(_)&&(Gm(n,_),this.markDirty())},"Settings",s);else{let _=S.createEl("button",{text:"Configure settings"});_.disabled=s,_.onclick=()=>{let E=wa(i.binding_schema);Se(E)&&(Gm(n,E),this.markDirty(!0))}}}}renderContractSchemaValue(e,t,n,i,s,o){if(jn(t)==="object"){let c=Se(n)?n:{},l=e.createEl("fieldset",{cls:"mdbase-contract-schema-object"});l.createEl("legend",{text:s});let u=Se(t.properties)?t.properties:{},d=new Set(Array.isArray(t.required)?t.required.map(String):[]),f=[...new Set([...d,...Object.keys(c).filter(h=>h in u)])];for(let h of f){let m=u[h];if(!Se(m))continue;let y=l.createDiv({cls:"mdbase-contract-schema-field"}),g=typeof m.description=="string"?m.description:void 0;y.createEl("label",{text:`${h}${d.has(h)?" \xB7 required":""}`}),g&&y.createEl("small",{text:g}),this.renderContractSchemaControl(y,m,c[h],b=>{i({...c,[h]:b})},h,o)}f.length||l.createDiv({cls:"mdbase-empty-list",text:"No settings declared."});let p=Object.keys(u).filter(h=>!f.includes(h));if(p.length){let h=l.createDiv({cls:"mdbase-contract-schema-add"}),m=h.createEl("select");for(let g of p)m.createEl("option",{value:g,text:g});let y=h.createEl("button",{text:"Add optional setting"});y.disabled=o,y.onclick=()=>{let g=m.value,b=u[g];Se(b)&&i({...c,[g]:wa(b)})}}return}this.renderContractSchemaControl(e,t,n,i,s,o)}renderContractSchemaControl(e,t,n,i,s,o){let a=jn(t);if(Array.isArray(t.enum)){let l=e.createEl("select");l.setAttr("aria-label",s);for(let u of t.enum)l.createEl("option",{value:JSON.stringify(u),text:String(u)});l.value=JSON.stringify(n),l.disabled=o,l.onchange=()=>i(JSON.parse(l.value));return}if(a==="array"){let l=Se(t.items)?t.items:{type:"string"},u=Array.isArray(n)?n:[],d=e.createDiv({cls:"mdbase-contract-schema-array"});for(let[p,h]of u.entries()){let m=d.createDiv({cls:"mdbase-contract-schema-array-item"});m.createSpan({text:`${p+1}.`}),this.renderContractSchemaControl(m,l,h,g=>{i(u.map((b,v)=>v===p?g:b))},`${s} item ${p+1}`,o);let y=m.createEl("button",{text:"Remove"});y.disabled=o||u.length<=(typeof t.minItems=="number"?t.minItems:0),y.onclick=()=>i(u.filter((g,b)=>b!==p))}let f=e.createEl("button",{text:`Add ${s.toLowerCase()} item`});f.disabled=o||typeof t.maxItems=="number"&&u.length>=t.maxItems,f.onclick=()=>i([...u,wa(l)]);return}if(a==="object"){this.renderContractSchemaValue(e,t,n,i,s,o);return}if(a==="boolean"){let l=e.createEl("input",{type:"checkbox"});l.checked=n===!0,l.disabled=o,l.setAttr("aria-label",s),l.onchange=()=>i(l.checked);return}let c=e.createEl("input",{type:a==="number"||a==="integer"?"number":"text"});c.setAttr("aria-label",s),c.value=n==null?"":typeof n=="string"?n:typeof n=="number"||typeof n=="boolean"?String(n):"",c.disabled=o,c.oninput=()=>i(a==="number"||a==="integer"?Number(c.value):c.value)}renderFieldRow(e,t,n,i){let s=this.model?.fields??[];this.renderFieldDefinition(e,t.definition,{name:t.name,nameLabel:`Field ${n+1} name`,onNameInput:o=>{t.name=o,this.markDirty()},required:t.definition.required===!0,onRequiredChange:o=>{t.definition.required=o,this.markDirty()},onRemove:()=>{this.model?.fields.splice(n,1),this.markDirty(!0)},onMove:o=>{let a=n+o;a<0||a>=s.length||([s[n],s[a]]=[s[a],s[n]],this.pendingFieldReveal=this.fieldId(t.definition),this.markDirty(!0))},canMoveUp:n>0,canMoveDown:n{i.open?this.expandedFields.add(s):this.expandedFields.delete(s)};let a=n.name||n.staticLabel||"Unnamed field",c=i.createEl("summary",{cls:"mdbase-field-summary"});c.setAttr("data-focus-key",`field-${s}-summary`);let l=c.createSpan({cls:"mdbase-field-chevron"});l.setAttr("aria-hidden","true"),(0,Ze.setIcon)(l,"chevron-right"),c.createSpan({cls:"mdbase-field-summary-name",text:a}),c.createSpan({cls:"mdbase-field-summary-type",text:ty($a(t))});let u=c.createSpan({cls:"mdbase-field-summary-rules"}),d=()=>{u.textContent=V$(t).join(" \xB7 ")};d(),n.required&&c.createSpan({cls:"mdbase-field-summary-rule",text:"Required"}),n.onMove&&!n.readOnly&&c.addEventListener("keydown",y=>{!y.altKey||y.key!=="ArrowUp"&&y.key!=="ArrowDown"||(y.preventDefault(),y.key==="ArrowUp"&&n.canMoveUp&&n.onMove?.(-1),y.key==="ArrowDown"&&n.canMoveDown&&n.onMove?.(1))});let f=i.createDiv({cls:"mdbase-field-row"});if(n.staticLabel)f.createDiv({cls:"mdbase-field-role",text:n.staticLabel});else{let y=f.createEl("input",{type:"text",cls:"mdbase-field-name-control"});y.setAttr("data-focus-key",`field-${s}-name`),y.setAttr("aria-label",n.nameLabel),y.placeholder="Field name",y.value=n.name??"",y.disabled=n.readOnly,n.onNameInput&&(y.oninput=()=>n.onNameInput?.(y.value)),n.onNameCommit&&(y.onchange=()=>n.onNameCommit?.(y.value,y))}let p=f.createEl("select",{cls:"mdbase-field-type-control"});p.setAttr("data-focus-key",`field-${s}-type`),p.setAttr("aria-label",`${n.name||n.staticLabel||"Field"} type`);for(let y of T$)p.createEl("option",{value:y,text:ty(y)});p.value=$a(t),p.disabled=n.readOnly,p.onchange=()=>{t.type=p.value,p.value==="list"&&!Se(t.items)&&(t.items={type:"string"}),p.value==="object"&&!Se(t.fields)&&(t.fields={}),p.value==="enum"&&!Array.isArray(t.values)&&(t.values=[]),p.value!=="integer"&&p.value!=="number"&&(delete t.min,delete t.max),p.value!=="string"&&delete t.pattern,["string","list"].includes(p.value)||(delete t.min_length,delete t.max_length),delete t.default,this.markDirty(!0)};let h=f.createEl("input",{type:"text",cls:"mdbase-field-description-control"});if(h.setAttr("data-focus-key",`field-${s}-description`),h.setAttr("aria-label",`${n.name||n.staticLabel||"Field"} description`),h.placeholder="Description",h.value=typeof t.description=="string"?t.description:"",h.disabled=n.readOnly,h.oninput=()=>{h.value?t.description=h.value:delete t.description,this.markDirty()},n.onRequiredChange){let y=f.createEl("label",{cls:"mdbase-field-required"}),g=y.createEl("input",{type:"checkbox"});g.setAttr("data-focus-key",`field-${s}-required`),g.checked=n.required===!0,g.disabled=n.readOnly,g.onchange=()=>n.onRequiredChange?.(g.checked),y.createSpan({text:"Required"})}if(n.onRemove||n.onMove){let y=this.ctx.iconButton(f,"more-horizontal",`${a} actions`);y.addClass("mdbase-field-menu"),y.setAttr("data-focus-key",`field-${s}-menu`),y.disabled=n.readOnly,y.onclick=g=>{let b=new Ze.Menu;if(n.onMove&&(b.addItem(v=>v.setTitle("Move up").setIcon("arrow-up").setDisabled(!n.canMoveUp).onClick(()=>n.onMove?.(-1))),b.addItem(v=>v.setTitle("Move down").setIcon("arrow-down").setDisabled(!n.canMoveDown).onClick(()=>n.onMove?.(1)))),n.onRemove&&(n.onMove&&b.addSeparator(),b.addItem(v=>{v.setTitle("Remove field").setIcon("trash-2").onClick(()=>n.onRemove?.()),v.setWarning(!0)})),g.detail===0){let v=y.getBoundingClientRect();b.showAtPosition({x:v.left,y:v.bottom})}else b.showAtMouseEvent(g)}}let m=$a(t);this.renderConstraintControls(i,t,m,n,d),m==="enum"&&this.renderEnumFieldDetails(i,t,n,d),m==="link"&&this.renderLinkFieldDetails(i,t,n),m==="list"&&this.renderListFieldDetails(i,t,n),m==="object"&&this.renderObjectFieldDetails(i,t,n)}renderConstraintControls(e,t,n,i,s){let a=n==="integer"||n==="number"?[["min","Minimum"],["max","Maximum"]]:n==="string"?[["min_length","Min length"],["max_length","Max length"]]:n==="list"?[["min_length","Min items"],["max_length","Max items"]]:[],c=!["list","object","any","link"].includes(n);if(!a.length&&n!=="string"&&!c)return;let l=e.createDiv({cls:"mdbase-field-details mdbase-field-constraints"}),u=i.name||i.staticLabel||"Field",d=this.fieldId(t);for(let[g,b]of a){let v=l.createDiv({cls:"mdbase-constraint"}),S=v.createEl("label",{text:b}),_=v.createEl("input",{type:"number"});_.id=`mdbase-${d}-${g}`,S.htmlFor=_.id,_.setAttr("data-focus-key",`field-${d}-${g}`),_.setAttr("aria-label",`${u} ${b.toLowerCase()}`),(g.endsWith("length")||n==="integer")&&(_.step="1"),g.endsWith("length")&&(_.min="0"),_.value=typeof t[g]=="number"?String(t[g]):"",_.disabled=i.readOnly,_.oninput=()=>{let E=_.value.trim()===""?NaN:Number(_.value);Number.isFinite(E)?t[g]=E:delete t[g],s(),this.markDirty()}}if(n==="string"){let g=l.createDiv({cls:"mdbase-constraint mdbase-constraint-wide"}),b=g.createEl("label",{text:"Pattern"}),v=g.createEl("input",{type:"text"});v.id=`mdbase-${d}-pattern`,b.htmlFor=v.id,v.setAttr("data-focus-key",`field-${d}-pattern`),v.setAttr("aria-label",`${u} pattern`),v.placeholder="Regular expression",v.spellcheck=!1,v.value=typeof t.pattern=="string"?t.pattern:"",v.disabled=i.readOnly,v.oninput=()=>{v.value?t.pattern=v.value:delete t.pattern,s(),this.markDirty()}}if(!c)return;let f=l.createDiv({cls:"mdbase-constraint mdbase-constraint-wide"}),p=f.createEl("label",{text:"Default"}),h=`mdbase-${d}-default`;if(p.htmlFor=h,n==="enum"||n==="boolean"){let g=f.createEl("select");g.id=h,g.setAttr("data-focus-key",`field-${d}-default`),g.createEl("option",{value:"",text:"None"});let b=n==="boolean"?[!0,!1]:Array.isArray(t.values)?t.values:[];for(let[S,_]of b.entries())g.createEl("option",{value:String(S),text:sn(_)});let v=b.findIndex(S=>JSON.stringify(S)===JSON.stringify(t.default));t.default!==void 0&&v===-1?(g.createEl("option",{value:"missing",text:`${sn(t.default)} \xB7 not allowed`}),g.value="missing"):g.value=v===-1?"":String(v),g.disabled=i.readOnly,g.onchange=()=>{g.value===""?delete t.default:g.value!=="missing"&&(t.default=b[Number(g.value)]),s(),this.markDirty()};return}let m=f.createEl("input",{type:"text"});m.id=h,m.setAttr("data-focus-key",`field-${d}-default`),m.setAttr("aria-label",`${u} default`),m.placeholder=n==="date"?"YYYY-MM-DD":n==="time"?"HH:MM":"None",m.value=t.default===void 0?"":sn(t.default),m.disabled=i.readOnly;let y=f.createDiv({cls:"mdbase-constraint-error"});m.oninput=()=>{let g=z$(m.value,n);y.textContent=g.error??"",m.toggleClass("is-invalid",!!g.error),!g.error&&(g.value===void 0?delete t.default:t.default=g.value,s(),this.markDirty())}}fieldId(e){let t=this.fieldIds.get(e);if(t)return t;let n=`field-${this.nextFieldId}`;return this.nextFieldId+=1,this.fieldIds.set(e,n),n}fieldMatches(e,t,n){return`${e} ${$a(t)} ${typeof t.description=="string"?t.description:""}`.toLowerCase().includes(n)||Se(t.items)&&this.fieldMatches("item",t.items,n)?!0:Se(t.fields)?Object.entries(t.fields).some(([s,o])=>Se(o)&&this.fieldMatches(s,o,n)):!1}renderEnumFieldDetails(e,t,n,i){let s=e.createDiv({cls:"mdbase-field-details mdbase-enum-values"}),o=n.name||n.staticLabel||"Enum",a=this.fieldId(t);s.createDiv({cls:"mdbase-field-children-label",text:"Allowed values"});let c=Array.isArray(t.values)?t.values:[];!Array.isArray(t.values)&&!n.readOnly&&(t.values=c);let l=s.createDiv({cls:"mdbase-enum-list"});l.setAttr("role","list");let u=new Set(c.map(f=>typeof f)).size>1;for(let[f,p]of c.entries()){let h=l.createDiv({cls:"mdbase-enum-row"});h.setAttr("role","listitem");let m=h.createEl("input",{type:"text"});m.setAttr("data-focus-key",`field-${a}-value-${f}`),m.setAttr("aria-label",`${o} allowed value ${f+1}`),m.value=sn(p),m.disabled=n.readOnly,m.oninput=()=>{c[f]=H$(m.value,p,c.filter((g,b)=>b!==f)),i(),this.markDirty()},m.onkeydown=g=>{g.key==="Enter"&&(g.preventDefault(),c.splice(f+1,0,""),this.ctx.pendingFocusKey=`field-${a}-value-${f+1}`,this.markDirty(!0))},u&&h.createSpan({cls:"mdbase-enum-kind",text:typeof p});for(let[g,b,v]of[["arrow-up","Move value up",-1],["arrow-down","Move value down",1]]){let S=this.ctx.iconButton(h,g,`${b}: ${sn(p)}`);S.disabled=n.readOnly||f+v<0||f+v>=c.length,S.onclick=()=>{[c[f],c[f+v]]=[c[f+v],c[f]],this.markDirty(!0)}}let y=this.ctx.iconButton(h,"x",`Remove value ${sn(p)}`);y.disabled=n.readOnly,y.onclick=()=>{c.splice(f,1),this.markDirty(!0)}}let d=s.createEl("button",{cls:"mdbase-link-button",text:"Add value"});d.disabled=n.readOnly,d.onclick=()=>{c.push(""),this.ctx.pendingFocusKey=`field-${a}-value-${c.length-1}`,this.markDirty(!0)}}renderLinkFieldDetails(e,t,n){let i=e.createDiv({cls:"mdbase-field-details mdbase-field-options"}),s=this.fieldId(t),o=i.createEl("label",{text:"Target type"}),a=i.createEl("select");a.setAttr("data-focus-key",`field-${s}-target`),a.setAttr("aria-label",`${n.name||n.staticLabel||"Link"} target type`),a.createEl("option",{value:"",text:"Any type"});let c=typeof t.target=="string"?t.target:"";for(let d of this.typeEntries())a.createEl("option",{value:d.name,text:d.name});c&&!this.typeEntries().some(d=>d.name===c)&&a.createEl("option",{value:c,text:`${c} \xB7 missing`}),a.value=c,a.disabled=n.readOnly,a.onchange=()=>{a.value?t.target=a.value:delete t.target,this.markDirty()},o.htmlFor=a.id=`mdbase-${s}-target`;let l=i.createEl("label",{cls:"mdbase-field-required"}),u=l.createEl("input",{type:"checkbox"});u.setAttr("data-focus-key",`field-${s}-exists`),u.checked=t.validate_exists===!0,u.disabled=n.readOnly,u.onchange=()=>{t.validate_exists=u.checked,this.markDirty()},l.createSpan({text:"Validate target exists"})}renderListFieldDetails(e,t,n){let i=e.createDiv({cls:"mdbase-field-children"});i.createDiv({cls:"mdbase-field-children-label",text:"List items"});let s=Se(t.items)?t.items:{type:"any"};!Se(t.items)&&!n.readOnly&&(t.items=s),this.renderFieldDefinition(i,s,{staticLabel:"Item",nameLabel:"List item",readOnly:n.readOnly,depth:n.depth+1})}renderObjectFieldDetails(e,t,n){let i=e.createDiv({cls:"mdbase-field-children"});i.createDiv({cls:"mdbase-field-children-label",text:"Object fields"});let s=Se(t.fields)?t.fields:{};!Se(t.fields)&&!n.readOnly&&(t.fields=s);let o=i.createDiv({cls:"mdbase-nested-fields"}),a=i.createEl("button",{cls:"mdbase-link-button",text:"Add nested field"});a.disabled=n.readOnly,a.onclick=()=>{let l=I$(s);_d(s,l,{type:"string"}),this.expandedFields.add(this.fieldId(s[l])),this.markDirty(!0)};let c=Object.entries(s).filter(l=>Se(l[1]));if(!c.length){o.createDiv({cls:"mdbase-empty-list",text:"No nested fields."});return}for(let[l,[u,d]]of c.entries()){let f=u;this.renderFieldDefinition(o,d,{name:f,nameLabel:`${f} nested field name`,onNameCommit:(p,h)=>{let m=p.trim();if(!m){new Ze.Notice("Nested field name is required."),h.value=f;return}if(m!==f&&Object.prototype.hasOwnProperty.call(s,m)){new Ze.Notice(`Nested field already exists: ${m}`),h.value=f;return}m!==f&&(delete s[f],_d(s,m,d),f=m,this.markDirty())},required:d.required===!0,onRequiredChange:p=>{d.required=p,this.markDirty()},onRemove:()=>{delete s[f],this.markDirty(!0)},onMove:p=>{let h=Object.keys(s),m=h.indexOf(f),y=m+p;if(m===-1||y<0||y>=h.length)return;[h[m],h[y]]=[h[y],h[m]];let g=h.map(b=>[b,s[b]]);for(let b of h)delete s[b];for(let[b,v]of g)Se(v)&&_d(s,b,v);this.pendingFieldReveal=this.fieldId(d),this.markDirty(!0)},canMoveUp:l>0,canMoveDown:lthis.onYamlInput(s.value)}}ensureYamlEditor(e){try{return this.yamlEditor?(this.yamlEditor.setValue(this.yamlDraft),this.yamlEditor.setReadOnly(e)):this.yamlEditor=new Ad({doc:this.yamlDraft,readOnly:e,labelledBy:"mdbase-mode-yaml",onChange:t=>this.onYamlInput(t)}),this.yamlEditor.setProblems(this.yamlProblems()),this.yamlEditor}catch(t){return console.error("mdbase: YAML editor unavailable",t),this.yamlEditor=null,null}}onYamlInput(e){this.yamlDraft=e,this.markDirty(!1),this.yamlProblemTimer!==null&&window.clearTimeout(this.yamlProblemTimer),this.yamlProblemTimer=window.setTimeout(()=>{this.yamlProblemTimer=null;let t=this.yamlProblems();this.yamlEditor?.setProblems(t);let n=this.ctx.containerEl.querySelector(".mdbase-yaml-problems");n&&(n.empty(),this.fillYamlProblems(n,t))},250)}fillYamlProblems(e,t=this.yamlProblems()){if(!(!this.dirty||!t.length))for(let n of t.slice(0,20)){let i=e.createEl("button",{cls:"mdbase-yaml-problem"});if(i.setAttr("data-severity",n.severity),i.createSpan({cls:"mdbase-yaml-problem-line-number",text:n.line?`Line ${n.line}`:"Type"}),i.createSpan({text:n.message}),i.disabled=n.line===null,n.line!==null){let s=n.line;i.onclick=()=>this.yamlEditor?.revealLine(s)}}}async leaveCurrentType(){this.dirty&&await this.flushTypeDraft(),this.yamlEditor?.destroy(),this.yamlEditor=null,this.impact=null,this.showAllMatches=!1}async selectType(e,t=!0){t&&e!==this.selectedPath&&await this.leaveCurrentType();let n=++this.typeSelectionVersion,i=await this.ctx.host.loadTypeModel(e);if(n!==this.typeSelectionVersion)return;let s=this.ctx.host.loadTypeDraft(e),o=s?.version===1&&s.sourceRevision===(i.sourceRevision??null),a=o?qn(s.model):i;this.selectedPath=e,this.model=a,this.originalModel=qn(i),this.yamlDraft=o&&s.yamlDraft!==void 0?s.yamlDraft:`${mt(Aa(i),i.body)} +`,this.dirty=!bd(this.originalModel,a),this.editorMode=o&&s.editorMode==="yaml"?"yaml":"design",this.editorMode==="yaml"&&(this.dirty=!0),o&&this.dirty?this.sessionDrafts.has(e)||(this.ctx.message=`Recovered unsaved changes for ${e}.`):s&&!o&&(this.ctx.message=`An older draft for ${e} was kept, but the source changed. The current file is shown.`),this.scheduleImpact(0),this.ctx.render()}async createType(){await this.leaveCurrentType(),this.typeSelectionVersion+=1;let e=this.ctx.host.loadTypeDraft(null),t=e?.version===1?qn(e.model):Wm();this.selectedPath=null,this.model=t,this.originalModel=null,this.yamlDraft=e?.yamlDraft??"",this.dirty=!0,e&&!this.sessionDrafts.has("__new__")&&(this.ctx.message="Recovered an unsaved new type."),this.editorMode=e?.editorMode??"design",this.scheduleImpact(0),this.ctx.render()}switchEditorMode(e){if(!(!this.model||e===this.editorMode)){if(e==="yaml")try{this.yamlDraft=`${mt(Aa(this.model),this.model.body)} +`}catch(t){new Ze.Notice(t instanceof Error?t.message:String(t));return}else if(!this.readYamlDraftIntoModel())return;this.editorMode=e,e==="design"&&(this.yamlEditor?.destroy(),this.yamlEditor=null),this.scheduleImpact(0),this.ctx.render()}}modelFromYamlDraft(){let e=Ce(this.yamlDraft);if(!e.hasFrontmatter)return{error:"Type YAML must start with a --- frontmatter block.",line:1};if(e.error)return{error:`Invalid YAML: ${e.error.split(` +`)[0].replace(/:$/,"").replace(/ at line \d+, column \d+$/,"")}`,line:W$(e.error)};if(e.frontmatter.kind!=="mdbase.type")return{error:"Canonical v0.3 type YAML requires kind: mdbase.type.",line:ay(this.yamlDraft,"kind")??2};try{let t=gd(e.frontmatter,e.body,this.model?.name||"type");return this.model?.sourceRevision&&(t.sourceRevision=this.model.sourceRevision),{model:t}}catch(t){return{error:t instanceof Error?t.message:String(t),line:null}}}yamlProblems(){let e=this.modelFromYamlDraft();return"error"in e?[{line:e.line??null,message:e.error,severity:"error"}]:_a(e.model,{knownTypes:this.typeEntries().map(t=>t.name),contracts:this.ctx.schema?.contracts.values()}).map(t=>{let n=t.path.startsWith("fields.")?t.path.slice(7).split(/[.[]/)[0]:t.path==="identity.displayNameKey"?"name_field":t.path.split(".").pop()??"";return{line:ay(this.yamlDraft,n),message:t.message,severity:t.severity==="error"?"error":"warning"}})}readYamlDraftIntoModel(){let e=this.modelFromYamlDraft();return"error"in e?(new Ze.Notice(e.error),e.line&&this.yamlEditor?.revealLine(e.line),!1):(this.model=e.model,!0)}async saveCurrentType(){if(!this.model||this.model.specProfile!=="v0.3"||this.model.readOnlyReason||this.editorMode==="yaml"&&!this.readYamlDraftIntoModel())return;let t=_a(this.model,{knownTypes:this.typeEntries().map(a=>a.name),contracts:this.ctx.schema?.contracts.values()}).filter(a=>a.severity==="error");if(t.length){this.ctx.message=`${t.length} ${t.length===1?"error must":"errors must"} be fixed before saving.`,this.ctx.render(),new Ze.Notice(t[0].message);return}let n=Sa(this.originalModel,this.model).filter(a=>a.risk==="high"),i=await this.computeImpact();i!==void 0&&(this.impact=i);let s=this.impact&&!("error"in this.impact)?this.impact.impact.failing.filter(a=>a.isNew).map(a=>a.path):[];if(n.length||s.length){let a=n.length?n:Sa(this.originalModel,this.model).filter(l=>l.risk!=="safe");if(!await new Ec(this.ctx.app).confirm(a,s))return}let o=this.model;await this.flushTypeDraft(),await this.ctx.perform(async()=>{let a=this.selectedPath,c=await this.ctx.host.saveTypeModel(o,a,this.originalModel?.sourceRevision);await this.ctx.host.clearTypeDraft(a),a!==c.path&&await this.ctx.host.clearTypeDraft(c.path),this.selectedPath=c.path,this.originalModel=qn(o),this.dirty=!1,this.ctx.message=`Saved ${c.path}.`,await this.ctx.refresh(!0)})}markDirty(e=!1){let t=this.dirty;if(this.dirty=this.editorMode==="yaml"?!0:!bd(this.originalModel,this.model),this.scheduleTypeDraftSave(),this.scheduleImpact(),this.dirty&&!t&&(this.ctx.message=""),e||t!==this.dirty){this.ctx.render();return}let n=this.ctx.containerEl.querySelector(".mdbase-type-editor-pane"),i=n?.querySelector(".mdbase-draft-bar");if(n&&i&&this.model){i.remove(),this.renderDraftBar(n,this.model);let s=n.querySelector(".mdbase-editor-title-line h2");s&&(s.textContent=this.model.name||"Untitled type")}}scheduleTypeDraftSave(){this.draftSaveTimer!==null&&window.clearTimeout(this.draftSaveTimer),this.draftSaveTimer=window.setTimeout(()=>{this.draftSaveTimer=null,this.flushTypeDraft()},2e3)}async flushTypeDraft(){if(this.draftSaveTimer!==null&&(window.clearTimeout(this.draftSaveTimer),this.draftSaveTimer=null),!this.model)return;if(!this.dirty){let t=this.ctx.host.loadTypeDraft(this.selectedPath);t&&t.sourceRevision===(this.originalModel?.sourceRevision??null)&&await this.ctx.host.clearTypeDraft(this.selectedPath);return}this.sessionDrafts.add(this.selectedPath??"__new__");let e={version:1,path:this.selectedPath,sourceRevision:this.originalModel?.sourceRevision??null,model:qn(this.model),editorMode:this.editorMode,yamlDraft:this.editorMode==="yaml"?this.yamlDraft:void 0,updatedAt:new Date().toISOString()};await this.ctx.host.saveTypeDraft(e)}async discardCurrentType(){let e=this.selectedPath,t=this.ctx.host.loadTypeDraft(e);if((!t||t.sourceRevision===(this.originalModel?.sourceRevision??null))&&await this.ctx.host.clearTypeDraft(e),e){let n=await this.ctx.host.loadTypeModel(e);this.model=n,this.originalModel=qn(n),this.yamlDraft=`${mt(Aa(n),n.body)} +`,this.dirty=!1}else this.model=null,this.originalModel=null,this.yamlDraft="",this.dirty=!1;this.ctx.message="Unsaved changes discarded.",this.ctx.render()}};function Aa(r){return r.specProfile==="v0.3"&&!r.readOnlyReason?Fn(r):qn(r.originalFrontmatter??{name:r.name,fields:Object.fromEntries(r.fields.map(e=>[e.name,e.definition]))})}var Or="mdbase-workspace-view",Pd=class r extends Ns.ItemView{constructor(t,n){super(t);this.host=n;this.destination="types";this.message="";this.pendingFocusKey=null;this.busy=!1;this.schema=null;this.records=null;this.disclosures=new Map;this.types=new kd(this);this.sync=new Ed(this);this.issues=new vd(this);this.navigationId=`mdbase-workspace-${++r.nextNavigationId}`;this.refreshVersion=0;this.unsubscribeSync=null;this.syncRenderTimer=null}static{this.nextNavigationId=0}getState(){return this.captureRenderSnapshot(this.containerEl),{destination:this.destination,...this.types.getState(),...this.issues.getState(),...this.sync.getState(),disclosures:Object.fromEntries(this.disclosures)}}async setState(t,n){if(["types","sync","issues"].includes(String(t.destination))&&(this.destination=t.destination),t.disclosures&&typeof t.disclosures=="object")for(let[i,s]of Object.entries(t.disclosures))typeof s=="boolean"&&this.disclosures.set(i,s);await this.types.setState(t),this.issues.setState(t),this.sync.setState(t),await this.refresh(),this.types.restoreEditorMode(t.editorMode),await super.setState(t,n)}refreshValidationControls(){this.destination==="issues"&&this.render()}updateValidationProgress(){this.issues.updateValidationProgress()}getViewType(){return Or}getDisplayText(){return"mdbase"}getIcon(){return xa}async onOpen(){this.containerEl.addClass("mdbase-workspace"),this.registerDomEvent(this.containerEl,"keydown",n=>{(n.metaKey||n.ctrlKey)&&n.key.toLowerCase()==="s"&&this.types.dirty&&(n.preventDefault(),this.types.saveCurrentType())});let t=this.host.sync.state;this.unsubscribeSync=this.host.sync.subscribe(()=>{let n=this.host.sync.state,i=Object.keys(n).every(s=>s==="progress"||s==="fileProgress"||t[s]===n[s]);if(t=n,i&&(n.progress||n.fileProgress)){this.destination==="sync"&&this.syncRenderTimer===null&&(this.syncRenderTimer=window.setTimeout(()=>{this.syncRenderTimer=null,this.destination==="sync"&&this.render()},100));return}this.cancelSyncRender(),this.destination==="sync"?this.render():this.renderTopbarOnly()}),await this.refresh(!0)}async onClose(){this.refreshVersion++,this.unsubscribeSync?.(),this.unsubscribeSync=null,this.cancelSyncRender(),await this.types.dispose(),this.sync.dispose()}cancelSyncRender(){this.syncRenderTimer!==null&&window.clearTimeout(this.syncRenderTimer),this.syncRenderTimer=null}async refresh(t=!1){let n=++this.refreshVersion,i=()=>n===this.refreshVersion;try{let s=await this.host.loadWorkspaceSchema(t);if(!i())return;if(this.schema=s,this.destination==="types"){if(await this.types.onSchemaLoaded(t,i),!i())return;let o=s?await this.host.loadCollectionRecords():null;if(!i())return;let a=o!==this.records;this.records=o,this.types.onRecordsLoaded(a||t)}else this.destination==="sync"&&await this.sync.refresh();if(!i())return;this.render()}catch(s){if(!i())return;this.message=s instanceof Error?s.message:String(s),this.render()}}showDestination(t){this.destination=t,this.render(),t==="types"?this.refresh():t==="sync"&&this.sync.refresh().then(()=>this.render())}showIssuesForPath(t){this.issues.filterToPath(t),this.showDestination("issues")}openTypeField(t,n){return this.types.openTypeField(t,n)}recordTypes(){return this.types.currentStats().recordTypes}createNewType(){this.types.createNewType()}editType(t){return this.types.editType(t)}focusSyncSection(t){this.sync.focusSection(t)}reconnectCollection(){return this.sync.reconnectCollection()}render(){let t=this.containerEl,n=this.captureRenderSnapshot(t);t.empty(),t.addClass("mdbase-workspace");let i=t.createDiv({cls:"mdbase-shell"});if(this.renderTopbar(i),this.message){let o=i.createDiv({cls:"mdbase-inline-message mdbase-notice"});o.createSpan({text:this.message}).setAttr("role","status");let a=this.iconButton(o,"x","Dismiss message");a.onclick=()=>{this.message="",this.render()}}let s=i.createDiv({cls:"mdbase-workspace-content"});s.setAttr("data-scroll-key","workspace"),s.id=`${this.navigationId}-${this.destination}-panel`,s.setAttr("role","tabpanel"),s.setAttr("aria-labelledby",`${this.navigationId}-${this.destination}-tab`),this.destination==="types"?this.types.render(s):this.destination==="sync"?this.sync.render(s):this.issues.render(s),this.restoreRenderSnapshot(t,n),this.app.workspace?.requestSaveLayout(),this.pendingFocusKey&&(this.focusTarget(t,this.pendingFocusKey)?.focus(),this.pendingFocusKey=null),this.destination==="types"&&this.types.afterRender(t)}syncAttention(){let{status:t,preview:n}=this.host.sync.state,i=t?.conflicts.length??0;if(i)return{count:i,label:`${i} sync ${i===1?"conflict":"conflicts"}`};let s=this.host.sync.safety(),o=s&&!s.safe?n?.plan.actions.length??0:0;return o?{count:o,label:`${o} ${o===1?"change needs":"changes need"} review`}:null}renderTopbarOnly(){let t=this.containerEl.querySelector(".mdbase-topbar");if(!t)return;let n=this.captureRenderSnapshot(t),i=this.containerEl.ownerDocument.createElement("div");this.renderTopbar(i);let s=i.firstElementChild;s&&(t.replaceWith(s),this.restoreRenderSnapshot(s,n))}captureRenderSnapshot(t){for(let a of Array.from(t.querySelectorAll("details[data-disclosure]"))){let c=a.dataset.disclosure;c&&this.disclosures.set(c,a.open)}let n=t.ownerDocument,i=t.contains(n.activeElement)?n.activeElement:null,s=i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement?i:null,o=new Map;for(let a of Array.from(t.querySelectorAll("[data-scroll-key]"))){let c=a.getAttr("data-scroll-key");c&&o.set(c,{top:a.scrollTop,left:a.scrollLeft})}return{focusKey:i?.getAttr("data-focus-key")??null,selectionStart:s?.selectionStart??null,selectionEnd:s?.selectionEnd??null,scroll:o}}restoreRenderSnapshot(t,n){for(let[s,o]of n.scroll){let a=t.querySelector(`[data-scroll-key="${s}"]`);a&&(a.scrollTop=o.top,a.scrollLeft=o.left)}if(!n.focusKey)return;let i=this.focusTarget(t,n.focusKey);i?.focus({preventScroll:!0}),(i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement)&&n.selectionStart!==null&&n.selectionEnd!==null&&i.setSelectionRange(n.selectionStart,n.selectionEnd)}focusTarget(t,n){return Array.from(t.querySelectorAll("[data-focus-key]")).find(i=>i.getAttr("data-focus-key")===n)}iconButton(t,n,i){let s=t.createEl("button",{cls:"clickable-icon mdbase-icon-button"});return s.setAttr("aria-label",i),s.setAttr("title",i),s.setAttr("data-focus-key",`action-${i.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`),(0,Ns.setIcon)(s,n),s}disclosure(t,n,i,s=!1){let o=t.createEl("details",{cls:"mdbase-disclosure"});return o.dataset.disclosure=n,o.open=this.disclosures.get(n)??s,o.addEventListener("toggle",()=>{this.containerEl.contains(o)&&(this.disclosures.set(n,o.open),this.app.workspace?.requestSaveLayout())}),o.createEl("summary",{text:i}).setAttr("data-focus-key",`disclosure-${n}`),o.createDiv({cls:"mdbase-disclosure-body"})}renderTopbar(t){let i=t.createDiv({cls:"mdbase-topbar"}).createDiv({cls:"mdbase-nav"});i.setAttr("role","tablist"),i.setAttr("aria-label","mdbase destinations");let s=[["types","Types"],["sync","Sync"],["issues","Issues"]];for(let[o,[a,c]]of s.entries()){let l=i.createEl("button",{text:c,cls:"clickable-icon"});if(l.addClass("mdbase-nav-button"),l.setAttr("role","tab"),l.id=`${this.navigationId}-${a}-tab`,this.destination===a&&l.setAttr("aria-controls",`${this.navigationId}-${a}-panel`),l.tabIndex=this.destination===a?0:-1,l.setAttr("data-focus-key",`destination-${a}`),l.setAttr("aria-selected",String(this.destination===a)),this.destination===a&&l.addClass("is-active"),a==="issues"&&this.host.getIssues().length){let d=this.host.getIssues().length;l.createSpan({cls:"mdbase-count",text:ry(d)}).setAttr("title",`${d} issues`)}let u=a==="sync"?this.syncAttention():null;u&&l.createSpan({cls:"mdbase-count",text:ry(u.count)}).setAttr("title",u.label),l.onclick=()=>this.showDestination(a),l.onkeydown=d=>{let f=d.key==="ArrowRight"?(o+1)%s.length:d.key==="ArrowLeft"?(o+s.length-1)%s.length:d.key==="Home"?0:d.key==="End"?s.length-1:null;f!==null&&(d.preventDefault(),this.pendingFocusKey=`destination-${s[f][0]}`,this.showDestination(s[f][0]))}}}async perform(t){if(!this.busy){this.busy=!0,this.message="",this.render();try{await t()}catch(n){let i=n instanceof Error?n.message:String(n);this.message=i,new Ns.Notice(i)}finally{this.busy=!1,this.render()}}}};var ka=class{constructor(e,t){this.delayMs=e;this.task=t;this.entries=new Map;if(!Number.isFinite(e)||e<0)throw new Error("Debounce delay must be a non-negative finite number.")}has(e){return this.entries.has(e)}schedule(e,t){let n=this.entries.get(e);n||(n={value:t,revision:0,timer:null,ready:!1,running:!1},this.entries.set(e,n)),n.value=t,n.revision+=1,n.ready=!1,n.timer!==null&&clearTimeout(n.timer),n.timer=setTimeout(()=>{this.entries.get(e)===n&&(n.timer=null,n.ready=!0,this.drain(e,n))},this.delayMs)}cancel(e){let t=this.entries.get(e);t&&(t.timer!==null&&clearTimeout(t.timer),this.entries.delete(e))}clear(){for(let e of this.entries.values())e.timer!==null&&clearTimeout(e.timer);this.entries.clear()}async drain(e,t){if(this.entries.get(e)!==t||t.running||!t.ready)return;t.ready=!1,t.running=!0;let n=t.revision,i=t.value,s=()=>this.entries.get(e)===t&&t.revision===n;try{await this.task(i,s)}finally{t.running=!1,this.entries.get(e)===t&&(t.ready?this.drain(e,t):t.timer===null&&t.revision===n&&this.entries.delete(e))}}};var G$=require("obsidian");var Md=class extends G$.Modal{constructor(t,n,i){super(t);this.path=n;this.runs=i}onOpen(){this.titleEl.setText(`Sync history \xB7 ${this.path.split("/").pop()??this.path}`),this.contentEl.addClass("mdbase-note-history");let t=Gx(this.runs,this.path).map(({run:i,file:s})=>({at:s.at,label:i.summary??Yx(s),detail:i.summary===void 0&&s.fromPath?`From ${s.fromPath}`:s.message}));if(!t.length){this.contentEl.createEl("p",{cls:"mdbase-muted",text:"No syncs of this note are recorded on this device."});return}let n=this.contentEl.createDiv({cls:"mdbase-transfer-ledger"});for(let i of t){let s=n.createDiv({cls:"mdbase-note-history-row"});s.createSpan({cls:"mdbase-muted",text:Ps(i.at)});let o=s.createDiv();o.createDiv({text:i.label}),i.detail&&o.createDiv({cls:"mdbase-muted",text:i.detail})}}onClose(){this.contentEl.empty()}};var Oe=require("obsidian");var sj=[["image","Images"],["audio","Audio"],["video","Video"],["pdf","PDFs"],["other","Other files"]],Cd=class extends Oe.PluginSettingTab{constructor(t,n){super(t,n);this.plugin=n}display(){let{containerEl:t,plugin:n}=this;t.empty(),new Oe.Setting(t).setName("Validate notes automatically").setDesc("Check notes against their types when they are opened or saved.").addToggle(i=>i.setValue(n.settings.validateOnSave||n.settings.validateOnOpen).onChange(async s=>{n.settings.validateOnSave=s,n.settings.validateOnOpen=s,await n.saveSettings(),this.display()})),n.settings.validateOnSave&&new Oe.Setting(t).setName("Show validation notices").setDesc("Notify when saving a note with issues.").addToggle(i=>i.setValue(n.settings.showNoticeOnSave).onChange(async s=>{n.settings.showNoticeOnSave=s,await n.saveSettings()})),new Oe.Setting(t).setName("Allow plugin integrations").setDesc("Let other installed plugins exchange mdbase events and actions in this vault.").addToggle(i=>i.setValue(n.settings.interopEnabled).onChange(async s=>{n.settings.interopEnabled=s,await n.saveSettings()})),this.displaySync(t)}displaySync(t){let{plugin:n}=this,i=n.getMirrorProfile();if(new Oe.Setting(t).setName("Sync").setHeading(),!i){new Oe.Setting(t).setName("Not connected").setDesc("Connect this vault to mdbase Connect from the sync tab of the mdbase workspace.").addButton(l=>l.setButtonText("Open sync").onClick(()=>{n.openWorkspace("sync")}));return}new Oe.Setting(t).setName(i.name).setDesc(`${i.mode==="read_write"?"Read and write":"Read only"} \xB7 ${new URL(i.controlUrl).host}`).addButton(l=>l.setButtonText("Reconnect").onClick(async()=>{l.setDisabled(!0);try{await n.openWorkspace("sync").then(u=>u.reconnectCollection())}catch(u){new Oe.Notice(u instanceof Error?u.message:String(u))}finally{l.setDisabled(!1)}})),new Oe.Setting(t).setName("Sync automatically").setDesc("Keep this vault in sync in the background. Deleted files go to the trash, and conflicting edits are merged or kept as two files. Deleting many files at once on this device waits for your review.").addToggle(l=>l.setValue(n.settings.autoSync).onChange(async u=>{n.settings.autoSync=u,await n.saveSettings(),n.requestSync()}));let s=n.connectSync.getSelectiveSync(),o=async l=>{try{return await n.sync.configureSelectiveSync(l),!0}catch(u){return new Oe.Notice(u instanceof Error?u.message:String(u)),this.display(),!1}};for(let[l,u]of sj)new Oe.Setting(t).setName(`Sync ${u.toLowerCase()}`).setDesc(l==="other"?"All remaining visible file formats. Markdown always syncs.":"").addToggle(d=>d.setValue(s.file_classes.includes(l)).onChange(async f=>{let p=n.connectSync.getSelectiveSync();await o({...p,file_classes:f?[...new Set([...p.file_classes,l])]:p.file_classes.filter(h=>h!==l)})}));let a=[...s.excluded_folders],c=new Oe.Setting(t).setName("Excluded folders").setDesc(xd);$d(this.app,c.controlEl,a,l=>{a=l}),c.addButton(l=>l.setButtonText("Apply").onClick(async()=>{l.setDisabled(!0);try{await o({...n.connectSync.getSelectiveSync(),excluded_folders:a})&&new Oe.Notice("Excluded folders updated. The next sync applies them.")}finally{l.setDisabled(!1)}})),new Oe.Setting(t).setName("Disconnect").setDesc("Stop syncing this vault. The hosted collection is not deleted.").addButton(l=>l.setButtonText("Disconnect\u2026").setWarning().setDisabled(n.sync.isSyncing()).onClick(async()=>{let u=await new kc(this.app).choose(i.name);if(u){try{await n.sync.disconnect(i,u==="remove"),new Oe.Notice(n.sync.state.message)}catch(d){new Oe.Notice(d instanceof Error?d.message:String(d))}this.display()}}))}};async function J$(r,e,t,n){let i=await r.resolveConflict(e,t,n),s=await r.preview();return{status:i,preview:s}}var oj=4,Y$={status:null,preview:null,progress:null,fileProgress:null,problem:null,message:"",localChangeObserved:!1,busy:!1,paused:!1,retryAt:null},Rd=class{constructor(e,t,n,i=()=>{}){this.controller=e;this.getProfile=t;this.history=n;this.notify=i;this.current={...Y$};this.listeners=new Set;this.safetyPreview=null;this.previewSafety=null;this.pinnedFailure=null}get state(){return this.current}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}update(e){this.current={...this.current,...e};for(let t of this.listeners)t()}reset(){this.update({...Y$})}isSyncing(){return this.controller.isSyncing()}clearMessage(){this.current.message&&this.update({message:""})}observeLocalChange(){this.current.localChangeObserved||this.update({localChangeObserved:!0})}historyRuns(){let e=this.getProfile()?.collectionId;return e?this.history?.list(e)??[]:[]}async recordEvent(e,t=this.getProfile()?.collectionId){if(!(!t||!this.history)){try{await this.history.append(ld(t,e))}catch(n){console.error("mdbase: could not save sync history",n)}this.update({})}}async dismissEvent(e){await this.history?.acknowledge(e),this.update({})}async clearHistory(){await this.history?.clear(),this.update({})}async refreshStatus(){let e=this.getProfile();if(!e)return this.reset(),null;if(this.controller.isSyncing())return this.current.status;try{let t=await this.controller.status();return Td(e,this.getProfile())?(this.update({status:t,problem:null}),t):null}catch(t){return Td(e,this.getProfile())&&this.update({problem:Rt(t)}),null}}async review(){return this.getProfile()?await this.exclusive(async()=>(await this.loadPreview(),this.current.preview))??null:null}async apply(){if(!this.current.preview){await this.review();return}await this.exclusive(()=>this.applyReviewed())}async syncNow(e={}){return this.getProfile()?this.current.busy||this.controller.isSyncing()?"busy":e.automatic&&this.current.paused?"paused":(!e.automatic&&this.current.paused&&this.update({paused:!1}),await this.exclusive(async()=>{let n=!1;for(let i=0;it.outcome!=="unresolved")}safety(){let e=this.current.preview;return e!==this.safetyPreview&&(this.safetyPreview=e,this.previewSafety=e?Lx(e):null),this.previewSafety}cancel(){this.update({paused:!0}),this.controller.isSyncing()&&(this.controller.cancelSync(),this.update({message:"Stopping\u2026"}))}async reconnect(){return await this.exclusive(async()=>{try{let t=await this.controller.reconnect();return this.update({status:t,problem:null,message:"Connection restored."}),await this.recordEvent({summary:"Collection reconnected",message:"Connect credentials were renewed and the mirror checkpoint was preserved.",tone:"success"}),"connected"}catch(t){let n=Rt(t);return this.update({problem:n,message:n.action==="reauthorize"?"":n.message}),n.action==="reauthorize"?"reauthorize":"failed"}})??"failed"}async reauthorize(e){let t=await this.controller.reauthorize(e);this.update({status:t,problem:null,message:"Approval restored. The mirror checkpoint was preserved."}),await this.recordEvent({summary:"Connect approval restored",message:"The existing mirror checkpoint and local files were preserved.",tone:"success"})}async disconnect(e,t){let n=await this.controller.disconnect(t),i=t?`${n.removed.length} unchanged synced ${n.removed.length===1?"file was":"files were"} removed. ${n.preserved.length} locally changed ${n.preserved.length===1?"file was":"files were"} preserved.`:"All local files were retained as an unsynced copy.";return this.reset(),this.update({message:`Disconnected from ${e.name}. ${i}`}),n}async configureSelectiveSync(e){await this.controller.configureSelectiveSync(e),this.update({preview:null,message:"Sync settings updated."})}async resolveConflict(e,t,n){let i=null;try{n&&(i=await this.controller.preserveConflictCopy(e.path??"")),this.update({preview:null});let s=await J$(this.controller,e.object_id,e.decision_id,t),o=i?`Local copy saved to ${i}. Sync to apply the hosted version.`:"Conflict resolved. Sync to continue.";return this.update({status:s.status,preview:s.preview,problem:null,message:o}),await this.recordEvent({summary:i?"Conflict kept as two files":`Conflict resolved with ${t==="local"?"local":"hosted"} version`,message:o,...e.path?{path:e.path}:{},tone:"info"}),!0}catch(s){let o=Rt(s);return i&&(o.message=`The local copy at ${i} is safe, but the original changed again. Review the newest versions before deciding.`),this.update({problem:o,message:o.message}),o.code==="conflict_decision_stale"&&(this.update({preview:null}),await this.refreshStatus()),await this.recordEvent({summary:o.title,message:o.message,...e.path?{path:e.path}:{},tone:"attention",needsAcknowledgement:!0}),!1}}reportProblem(e){let t=Rt(e);return this.update({problem:t,message:t.message}),t}async exclusive(e,t=!1){if(!this.current.busy){this.update({busy:!0,...t?{}:{message:""}});try{return await e()}finally{this.update({busy:!1})}}}async loadPreview(){let e=this.getProfile();if(!e)return null;try{let{preview:t,status:n}=await this.controller.inspect();return Td(e,this.getProfile())?(this.update({preview:t,status:n,problem:null}),t):null}catch(t){if(!Td(e,this.getProfile()))return null;let n=Rt(t);return this.update({problem:n,message:n.message}),null}}async applyReviewed(){let e=this.current.preview;if(!e)return"failed";let t=this.getProfile()?.collectionId,n=new Date().toISOString(),i=[],s="failed",o;try{let a=await this.controller.sync(e,h=>this.update({progress:h}),h=>this.update({fileProgress:h}),(h,m)=>{let y=Kx(h,m,new Date().toISOString());y&&i.push(y)});s=a.status,o=a.failure?.message;let{preview:c,status:l}=await this.controller.inspect(),u=a.status==="cancelled"?Rt(new DOMException("Synchronization stopped.","AbortError")):a.status==="failed"||a.status==="blocked"?q$(a.failure??{code:"sync_failed",message:"Synchronization stopped."}):null,d=a.status==="applied"?"Sync complete.":a.status==="attention"?a.applied>0?"Available changes synced. Remaining items need attention.":"No available changes. Resolve the listed items and review again.":a.status==="cancelled"?`Sync paused after ${a.applied} ${a.applied===1?"change":"changes"}. Resume to finish the rest.`:a.status==="stale"?"Files changed during sync; checking again.":u?.message??`Sync stopped: ${a.failure?.message??a.status}.`;this.update({status:l,preview:c.plan.actions.length||c.entries.length?c:null,problem:u,message:d,...a.status==="applied"&&a.pending===0?{localChangeObserved:!1}:{}});let f=u?`${u.kind}:${u.code}`:null,p=a.status==="stale"||u?.kind==="offline"||a.status==="attention"&&l.conflicts.length>0||f!==null&&f===this.pinnedFailure;return a.status==="applied"?this.pinnedFailure=null:f&&!p&&(this.pinnedFailure=f),!p&&(a.status!=="applied"||!i.length)&&await this.recordEvent({summary:a.status==="applied"?`Synchronized ${a.applied} ${a.applied===1?"change":"changes"}`:a.status==="cancelled"?"Synchronization paused safely":a.applied>0?"Synced available changes":"Synchronization needs attention",message:d,tone:a.status==="applied"?"success":"attention",needsAcknowledgement:a.status!=="applied"&&a.status!=="attention"},t),a.status==="blocked"?"failed":a.status}catch(a){let c=Rt(a);s=c.kind==="paused"?"cancelled":"failed",o=c.message,this.update({problem:c,message:c.message});let l=`${c.kind}:${c.code}`;return c.kind!=="offline"&&l!==this.pinnedFailure&&(this.pinnedFailure=l,await this.recordEvent({summary:c.title,message:c.message,tone:c.kind==="paused"?"attention":"error",needsAcknowledgement:c.kind!=="paused"},t)),c.kind==="paused"?"cancelled":"failed"}finally{if(this.update({progress:null,fileProgress:null}),t&&i.length&&this.history){try{await this.history.append({id:crypto.randomUUID(),collectionId:t,startedAt:n,finishedAt:new Date().toISOString(),outcome:s,files:i,...o?{message:o}:{}})}catch(a){console.error("mdbase: could not save sync history",a)}this.update({})}}}};function Td(r,e){return r?.collectionId===e?.collectionId&&r?.replicaId===e?.replicaId&&r?.enrollmentId===e?.enrollmentId}function aj(r){let e=r.path.split("/").pop()??r.path;switch(r.outcome){case"merged":return{summary:`Merged edits to ${e}`,message:"Changes made here and on another device were combined.",path:r.path,tone:"success"};case"kept_both":return{summary:`Kept both versions of ${e}`,message:`The same part was edited on two devices. The other device's version is in place and this device's version was saved as ${r.copyPath??"a copy"}.`,path:r.path,tone:"attention",needsAcknowledgement:!0};case"restored":return{summary:`Restored ${e}`,message:"It was deleted here but edited on another device, so the edited version was kept.",path:r.path,tone:"info"};case"kept_local":return{summary:`Kept ${e}`,message:"It was deleted on another device but edited here, so this version was uploaded again.",path:r.path,tone:"info"};case"took_hosted":return{summary:`Settled ${e}`,message:"The hosted version was kept.",path:r.path,tone:"info"};case"unresolved":return{summary:`Couldn't sync ${e}`,message:r.reason??"This change needs a decision.",path:r.path,tone:"attention",needsAcknowledgement:!0}}}var cj={localQuietMs:3e3,localMaxWaitMs:2e4,probeVisibleMs:3e4,probeHiddenMs:5*6e4,safetyNetMs:15*6e4,retryBaseMs:5e3,retryMaxMs:5*6e4,unexpectedRetryMaxMs:30*6e4},cy=new Set(["auth","device","paused"]),Id=class{constructor(e,t=lj,n=cj){this.host=e;this.clock=t;this.timing=n;this.timer=null;this.dueAt=null;this.dueIsDebounce=!1;this.firstLocalChangeAt=null;this.changed=!0;this.failures=0;this.running=!1;this.rerun=!1;this.visible=!0;this.stopped=!0;this.lastSyncAt=t.now()}start(){this.stopped=!1,this.schedule(this.clock.now())}stop(){this.stopped=!0,this.timer!==null&&this.clock.clearTimeout(this.timer),this.timer=null,this.dueAt=null}noteLocalChange(){let e=this.clock.now();this.firstLocalChangeAt??=e,this.changed=!0,this.schedule(Math.min(e+this.timing.localQuietMs,this.firstLocalChangeAt+this.timing.localMaxWaitMs),!0)}noteVisibility(e){let t=this.visible;this.visible=e,e&&!t&&this.schedule(this.clock.now())}noteOnline(){this.failures>0&&(this.changed=!0),this.failures=0,this.host.setRetryAt(null),this.schedule(this.clock.now())}requestSoon(){this.changed=!0,this.schedule(this.clock.now())}async tick(){if(this.stopped)return;if(this.running){this.rerun=!0;return}this.running=!0,this.dueAt=null;let e=null;try{e=await this.decide()}catch(t){this.host.reportProblem(t);let n=this.host.problemKind();e=n&&cy.has(n)?this.settled():this.failed(ks(t))}finally{this.running=!1;let t=this.clock.now();this.rerun?(this.rerun=!1,this.schedule(t)):e!==null?this.schedule(t+e):this.schedule(t+(this.visible?this.timing.probeVisibleMs:this.timing.probeHiddenMs))}}async decide(){if(!this.host.connected())return null;let e=this.host.problemKind();if(e&&cy.has(e))return null;let t=this.clock.now(),n=this.changed;if(this.changed=!1,this.firstLocalChangeAt=null,!this.host.automatic())return(n||await this.probe()===!0)&&await this.host.refreshStatus(),null;let i=n||this.failures>0||t-this.lastSyncAt>=this.timing.safetyNetMs;if(!i){let o=await this.probe();if(o===null)return this.failed(!0);i=o}if(!i)return null;this.lastSyncAt=t;let s=await this.host.autoSync();if(s==="busy"||s==="pending")return this.changed||=n||s==="pending",2e3;if(s==="failed"){this.changed||=n;let o=this.host.problemKind();return o&&cy.has(o)?this.settled():this.failed(o==="offline")}return this.settled()}async probe(){try{return await this.host.remoteChangesWaiting()}catch(e){return this.host.reportProblem(e),ks(e)?null:!0}}failed(e){let t=Cm(this.failures,{baseDelayMs:this.timing.retryBaseMs,maxDelayMs:e?this.timing.retryMaxMs:this.timing.unexpectedRetryMaxMs,random:()=>this.clock.random()});return this.failures+=1,this.host.setRetryAt(this.clock.now()+t),t}settled(){return this.failures=0,this.host.setRetryAt(null),null}schedule(e,t=!1){if(this.stopped)return;let n=this.timer===null?null:this.dueAt;n!==null&&n<=e&&!(t&&this.dueIsDebounce)||(this.timer!==null&&this.clock.clearTimeout(this.timer),this.dueAt=e,this.dueIsDebounce=t,this.timer=this.clock.setTimeout(()=>{this.timer=null,this.dueAt=null,this.tick()},Math.max(0,e-this.clock.now())))}},lj={now:()=>Date.now(),setTimeout:(r,e)=>window.setTimeout(r,e),clearTimeout:r=>window.clearTimeout(r),random:()=>Math.random()};function Q$(r){let{profile:e,state:t}=r,n=["mdbase sync diagnostics",`Generated: ${r.generatedAt}`,`Plugin ${r.pluginVersion} \xB7 Obsidian ${r.obsidianVersion} \xB7 ${r.platform}`,"","Connection"];e?n.push(` Collection: ${e.collectionId}`,` Replica: ${e.replicaId} (${e.mode})`,` Connect: ${X$(e.controlUrl)} \xB7 sync ${X$(e.syncUrl)}`,` Access token expires: ${e.accessTokenExpiresAt}`,` Enrolled on this device: ${r.otherDevice?"no \u2014 copied from another device or vault":"yes"}`,` File classes: ${e.selectiveSync?.file_classes.join(", ")||"notes only"}`,` Excluded folders: ${e.selectiveSync?.excluded_folders.length??0}`):n.push(" Not connected"),n.push(` Automatic sync: ${r.automatic?"on":"off"}${t.paused?" (paused)":""}`,` Other sync services on this vault: ${r.otherSyncServices.join(", ")||"none detected"}`,"","State",` Engine state: ${t.status?.state??"unknown"} \xB7 pending ${t.status?.pending??"?"} \xB7 conflicts ${t.status?.conflicts.length??0} \xB7 local issues ${t.status?.local_issues.length??0}`,` Last synced: ${t.status?.last_synced_at??"never"}`,` Problem: ${t.problem?`${t.problem.kind}/${t.problem.code} \u2014 ${t.problem.message}`:"none"}`,` Next automatic attempt: ${t.retryAt?new Date(t.retryAt).toISOString():"not scheduled"}`,` Plan on screen: ${t.preview?`${t.preview.plan.kind}, ${t.preview.plan.actions.length} actions, ${t.preview.plan.summary.blocking_issues} blocking issues`:"none"}`,` Checkpoint: ${r.checkpoint?`cursor ${r.checkpoint.cursor}, generation ${r.checkpoint.generation}`:"none"}`,` Interrupted batch: ${r.checkpoint?.batch??"none"}${r.checkpoint?.failure?` (${r.checkpoint.failure})`:""}`,"","Recent history (newest first)");let i=[...r.history].sort((s,o)=>o.finishedAt.localeCompare(s.finishedAt)).slice(0,25);i.length||n.push(" none");for(let s of i){let o=s.summary??`${s.files.length} ${s.files.length===1?"file":"files"}`;n.push(` ${s.finishedAt} \xB7 ${s.outcome}${s.tone?`/${s.tone}`:""} \xB7 ${o}${s.message?` \u2014 ${s.message}`:""}`)}return`${n.join(` `)} -`}function Jx(r){try{return new URL(r).host}catch{return"invalid URL"}}var cj={validateOnSave:!0,validateOnOpen:!0,showNoticeOnSave:!1,interopEnabled:!1,mirrorProfile:null,typeDrafts:{},archivedTypeDrafts:[],autoSync:!0,syncSettingsVersion:2},Xx="mdbase-sync-device-id";function lj(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;return e.version===1&&typeof e.syncUrl=="string"&&typeof e.controlUrl=="string"&&typeof e.collectionId=="string"&&typeof e.replicaId=="string"&&(e.mode==="read_only"||e.mode==="read_write")&&typeof e.name=="string"&&typeof e.enrollmentId=="string"&&typeof e.accessTokenExpiresAt=="string"&&(e.selectiveSync===void 0||Array.isArray(e.selectiveSync.file_classes)&&Array.isArray(e.selectiveSync.excluded_folders))}function dj(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Rd=class extends L.Plugin{constructor(t,n){super(t,n);this.issueMap=new Map;this.validation=new Ta;this.validationAbort=null;this.sortedIssuesCache=null;this.noteStatusVersion=0;this.syncScheduler=null;this.recordCache=null;this.recordCacheSettings="";this.recordList=null;this.recordLoadPromise=null;this.dirtyRecordPaths=new Set;this.schemaCache=null;this.schemaLoadPromise=null;this.saveValidationDebounceMs=2e3;this.schemaRefreshDebounceMs=2e3;this.saveValidations=new Aa(this.saveValidationDebounceMs,async(t,n)=>{try{await this.validateFileAndStore(t,"save",n)}catch(i){console.error("mdbase: background validation failed",i)}});this.schemaRefreshes=new Aa(this.schemaRefreshDebounceMs,async()=>{this.invalidateSchemaCache(),this.refreshWorkspaceViews()});this.connectSync=new fd(t,{getMirrorProfile:()=>this.getMirrorProfile(),saveMirrorProfile:async i=>{this.settings.mirrorProfile=i,await this.saveSettings(),i?this.requestSync():this.sync?.reset()},deviceId:()=>this.deviceId()}),this.interopBridge=new Vc(t,()=>this.settings?.interopEnabled===!0),this.api={apiVersion:1,interop:this.interopBridge,getInteropStatus:()=>({enabled:this.settings?.interopEnabled===!0,profileVersion:"0.1"})}}async onload(){await this.loadSettings(),await this.connectSync.initialize(),await this.createSyncSession(),(0,L.addIcon)(Sa,wx),this.statusBarEl=this.addStatusBarItem(),this.statusBarEl.addClass("mdbase-status-bar"),this.statusBarEl.setAttr("role","button"),this.statusBarEl.setAttr("tabindex","0"),this.registerDomEvent(this.statusBarEl,"click",()=>void this.openStatusDestination()),this.registerDomEvent(this.statusBarEl,"keydown",n=>{n.key!=="Enter"&&n.key!==" "||(n.preventDefault(),this.openStatusDestination())}),this.noteStatusEl=this.addStatusBarItem(),this.noteStatusEl.addClass("mdbase-note-status"),this.noteStatusEl.setAttr("role","button"),this.noteStatusEl.setAttr("tabindex","0"),this.noteStatusEl.hide(),this.registerDomEvent(this.noteStatusEl,"click",()=>void this.openNoteStatusDestination()),this.registerDomEvent(this.noteStatusEl,"keydown",n=>{n.key!=="Enter"&&n.key!==" "||(n.preventDefault(),this.openNoteStatusDestination())}),this.updateStatusBar(),this.registerView(Dr,n=>new kd(n,this)),this.addSettingTab(new Cd(this.app,this)),this.addRibbonIcon(Sa,"Open mdbase",()=>void this.openWorkspace()),gw(this),this.registerEvent(this.app.vault.on("modify",n=>{n instanceof L.TFile&&this.onVaultModify(n)})),this.registerEvent(this.app.vault.on("rename",(n,i)=>{n instanceof L.TFile&&this.onVaultRename(n,i)})),this.registerEvent(this.app.vault.on("delete",n=>{n instanceof L.TFile&&this.onVaultDelete(n)})),this.registerEvent(this.app.vault.on("create",n=>{n instanceof L.TFile&&this.onVaultCreate(n)})),this.registerEvent(this.app.workspace.on("file-open",n=>{this.settings.validateOnOpen&&(!(n instanceof L.TFile)||n.extension!=="md"||this.validateFileAndStore(n,"open"))})),this.registerEvent(this.app.workspace.on("active-leaf-change",()=>void this.updateNoteStatus())),this.registerEvent(this.app.metadataCache.on("changed",n=>{n.path===this.app.workspace.getActiveFile()?.path&&this.updateNoteStatus()})),this.registerEvent(this.app.workspace.on("editor-change",(n,i)=>{let s=i.file;s instanceof L.TFile&&(this.saveValidations.has(s.path)&&this.scheduleSaveValidation(s),this.schemaRefreshes.has("schema")&&this.isSchemaRelevantPath(s.path)&&this.scheduleSchemaRefresh())}));try{await Nd(this.app)}catch(n){new L.Notice(`Contract pack recovery needs attention: ${String(n)}`,0)}let t=this.app.workspace.getActiveFile();t&&this.settings.validateOnOpen&&this.validateFileAndStore(t,"open"),this.startSyncScheduler()}startSyncScheduler(){this.syncScheduler=new Td({connected:()=>this.getMirrorProfile()!==null,automatic:()=>this.settings.autoSync,problemKind:()=>this.sync.state.problem?.kind??(this.sync.state.paused?"paused":null),autoSync:()=>this.sync.autoSync(),refreshStatus:()=>this.sync.refreshStatus(),remoteChangesWaiting:()=>this.connectSync.remoteChangesWaiting(),reportProblem:n=>{this.sync.reportProblem(n)},setRetryAt:n=>this.sync.setRetryAt(n)}),this.registerDomEvent(window,"online",()=>this.syncScheduler?.noteOnline()),this.registerDomEvent(window,"focus",()=>this.syncScheduler?.noteVisibility(!0));let t=window.document;this.registerDomEvent(t,"visibilitychange",()=>{this.syncScheduler?.noteVisibility(t.visibilityState==="visible")}),this.syncScheduler.start()}requestSync(){this.syncScheduler?.requestSoon()}deviceId(){let t=this.app.loadLocalStorage(Xx);if(typeof t=="string"&&t)return t;let n=crypto.randomUUID();return this.app.saveLocalStorage(Xx,n),n}onunload(){this.validationAbort?.abort(),this.syncScheduler?.stop(),this.connectSync.dispose(),this.interopBridge.dispose().catch(t=>{console.error("mdbase: failed to dispose the interoperability bridge",t)}),this.app.workspace.getLeavesOfType(Dr).forEach(t=>t.detach()),this.saveValidations.clear(),this.schemaRefreshes.clear()}async loadSettings(){let t=await this.loadData();if(this.settings=Object.assign({},cj,t),t&&(t.syncSettingsVersion??1)<2&&(this.settings.autoSync=!0,this.settings.syncSettingsVersion=2),!lj(this.settings.mirrorProfile))this.settings.mirrorProfile=null;else try{this.settings.mirrorProfile.selectiveSync=fr(this.settings.mirrorProfile.selectiveSync)}catch{this.settings.mirrorProfile.selectiveSync=fr()}(!this.settings.typeDrafts||typeof this.settings.typeDrafts!="object"||Array.isArray(this.settings.typeDrafts))&&(this.settings.typeDrafts={}),this.settings.archivedTypeDrafts=Array.isArray(this.settings.archivedTypeDrafts)?this.settings.archivedTypeDrafts:[]}async saveSettings(){await this.saveData(this.settings)}getIssues(){return this.sortedIssuesCache??=Array.from(this.issueMap.values()).flat().sort((t,n)=>t.path.localeCompare(n.path)||t.severity.localeCompare(n.severity)||t.code.localeCompare(n.code)),this.sortedIssuesCache}getMirrorProfile(){return this.settings.mirrorProfile?JSON.parse(JSON.stringify(this.settings.mirrorProfile)):null}otherSyncServices(){let t=[],n=this.app,i=n.internalPlugins?.getEnabledPluginById?.("sync");typeof i?.vaultId=="string"&&i.vaultId&&t.push("Obsidian Sync");let s={"obsidian-livesync":"Self-hosted LiveSync","remotely-save":"Remotely Save","obsidian-git":"Obsidian Git"};for(let[l,u]of Object.entries(s))n.plugins?.enabledPlugins?.has(l)&&t.push(u);let o=this.app.vault.adapter,a=typeof L.FileSystemAdapter=="function"&&o instanceof L.FileSystemAdapter?o.getBasePath():"",c=[[/Mobile Documents|iCloud/i,"iCloud Drive"],[/[\\/]Dropbox[\\/]/i,"Dropbox"],[/[\\/]OneDrive/i,"OneDrive"],[/Google ?Drive|GoogleDrive/i,"Google Drive"]];for(let[l,u]of c)l.test(a)&&t.push(u);return t}async copySyncDiagnostics(){let t=this.getMirrorProfile(),n=null;try{n=await this.connectSync.checkpointSummary()}catch(s){console.error("mdbase: could not read the sync checkpoint for diagnostics",s)}let i=Yx({generatedAt:new Date().toISOString(),pluginVersion:this.manifest.version,obsidianVersion:L.apiVersion,platform:L.Platform.isIosApp?"iOS":L.Platform.isAndroidApp?"Android":L.Platform.isMacOS?"macOS":L.Platform.isWin?"Windows":L.Platform.isLinux?"Linux":"unknown",profile:t,otherDevice:this.connectSync.isOtherDevice(t),automatic:this.settings.autoSync,otherSyncServices:this.otherSyncServices(),state:this.sync.state,checkpoint:n,history:this.sync.historyRuns()});await navigator.clipboard.writeText(i),new L.Notice("Copied sync diagnostics. They name the collection and recent files but contain no note text or credentials.")}openNoteSyncHistory(t){new Pd(this.app,t,this.sync.historyRuns()).open()}openSettings(){let t=this.app.setting;t?.open(),t?.openTabById(this.manifest.id)}async createSyncSession(){let t=this.manifest.dir??`${this.app.vault.configDir}/plugins/${this.manifest.id}`,n=new ad(this.app.vault.adapter,(0,L.normalizePath)(`${t}/sync-history.jsonl`));try{await n.load(),await this.migrateSyncActivity(n)}catch(i){console.error("mdbase: could not load sync history",i)}this.sync=new Md(this.connectSync,()=>this.getMirrorProfile(),n,i=>{new L.Notice(`mdbase: ${i}`,1e4)}),this.register(this.sync.subscribe(()=>this.updateStatusBar()))}async migrateSyncActivity(t){let n=Lx(this.settings.syncActivity),i=this.settings.mirrorProfile?.collectionId;if(i)for(let s of n)await t.append(cd(i,{summary:s.summary,tone:s.tone,...s.detail?{message:s.detail}:{},...s.path?{path:s.path}:{},...s.requiresAcknowledgement?{needsAcknowledgement:!0}:{}},s.occurredAt));this.settings.syncActivity!==void 0&&(delete this.settings.syncActivity,await this.saveSettings())}async loadWorkspaceSchema(t=!1){return this.getConfigAndTypes(t)}async loadTypeModel(t){let n=this.app.vault.getAbstractFileByPath((0,L.normalizePath)(t));if(!(n instanceof L.TFile))throw new Error(`Type file not found: ${t}`);let i=await this.app.vault.cachedRead(n),s=Me(i);if(!s.hasFrontmatter||s.error)throw new Error(`Invalid type frontmatter: ${s.error??"frontmatter is missing"}`);let o=gd(s.frontmatter,s.body,n.basename);return o.sourceRevision=Jm(i),o}loadTypeDraft(t){let n=this.settings.typeDrafts[t??"__new__"];return n?JSON.parse(JSON.stringify(n)):null}async saveTypeDraft(t){let n=this.loadTypeDraft(t.path);n&&n.sourceRevision!==t.sourceRevision&&this.settings.archivedTypeDrafts.push(n),this.settings.typeDrafts[t.path??"__new__"]=JSON.parse(JSON.stringify(t)),await this.saveSettings()}getArchivedTypeDrafts(t){return this.settings.archivedTypeDrafts.filter(n=>n.path===t)}async discardArchivedTypeDraft(t){this.settings.archivedTypeDrafts=this.settings.archivedTypeDrafts.filter(n=>n.path!==t.path||n.updatedAt!==t.updatedAt||n.sourceRevision!==t.sourceRevision),await this.saveSettings()}async clearTypeDraft(t){let n=t??"__new__";n in this.settings.typeDrafts&&(delete this.settings.typeDrafts[n],await this.saveSettings())}async saveTypeModel(t,n,i){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access. Re-enroll it with write access before editing types.");let s=await ai(this.app.vault);if(!s)throw new Error("No mdbase.yaml found.");if(!s.spec_version.startsWith("0.3."))throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let o=n?this.app.vault.getAbstractFileByPath((0,L.normalizePath)(n)):null;if(o!=null&&!(o instanceof L.TFile))throw new Error(`Type file not found: ${n}`);let a=await this.writeTypeDefinition(s,t,o,i);return this.refreshWorkspaceViews(!0),a}getValidationSummary(){let t=this.schemaCache?.config,n=this.app.vault.getMarkdownFiles().filter(i=>!t||!yt(i.path,t)).map(i=>i.path);return this.validation.summary(n)}isValidating(){return this.validationAbort!==null}cancelValidation(){this.validationAbort?.abort()}async openContractCatalog(){if(this.getMirrorProfile())throw new Error("Install packs at the hosted collection authority using mdbase editor.");let t=await this.getConfigAndTypes();if(!t||!t.config.spec_version.startsWith("0.3."))throw new Error("Initialize or migrate this collection first.");if(t.config.settings.types_folder!=="_types"||(t.config.settings.contracts_folder??"_contracts")!=="_contracts")throw new Error("Catalog packs require the standard _types and _contracts folders. Use mdbase editor for custom target mappings.");new Ma(this.app,()=>{if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile())throw new Error("The vault role changed. Install at the collection authority instead.")},async n=>{this.invalidateSchemaCache();let i=await this.openWorkspace("types");await i.refresh(!0);let s=await this.getConfigAndTypes(),o=n?s?.types.get(n):null;o&&await i.editType(o.filePath),new L.Notice("Installed contract pack. Edit its type or create a note to try it.")}).open()}async createNoteFromType(t){await Fp(this,t)}async initializeCollection(){this.connectSync.assertLocalAuthorityWritable();let{created:t}=await $o(this.app.vault,{seedNoteType:!1});this.invalidateSchemaCache(),new L.Notice(t.length?`Initialized mdbase collection: ${t.join(", ")}`:"mdbase collection already initialized."),this.refreshWorkspaceViews(!0)}async validateCollection(){await this.runCollectionValidation(!1)}analyzeMigration(){if(this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");return lx(this.app.vault)}async applyMigration(t,n){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");let i=await dx(this.app.vault,t,{allowLossy:n});if(!i.applied)throw new Error(i.restored?`Migration failed and all writes were rolled back. ${i.error??""}`.trim():`Migration needs manual recovery. See ${i.manifestPath}. ${i.error??""}`.trim());this.invalidateSchemaCache(),new L.Notice(`Migrated to mdbase v0.3. Recovery manifest: ${i.manifestPath}`),this.refreshWorkspaceViews(!0)}async openIssue(t){await this.openFileByPath(t.path,t.field)}getQuickFixLabel(t){return ww(t)}async applyQuickFix(t){this.connectSync.assertLocalAuthorityWritable();let n=this.app.vault.getAbstractFileByPath(t.path);if(!(n instanceof L.TFile)){new L.Notice(`File not found: ${t.path}`);return}if(this.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access.");let i=!1;await this.app.vault.process(n,s=>{this.connectSync.assertLocalAuthorityWritable();let o=jp(s,t);return i=o.changed,o.content}),new L.Notice(i?`Updated '${t.field??"field"}' in ${n.basename}`:"The field changed or no safe quick fix is available. Revalidate the note."),await this.validateFileAndStore(n,"manual")}async applyQuickFixes(t){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access.");let n=0,i=0,s=new Map;for(let o of t){let a=this.app.vault.getAbstractFileByPath(o.path);if(!(a instanceof L.TFile)){i+=1;continue}let c=!1;await this.app.vault.process(a,l=>{this.connectSync.assertLocalAuthorityWritable();let u=jp(l,o);return c=u.changed,u.content}),c?(n+=1,s.set(a.path,a)):i+=1}for(let o of s.values())await this.validateFileAndStore(o,"manual");return{changed:n,skipped:i}}async openFileByPath(t,n){let i=this.app.vault.getAbstractFileByPath(t);if(!(i instanceof L.TFile)){new L.Notice(`File not found: ${t}`);return}await this.app.workspace.getLeaf(!0).openFile(i),n&&this.revealFrontmatterField(i,n)}revealFrontmatterField(t,n){let i=this.app.workspace.getMostRecentLeaf();if(!i||!(i.view instanceof L.MarkdownView))return;let s=i.view;if(!(s.file instanceof L.TFile)||s.file.path!==t.path)return;let o=s.editor,a=o.lineCount();if(a<3)return;let c=Dp(n),l=new RegExp(`^\\s*${dj(c)}\\s*:`);if(o.getLine(0).trim()==="---")for(let u=1;ud.severity==="error").length,c=this.validation.isChecked(n.path),l=c?o.length?` \xB7 ${o.length} ${o.length===1?"issue":"issues"}`:" \xB7 checked":" \xB7 not checked";this.noteStatusEl.setText(`${s.join(", ")}${l}`),this.noteStatusEl.setAttr("data-state",c?a?"error":o.length?"warning":"valid":"unchecked"),this.noteStatusEl.setAttr("data-path",n.path);let u=o.length?`${n.basename}: ${o.length} ${o.length===1?"issue":"issues"}. Open issues for this note.`:`${n.basename} is a ${s.join(", ")} note. Edit the type.`;this.noteStatusEl.setAttr("aria-label",u),this.noteStatusEl.setAttr("title",u),this.noteStatusEl.show()}async openNoteStatusDestination(){let t=this.noteStatusEl.getAttr("data-path");if(!t)return;if(this.issueMap.get(t)?.length){(await this.openWorkspace("issues")).showIssuesForPath(t);return}let n=this.app.vault.getAbstractFileByPath(t),i=await this.getConfigAndTypes();if(!(n instanceof L.TFile)||!i)return;let[s]=Ke(t,this.app.metadataCache.getFileCache(n)?.frontmatter??{},i.config,i.types),o=s?i.types.get(s):void 0;if(!o)return;await(await this.openWorkspace("types")).editType(o.filePath)}markRecordChanged(t){this.validation.changed(t),this.recordCache&&(this.dirtyRecordPaths.add((0,L.normalizePath)(t)),this.recordList=null)}loadCollectionRecords(){return this.recordLoadPromise??=this.readRecords().finally(()=>{this.recordLoadPromise=null}),this.recordLoadPromise}async readRecords(){let t=await this.getConfigAndTypes();if(!t)return[];let n=JSON.stringify(t.config.settings);if(!this.recordCache||n!==this.recordCacheSettings){this.dirtyRecordPaths.clear();let i=await Ep(this.app.vault,t.config);this.recordCache=new Map(i.map(s=>[s.path,s])),this.recordCacheSettings=n,this.recordList=null}else if(this.dirtyRecordPaths.size){let i=[...this.dirtyRecordPaths];this.dirtyRecordPaths.clear();for(let s of i){this.recordCache.delete(s);let o=this.app.vault.getAbstractFileByPath(s);if(!(o instanceof L.TFile)||o.extension!=="md"||yt(s,t.config))continue;let a=Me(await this.app.vault.cachedRead(o));a.error||this.recordCache.set(s,{path:s,frontmatter:a.frontmatter})}this.recordList=null}return this.recordList??=[...this.recordCache.values()].sort((i,s)=>i.path.localeCompare(s.path)),this.recordList}syncIndicator(t){let n=this.sync.state,i=this.sync.safety();return Dx({connected:this.getMirrorProfile()!==null,status:n.status,progress:n.progress,fileProgress:n.fileProgress,problem:n.problem,validationIssues:t,localChangeObserved:n.localChangeObserved,reviewChanges:i&&!i.safe?n.preview?.plan.actions.length??0:0})}async openStatusDestination(){await this.openWorkspace(this.syncIndicator(this.getIssues().length).destination)}async openIssuesView(){await this.openWorkspace("issues")}async openWorkspace(t="types"){let n=this.app.workspace.getLeavesOfType(Dr)[0];if(n){await this.app.workspace.revealLeaf(n);let o=n.view;return o.showDestination(t),await o.refresh(),o}let i=this.app.workspace.getLeaf(!0);await i.setViewState({type:Dr,active:!0}),await this.app.workspace.revealLeaf(i);let s=i.view;return await s.refresh(),s.showDestination(t),s}refreshWorkspaceViews(t=!1){for(let n of this.app.workspace.getLeavesOfType(Dr)){let i=n.view;typeof i.refresh=="function"&&i.refresh(t)}}refreshIssueViews(){this.updateStatusBar(),this.refreshWorkspaceViews()}setFileIssues(t,n){n.length===0?this.issueMap.delete(t):this.issueMap.set(t,n),this.sortedIssuesCache=null,this.refreshIssueViews()}clearFileIssues(t){this.issueMap.has(t)&&(this.issueMap.delete(t),this.sortedIssuesCache=null,this.refreshIssueViews())}moveFileIssues(t,n){let i=this.issueMap.get(t);i&&(this.issueMap.delete(t),this.issueMap.set(n,i.map(s=>({...s,path:n}))),this.sortedIssuesCache=null,this.refreshIssueViews())}clearPendingSaveValidation(t){this.saveValidations.cancel(t)}scheduleSaveValidation(t){this.saveValidations.schedule(t.path,t)}scheduleSchemaRefresh(){this.schemaRefreshes.schedule("schema",void 0)}refreshSchemaNow(){this.schemaRefreshes.cancel("schema"),this.invalidateSchemaCache(),this.refreshWorkspaceViews()}isSchemaRelevantPath(t){let n=(0,L.normalizePath)(t);if(n==="mdbase.yaml")return!0;let i=new Set(["_types","_contracts"]);this.schemaCache&&(i.add((0,L.normalizePath)(this.schemaCache.config.settings.types_folder)),i.add((0,L.normalizePath)(this.schemaCache.config.settings.contracts_folder??"_contracts")));for(let s of i)if(n===s||n.startsWith(`${s}/`))return!0;return!1}invalidateSchemaCache(){this.validation.changed(),this.schemaCache=null,this.schemaLoadPromise=null}async getConfigAndTypes(t=!1){if(t&&this.invalidateSchemaCache(),this.schemaCache)return this.schemaCache;if(this.schemaLoadPromise)return this.schemaLoadPromise;this.schemaLoadPromise=(async()=>{let n=await ai(this.app.vault);if(!n)return null;let i=await Ap(this.app.vault,n),s=await kp(this.app.vault,n);return{config:n,types:i,contracts:s}})();try{let n=await this.schemaLoadPromise;return n&&(this.schemaCache=n),n}finally{this.schemaLoadPromise=null}}async requireConfigAndTypes(t={}){let n=t.background??!1,i=await this.getConfigAndTypes(t.forceReload??!1);return i?(i.types.size===0&&!n&&new L.Notice(`No types found in ${i.config.settings.types_folder}`),i):(n||new L.Notice("No mdbase.yaml found. Run 'mdbase: Initialize collection' first."),null)}onVaultModify(t){this.observeLocalMirrorChange(t.path),this.markRecordChanged(t.path),this.isSchemaRelevantPath(t.path)&&this.scheduleSchemaRefresh(),this.settings.validateOnSave&&t.extension==="md"&&this.scheduleSaveValidation(t)}onVaultRename(t,n){this.observeLocalMirrorChange(n),this.markRecordChanged(n),this.markRecordChanged(t.path),this.observeLocalMirrorChange(t.path),(this.isSchemaRelevantPath(n)||this.isSchemaRelevantPath(t.path))&&this.refreshSchemaNow(),t.extension==="md"&&(this.clearPendingSaveValidation(n),this.moveFileIssues(n,t.path),this.settings.validateOnSave&&this.scheduleSaveValidation(t))}onVaultDelete(t){this.observeLocalMirrorChange(t.path),this.markRecordChanged(t.path),this.isSchemaRelevantPath(t.path)&&this.refreshSchemaNow(),t.extension==="md"&&(this.clearPendingSaveValidation(t.path),this.clearFileIssues(t.path))}onVaultCreate(t){this.observeLocalMirrorChange(t.path),this.markRecordChanged(t.path),this.isSchemaRelevantPath(t.path)&&this.refreshSchemaNow()}observeLocalMirrorChange(t){if(!this.getMirrorProfile()||this.connectSync.isEngineWrite(t))return;let n=(0,L.normalizePath)(t);[this.app.vault.configDir,".mdbase",".trash",".git"].some(s=>n===s||n.startsWith(`${s}/`))||(this.sync.observeLocalChange(),this.syncScheduler?.noteLocalChange())}async validateFileAndStore(t,n,i=()=>!0){let s=await this.requireConfigAndTypes({background:n!=="manual"});if(!i())return[];if(!s)return n!=="manual"&&this.clearFileIssues(t.path),[];let o=this.validation.revision,a=await _c(this.app.vault,t,s.config,s.types);return!i()||o!==this.validation.revision||(this.validation.markChecked(t.path),this.setFileIssues(t.path,a),n==="save"&&this.settings.showNoticeOnSave&&a.length>0&&new L.Notice(`mdbase: ${a.length} issue${a.length===1?"":"s"} in ${t.basename}`)),a}async runCollectionValidation(t){if(this.validationAbort)return;let n=await this.requireConfigAndTypes({background:!1});if(!n||this.validationAbort)return;let i=new AbortController;this.validationAbort=i,this.validation.cancelled=!1;let s=this.validation.revision,o=new Map;try{let a=await Mp(this.app.vault,n.config,n.types,{signal:i.signal,onProgress:c=>{if(this.validation.progress=c,c.completed===0)for(let l of this.app.workspace.getLeavesOfType(Dr))l.view.refreshValidationControls();else if(c.completed%25===0||c.phase==="uniqueness")for(let l of this.app.workspace.getLeavesOfType(Dr))l.view.updateValidationProgress()},onFile:(c,l)=>{s===this.validation.revision&&(this.validation.markChecked(c.path),o.set(c.path,l),l.length?this.issueMap.set(c.path,l):this.issueMap.delete(c.path),this.sortedIssuesCache=null)}});if(s!==this.validation.revision){new L.Notice("Files changed during validation. Validate again for a complete result.");return}o.clear();for(let c of a)o.set(c.path,[...o.get(c.path)??[],c]);this.issueMap=o,this.validation.lastCompletedAt=new Date().toISOString(),this.validation.completedRevision=s,t&&(new L.Notice(a.length?`Collection validation: ${a.length} issues`:"Collection validation passed with no issues."),a.length&&await this.openIssuesView())}catch(a){if(this.validation.cancelled=!0,s===this.validation.revision)for(let[c,l]of o)l.length?this.issueMap.set(c,l):this.issueMap.delete(c);new L.Notice(i.signal.aborted?"Validation stopped. Results are incomplete.":`Validation could not finish: ${String(a)}. Results are incomplete.`)}finally{this.validation.progress=null,this.validationAbort=null,this.sortedIssuesCache=null;for(let a of this.app.workspace.getLeavesOfType(Dr))a.view.refreshValidationControls();this.refreshIssueViews()}}async ensureFolderExists(t){let n=(0,L.normalizePath)(t).replace(/\/+$/,"");if(!n)return;let i=n.split("/"),s="";for(let o of i)s=s?`${s}/${o}`:o,await this.app.vault.adapter.exists(s)||await this.app.vault.createFolder(s)}async writeTypeDefinition(t,n,i,s){let o=n.name.trim();if(!o)throw new Error("Type name is required.");if(!t.spec_version.startsWith("0.3.")||n.specProfile!=="v0.3")throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let a=Fn(n),c=n.body.trim()||`# ${o} +`}function X$(r){try{return new URL(r).host}catch{return"invalid URL"}}var dj={validateOnSave:!0,validateOnOpen:!0,showNoticeOnSave:!1,interopEnabled:!1,mirrorProfile:null,typeDrafts:{},archivedTypeDrafts:[],autoSync:!0,syncSettingsVersion:2},Z$="mdbase-sync-device-id";function uj(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Od=class extends L.Plugin{constructor(t,n){super(t,n);this.issueMap=new Map;this.validation=new Ra;this.validationAbort=null;this.sortedIssuesCache=null;this.noteStatusVersion=0;this.syncScheduler=null;this.recordCache=null;this.recordCacheSettings="";this.recordList=null;this.recordLoadPromise=null;this.dirtyRecordPaths=new Set;this.schemaCache=null;this.schemaLoadPromise=null;this.saveValidationDebounceMs=2e3;this.schemaRefreshDebounceMs=2e3;this.saveValidations=new ka(this.saveValidationDebounceMs,async(t,n)=>{try{await this.validateFileAndStore(t,"save",n)}catch(i){console.error("mdbase: background validation failed",i)}});this.schemaRefreshes=new ka(this.schemaRefreshDebounceMs,async()=>{this.invalidateSchemaCache(),this.refreshWorkspaceViews()});this.connectSync=new fd(t,{getMirrorProfile:()=>this.getMirrorProfile(),saveMirrorProfile:async i=>{this.settings.mirrorProfile=i,await this.saveSettings(),i?this.requestSync():this.sync?.reset()},deviceId:()=>this.deviceId()}),this.interopBridge=new Hc(t,()=>this.settings?.interopEnabled===!0),this.api={apiVersion:1,interop:this.interopBridge,getInteropStatus:()=>({enabled:this.settings?.interopEnabled===!0,profileVersion:"0.1"})}}async onload(){await this.loadSettings(),await this.connectSync.initialize(),await this.createSyncSession(),(0,L.addIcon)(xa,$$),this.statusBarEl=this.addStatusBarItem(),this.statusBarEl.addClass("mdbase-status-bar"),this.statusBarEl.setAttr("role","button"),this.statusBarEl.setAttr("tabindex","0"),this.registerDomEvent(this.statusBarEl,"click",()=>void this.openStatusDestination()),this.registerDomEvent(this.statusBarEl,"keydown",n=>{n.key!=="Enter"&&n.key!==" "||(n.preventDefault(),this.openStatusDestination())}),this.noteStatusEl=this.addStatusBarItem(),this.noteStatusEl.addClass("mdbase-note-status"),this.noteStatusEl.setAttr("role","button"),this.noteStatusEl.setAttr("tabindex","0"),this.noteStatusEl.hide(),this.registerDomEvent(this.noteStatusEl,"click",()=>void this.openNoteStatusDestination()),this.registerDomEvent(this.noteStatusEl,"keydown",n=>{n.key!=="Enter"&&n.key!==" "||(n.preventDefault(),this.openNoteStatusDestination())}),this.updateStatusBar(),this.registerView(Or,n=>new Pd(n,this)),this.addSettingTab(new Cd(this.app,this)),this.addRibbonIcon(xa,"Open mdbase",()=>void this.openWorkspace()),ww(this),this.registerEvent(this.app.vault.on("modify",n=>{n instanceof L.TFile&&this.onVaultModify(n)})),this.registerEvent(this.app.vault.on("rename",(n,i)=>{n instanceof L.TFile&&this.onVaultRename(n,i)})),this.registerEvent(this.app.vault.on("delete",n=>{n instanceof L.TFile&&this.onVaultDelete(n)})),this.registerEvent(this.app.vault.on("create",n=>{n instanceof L.TFile&&this.onVaultCreate(n)})),this.registerEvent(this.app.workspace.on("file-open",n=>{this.settings.validateOnOpen&&(!(n instanceof L.TFile)||n.extension!=="md"||this.validateFileAndStore(n,"open"))})),this.registerEvent(this.app.workspace.on("active-leaf-change",()=>void this.updateNoteStatus())),this.registerEvent(this.app.metadataCache.on("changed",n=>{n.path===this.app.workspace.getActiveFile()?.path&&this.updateNoteStatus()})),this.registerEvent(this.app.workspace.on("editor-change",(n,i)=>{let s=i.file;s instanceof L.TFile&&(this.saveValidations.has(s.path)&&this.scheduleSaveValidation(s),this.schemaRefreshes.has("schema")&&this.isSchemaRelevantPath(s.path)&&this.scheduleSchemaRefresh())}));try{await Fd(this.app)}catch(n){new L.Notice(`Contract pack recovery needs attention: ${String(n)}`,0)}let t=this.app.workspace.getActiveFile();t&&this.settings.validateOnOpen&&this.validateFileAndStore(t,"open"),this.startSyncScheduler()}startSyncScheduler(){this.syncScheduler=new Id({connected:()=>this.getMirrorProfile()!==null,automatic:()=>this.settings.autoSync,problemKind:()=>this.sync.state.problem?.kind??(this.sync.state.paused?"paused":null),autoSync:()=>this.sync.autoSync(),refreshStatus:()=>this.sync.refreshStatus(),remoteChangesWaiting:()=>this.connectSync.remoteChangesWaiting(),reportProblem:n=>{this.sync.reportProblem(n)},setRetryAt:n=>this.sync.setRetryAt(n)}),this.registerDomEvent(window,"online",()=>this.syncScheduler?.noteOnline()),this.registerDomEvent(window,"focus",()=>this.syncScheduler?.noteVisibility(!0));let t=window.document;this.registerDomEvent(t,"visibilitychange",()=>{this.syncScheduler?.noteVisibility(t.visibilityState==="visible")}),this.syncScheduler.start()}requestSync(){this.syncScheduler?.requestSoon()}deviceId(){let t=this.app.loadLocalStorage(Z$);if(typeof t=="string"&&t)return t;let n=crypto.randomUUID();return this.app.saveLocalStorage(Z$,n),n}onunload(){this.validationAbort?.abort(),this.syncScheduler?.stop(),this.connectSync.dispose(),this.interopBridge.dispose().catch(t=>{console.error("mdbase: failed to dispose the interoperability bridge",t)}),this.app.workspace.getLeavesOfType(Or).forEach(t=>t.detach()),this.saveValidations.clear(),this.schemaRefreshes.clear()}async loadSettings(){let t=await this.loadData();this.settings=Object.assign({},dj,t),t&&(t.syncSettingsVersion??1)<2&&(this.settings.autoSync=!0,this.settings.syncSettingsVersion=2),this.settings.mirrorProfile=c$(this.settings.mirrorProfile),(!this.settings.typeDrafts||typeof this.settings.typeDrafts!="object"||Array.isArray(this.settings.typeDrafts))&&(this.settings.typeDrafts={}),this.settings.archivedTypeDrafts=Array.isArray(this.settings.archivedTypeDrafts)?this.settings.archivedTypeDrafts:[]}async saveSettings(){await this.saveData(this.settings)}getIssues(){return this.sortedIssuesCache??=Array.from(this.issueMap.values()).flat().sort((t,n)=>t.path.localeCompare(n.path)||t.severity.localeCompare(n.severity)||t.code.localeCompare(n.code)),this.sortedIssuesCache}getMirrorProfile(){return this.settings.mirrorProfile?JSON.parse(JSON.stringify(this.settings.mirrorProfile)):null}otherSyncServices(){let t=[],n=this.app,i=n.internalPlugins?.getEnabledPluginById?.("sync");typeof i?.vaultId=="string"&&i.vaultId&&t.push("Obsidian Sync");let s={"obsidian-livesync":"Self-hosted LiveSync","remotely-save":"Remotely Save","obsidian-git":"Obsidian Git"};for(let[l,u]of Object.entries(s))n.plugins?.enabledPlugins?.has(l)&&t.push(u);let o=this.app.vault.adapter,a=typeof L.FileSystemAdapter=="function"&&o instanceof L.FileSystemAdapter?o.getBasePath():"",c=[[/Mobile Documents|iCloud/i,"iCloud Drive"],[/[\\/]Dropbox[\\/]/i,"Dropbox"],[/[\\/]OneDrive/i,"OneDrive"],[/Google ?Drive|GoogleDrive/i,"Google Drive"]];for(let[l,u]of c)l.test(a)&&t.push(u);return t}async copySyncDiagnostics(){let t=this.getMirrorProfile(),n=null;try{n=await this.connectSync.checkpointSummary()}catch(s){console.error("mdbase: could not read the sync checkpoint for diagnostics",s)}let i=Q$({generatedAt:new Date().toISOString(),pluginVersion:this.manifest.version,obsidianVersion:L.apiVersion,platform:L.Platform.isIosApp?"iOS":L.Platform.isAndroidApp?"Android":L.Platform.isMacOS?"macOS":L.Platform.isWin?"Windows":L.Platform.isLinux?"Linux":"unknown",profile:t,otherDevice:this.connectSync.isOtherDevice(t),automatic:this.settings.autoSync,otherSyncServices:this.otherSyncServices(),state:this.sync.state,checkpoint:n,history:this.sync.historyRuns()});await navigator.clipboard.writeText(i),new L.Notice("Copied sync diagnostics. They name the collection and recent files but contain no note text or credentials.")}openNoteSyncHistory(t){new Md(this.app,t,this.sync.historyRuns()).open()}openSettings(){let t=this.app.setting;t?.open(),t?.openTabById(this.manifest.id)}async createSyncSession(){let t=this.manifest.dir??`${this.app.vault.configDir}/plugins/${this.manifest.id}`,n=new cd(this.app.vault.adapter,(0,L.normalizePath)(`${t}/sync-history.jsonl`));try{await n.load(),await this.migrateSyncActivity(n)}catch(i){console.error("mdbase: could not load sync history",i)}this.sync=new Rd(this.connectSync,()=>this.getMirrorProfile(),n,i=>{new L.Notice(`mdbase: ${i}`,1e4)}),this.register(this.sync.subscribe(()=>this.updateStatusBar()))}async migrateSyncActivity(t){let n=B$(this.settings.syncActivity),i=this.settings.mirrorProfile?.collectionId;if(i)for(let s of n)await t.append(ld(i,{summary:s.summary,tone:s.tone,...s.detail?{message:s.detail}:{},...s.path?{path:s.path}:{},...s.requiresAcknowledgement?{needsAcknowledgement:!0}:{}},s.occurredAt));this.settings.syncActivity!==void 0&&(delete this.settings.syncActivity,await this.saveSettings())}async loadWorkspaceSchema(t=!1){return this.getConfigAndTypes(t)}async loadTypeModel(t){let n=this.app.vault.getAbstractFileByPath((0,L.normalizePath)(t));if(!(n instanceof L.TFile))throw new Error(`Type file not found: ${t}`);let i=await this.app.vault.cachedRead(n),s=Ce(i);if(!s.hasFrontmatter||s.error)throw new Error(`Invalid type frontmatter: ${s.error??"frontmatter is missing"}`);let o=gd(s.frontmatter,s.body,n.basename);return o.sourceRevision=Qm(i),o}loadTypeDraft(t){let n=this.settings.typeDrafts[t??"__new__"];return n?JSON.parse(JSON.stringify(n)):null}async saveTypeDraft(t){let n=this.loadTypeDraft(t.path);n&&n.sourceRevision!==t.sourceRevision&&this.settings.archivedTypeDrafts.push(n),this.settings.typeDrafts[t.path??"__new__"]=JSON.parse(JSON.stringify(t)),await this.saveSettings()}getArchivedTypeDrafts(t){return this.settings.archivedTypeDrafts.filter(n=>n.path===t)}async discardArchivedTypeDraft(t){this.settings.archivedTypeDrafts=this.settings.archivedTypeDrafts.filter(n=>n.path!==t.path||n.updatedAt!==t.updatedAt||n.sourceRevision!==t.sourceRevision),await this.saveSettings()}async clearTypeDraft(t){let n=t??"__new__";n in this.settings.typeDrafts&&(delete this.settings.typeDrafts[n],await this.saveSettings())}async saveTypeModel(t,n,i){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access. Re-enroll it with write access before editing types.");let s=await ai(this.app.vault);if(!s)throw new Error("No mdbase.yaml found.");if(!s.spec_version.startsWith("0.3."))throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let o=n?this.app.vault.getAbstractFileByPath((0,L.normalizePath)(n)):null;if(o!=null&&!(o instanceof L.TFile))throw new Error(`Type file not found: ${n}`);let a=await this.writeTypeDefinition(s,t,o,i);return this.refreshWorkspaceViews(!0),a}getValidationSummary(){let t=this.schemaCache?.config,n=this.app.vault.getMarkdownFiles().filter(i=>!t||!yt(i.path,t)).map(i=>i.path);return this.validation.summary(n)}isValidating(){return this.validationAbort!==null}cancelValidation(){this.validationAbort?.abort()}async openContractCatalog(){if(this.getMirrorProfile())throw new Error("Install packs at the hosted collection authority using mdbase editor.");let t=await this.getConfigAndTypes();if(!t||!t.config.spec_version.startsWith("0.3."))throw new Error("Initialize or migrate this collection first.");if(t.config.settings.types_folder!=="_types"||(t.config.settings.contracts_folder??"_contracts")!=="_contracts")throw new Error("Catalog packs require the standard _types and _contracts folders. Use mdbase editor for custom target mappings.");new Ta(this.app,()=>{if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile())throw new Error("The vault role changed. Install at the collection authority instead.")},async n=>{this.invalidateSchemaCache();let i=await this.openWorkspace("types");await i.refresh(!0);let s=await this.getConfigAndTypes(),o=n?s?.types.get(n):null;o&&await i.editType(o.filePath),new L.Notice("Installed contract pack. Edit its type or create a note to try it.")}).open()}async createNoteFromType(t){await qp(this,t)}async initializeCollection(){this.connectSync.assertLocalAuthorityWritable();let{created:t}=await $o(this.app.vault,{seedNoteType:!1});this.invalidateSchemaCache(),new L.Notice(t.length?`Initialized mdbase collection: ${t.join(", ")}`:"mdbase collection already initialized."),this.refreshWorkspaceViews(!0)}async validateCollection(){await this.runCollectionValidation(!1)}analyzeMigration(){if(this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");return p$(this.app.vault)}async applyMigration(t,n){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");let i=await h$(this.app.vault,t,{allowLossy:n});if(!i.applied)throw new Error(i.restored?`Migration failed and all writes were rolled back. ${i.error??""}`.trim():`Migration needs manual recovery. See ${i.manifestPath}. ${i.error??""}`.trim());this.invalidateSchemaCache(),new L.Notice(`Migrated to mdbase v0.3. Recovery manifest: ${i.manifestPath}`),this.refreshWorkspaceViews(!0)}async openIssue(t){await this.openFileByPath(t.path,t.field)}getQuickFixLabel(t){return xw(t)}async applyQuickFix(t){this.connectSync.assertLocalAuthorityWritable();let n=this.app.vault.getAbstractFileByPath(t.path);if(!(n instanceof L.TFile)){new L.Notice(`File not found: ${t.path}`);return}if(this.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access.");let i=!1;await this.app.vault.process(n,s=>{this.connectSync.assertLocalAuthorityWritable();let o=Bp(s,t);return i=o.changed,o.content}),new L.Notice(i?`Updated '${t.field??"field"}' in ${n.basename}`:"The field changed or no safe quick fix is available. Revalidate the note."),await this.validateFileAndStore(n,"manual")}async applyQuickFixes(t){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access.");let n=0,i=0,s=new Map;for(let o of t){let a=this.app.vault.getAbstractFileByPath(o.path);if(!(a instanceof L.TFile)){i+=1;continue}let c=!1;await this.app.vault.process(a,l=>{this.connectSync.assertLocalAuthorityWritable();let u=Bp(l,o);return c=u.changed,u.content}),c?(n+=1,s.set(a.path,a)):i+=1}for(let o of s.values())await this.validateFileAndStore(o,"manual");return{changed:n,skipped:i}}async openFileByPath(t,n){let i=this.app.vault.getAbstractFileByPath(t);if(!(i instanceof L.TFile)){new L.Notice(`File not found: ${t}`);return}await this.app.workspace.getLeaf(!0).openFile(i),n&&this.revealFrontmatterField(i,n)}revealFrontmatterField(t,n){let i=this.app.workspace.getMostRecentLeaf();if(!i||!(i.view instanceof L.MarkdownView))return;let s=i.view;if(!(s.file instanceof L.TFile)||s.file.path!==t.path)return;let o=s.editor,a=o.lineCount();if(a<3)return;let c=Lp(n),l=new RegExp(`^\\s*${uj(c)}\\s*:`);if(o.getLine(0).trim()==="---")for(let u=1;ud.severity==="error").length,c=this.validation.isChecked(n.path),l=c?o.length?` \xB7 ${o.length} ${o.length===1?"issue":"issues"}`:" \xB7 checked":" \xB7 not checked";this.noteStatusEl.setText(`${s.join(", ")}${l}`),this.noteStatusEl.setAttr("data-state",c?a?"error":o.length?"warning":"valid":"unchecked"),this.noteStatusEl.setAttr("data-path",n.path);let u=o.length?`${n.basename}: ${o.length} ${o.length===1?"issue":"issues"}. Open issues for this note.`:`${n.basename} is a ${s.join(", ")} note. Edit the type.`;this.noteStatusEl.setAttr("aria-label",u),this.noteStatusEl.setAttr("title",u),this.noteStatusEl.show()}async openNoteStatusDestination(){let t=this.noteStatusEl.getAttr("data-path");if(!t)return;if(this.issueMap.get(t)?.length){(await this.openWorkspace("issues")).showIssuesForPath(t);return}let n=this.app.vault.getAbstractFileByPath(t),i=await this.getConfigAndTypes();if(!(n instanceof L.TFile)||!i)return;let[s]=Ke(t,this.app.metadataCache.getFileCache(n)?.frontmatter??{},i.config,i.types),o=s?i.types.get(s):void 0;if(!o)return;await(await this.openWorkspace("types")).editType(o.filePath)}markRecordChanged(t){this.validation.changed(t),this.recordCache&&(this.dirtyRecordPaths.add((0,L.normalizePath)(t)),this.recordList=null)}loadCollectionRecords(){return this.recordLoadPromise??=this.readRecords().finally(()=>{this.recordLoadPromise=null}),this.recordLoadPromise}async readRecords(){let t=await this.getConfigAndTypes();if(!t)return[];let n=JSON.stringify(t.config.settings);if(!this.recordCache||n!==this.recordCacheSettings){this.dirtyRecordPaths.clear();let i=await kp(this.app.vault,t.config);this.recordCache=new Map(i.map(s=>[s.path,s])),this.recordCacheSettings=n,this.recordList=null}else if(this.dirtyRecordPaths.size){let i=[...this.dirtyRecordPaths];this.dirtyRecordPaths.clear();for(let s of i){this.recordCache.delete(s);let o=this.app.vault.getAbstractFileByPath(s);if(!(o instanceof L.TFile)||o.extension!=="md"||yt(s,t.config))continue;let a=Ce(await this.app.vault.cachedRead(o));a.error||this.recordCache.set(s,{path:s,frontmatter:a.frontmatter})}this.recordList=null}return this.recordList??=[...this.recordCache.values()].sort((i,s)=>i.path.localeCompare(s.path)),this.recordList}syncIndicator(t){let n=this.sync.state,i=this.sync.safety();return j$({connected:this.getMirrorProfile()!==null,status:n.status,progress:n.progress,fileProgress:n.fileProgress,problem:n.problem,validationIssues:t,localChangeObserved:n.localChangeObserved,reviewChanges:i&&!i.safe?n.preview?.plan.actions.length??0:0})}async openStatusDestination(){await this.openWorkspace(this.syncIndicator(this.getIssues().length).destination)}async openIssuesView(){await this.openWorkspace("issues")}async openWorkspace(t="types"){let n=this.app.workspace.getLeavesOfType(Or)[0];if(n){await this.app.workspace.revealLeaf(n);let o=n.view;return o.showDestination(t),await o.refresh(),o}let i=this.app.workspace.getLeaf(!0);await i.setViewState({type:Or,active:!0}),await this.app.workspace.revealLeaf(i);let s=i.view;return await s.refresh(),s.showDestination(t),s}refreshWorkspaceViews(t=!1){for(let n of this.app.workspace.getLeavesOfType(Or)){let i=n.view;typeof i.refresh=="function"&&i.refresh(t)}}refreshIssueViews(){this.updateStatusBar(),this.refreshWorkspaceViews()}setFileIssues(t,n){n.length===0?this.issueMap.delete(t):this.issueMap.set(t,n),this.sortedIssuesCache=null,this.refreshIssueViews()}clearFileIssues(t){this.issueMap.has(t)&&(this.issueMap.delete(t),this.sortedIssuesCache=null,this.refreshIssueViews())}moveFileIssues(t,n){let i=this.issueMap.get(t);i&&(this.issueMap.delete(t),this.issueMap.set(n,i.map(s=>({...s,path:n}))),this.sortedIssuesCache=null,this.refreshIssueViews())}clearPendingSaveValidation(t){this.saveValidations.cancel(t)}scheduleSaveValidation(t){this.saveValidations.schedule(t.path,t)}scheduleSchemaRefresh(){this.schemaRefreshes.schedule("schema",void 0)}refreshSchemaNow(){this.schemaRefreshes.cancel("schema"),this.invalidateSchemaCache(),this.refreshWorkspaceViews()}isSchemaRelevantPath(t){let n=(0,L.normalizePath)(t);if(n==="mdbase.yaml")return!0;let i=new Set(["_types","_contracts"]);this.schemaCache&&(i.add((0,L.normalizePath)(this.schemaCache.config.settings.types_folder)),i.add((0,L.normalizePath)(this.schemaCache.config.settings.contracts_folder??"_contracts")));for(let s of i)if(n===s||n.startsWith(`${s}/`))return!0;return!1}invalidateSchemaCache(){this.validation.changed(),this.schemaCache=null,this.schemaLoadPromise=null}async getConfigAndTypes(t=!1){if(t&&this.invalidateSchemaCache(),this.schemaCache)return this.schemaCache;if(this.schemaLoadPromise)return this.schemaLoadPromise;this.schemaLoadPromise=(async()=>{let n=await ai(this.app.vault);if(!n)return null;let i=await Pp(this.app.vault,n),s=await Mp(this.app.vault,n);return{config:n,types:i,contracts:s}})();try{let n=await this.schemaLoadPromise;return n&&(this.schemaCache=n),n}finally{this.schemaLoadPromise=null}}async requireConfigAndTypes(t={}){let n=t.background??!1,i=await this.getConfigAndTypes(t.forceReload??!1);return i?(i.types.size===0&&!n&&new L.Notice(`No types found in ${i.config.settings.types_folder}`),i):(n||new L.Notice("No mdbase.yaml found. Run 'mdbase: Initialize collection' first."),null)}onVaultModify(t){this.observeLocalMirrorChange(t.path),this.markRecordChanged(t.path),this.isSchemaRelevantPath(t.path)&&this.scheduleSchemaRefresh(),this.settings.validateOnSave&&t.extension==="md"&&this.scheduleSaveValidation(t)}onVaultRename(t,n){this.observeLocalMirrorChange(n),this.markRecordChanged(n),this.markRecordChanged(t.path),this.observeLocalMirrorChange(t.path),(this.isSchemaRelevantPath(n)||this.isSchemaRelevantPath(t.path))&&this.refreshSchemaNow(),t.extension==="md"&&(this.clearPendingSaveValidation(n),this.moveFileIssues(n,t.path),this.settings.validateOnSave&&this.scheduleSaveValidation(t))}onVaultDelete(t){this.observeLocalMirrorChange(t.path),this.markRecordChanged(t.path),this.isSchemaRelevantPath(t.path)&&this.refreshSchemaNow(),t.extension==="md"&&(this.clearPendingSaveValidation(t.path),this.clearFileIssues(t.path))}onVaultCreate(t){this.observeLocalMirrorChange(t.path),this.markRecordChanged(t.path),this.isSchemaRelevantPath(t.path)&&this.refreshSchemaNow()}observeLocalMirrorChange(t){if(!this.getMirrorProfile()||this.connectSync.consumeEngineWrite(t))return;let n=(0,L.normalizePath)(t);[this.app.vault.configDir,".mdbase",".trash",".git"].some(s=>n===s||n.startsWith(`${s}/`))||(this.sync.observeLocalChange(),this.syncScheduler?.noteLocalChange())}async validateFileAndStore(t,n,i=()=>!0){let s=await this.requireConfigAndTypes({background:n!=="manual"});if(!i())return[];if(!s)return n!=="manual"&&this.clearFileIssues(t.path),[];let o=this.validation.revision,a=await Sc(this.app.vault,t,s.config,s.types);return!i()||o!==this.validation.revision||(this.validation.markChecked(t.path),this.setFileIssues(t.path,a),n==="save"&&this.settings.showNoticeOnSave&&a.length>0&&new L.Notice(`mdbase: ${a.length} issue${a.length===1?"":"s"} in ${t.basename}`)),a}async runCollectionValidation(t){if(this.validationAbort)return;let n=await this.requireConfigAndTypes({background:!1});if(!n||this.validationAbort)return;let i=new AbortController;this.validationAbort=i,this.validation.cancelled=!1;let s=this.validation.revision,o=new Map;try{let a=await Rp(this.app.vault,n.config,n.types,{signal:i.signal,onProgress:c=>{if(this.validation.progress=c,c.completed===0)for(let l of this.app.workspace.getLeavesOfType(Or))l.view.refreshValidationControls();else if(c.completed%25===0||c.phase==="uniqueness")for(let l of this.app.workspace.getLeavesOfType(Or))l.view.updateValidationProgress()},onFile:(c,l)=>{s===this.validation.revision&&(this.validation.markChecked(c.path),o.set(c.path,l),l.length?this.issueMap.set(c.path,l):this.issueMap.delete(c.path),this.sortedIssuesCache=null)}});if(s!==this.validation.revision){new L.Notice("Files changed during validation. Validate again for a complete result.");return}o.clear();for(let c of a)o.set(c.path,[...o.get(c.path)??[],c]);this.issueMap=o,this.validation.lastCompletedAt=new Date().toISOString(),this.validation.completedRevision=s,t&&(new L.Notice(a.length?`Collection validation: ${a.length} issues`:"Collection validation passed with no issues."),a.length&&await this.openIssuesView())}catch(a){if(this.validation.cancelled=!0,s===this.validation.revision)for(let[c,l]of o)l.length?this.issueMap.set(c,l):this.issueMap.delete(c);new L.Notice(i.signal.aborted?"Validation stopped. Results are incomplete.":`Validation could not finish: ${String(a)}. Results are incomplete.`)}finally{this.validation.progress=null,this.validationAbort=null,this.sortedIssuesCache=null;for(let a of this.app.workspace.getLeavesOfType(Or))a.view.refreshValidationControls();this.refreshIssueViews()}}async ensureFolderExists(t){let n=(0,L.normalizePath)(t).replace(/\/+$/,"");if(!n)return;let i=n.split("/"),s="";for(let o of i)s=s?`${s}/${o}`:o,await this.app.vault.adapter.exists(s)||await this.app.vault.createFolder(s)}async writeTypeDefinition(t,n,i,s){let o=n.name.trim();if(!o)throw new Error("Type name is required.");if(!t.spec_version.startsWith("0.3.")||n.specProfile!=="v0.3")throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let a=Fn(n),c=n.body.trim()||`# ${o} Type definition for ${o}.`,l=`${mt(a,c)} -`,u=(0,L.normalizePath)(t.settings.types_folder),d=(0,L.normalizePath)(`${u}/${o}.md`);if(!i){if(await this.ensureFolderExists(u),await this.app.vault.adapter.exists(d))throw new Error(`Type already exists: ${d}`);let v=await this.app.vault.create(d,l);return this.invalidateSchemaCache(),v}let f=i.path,p=await this.app.vault.cachedRead(i);if(s&&Jm(p)!==s)throw new Error(`The source changed after this draft was opened: ${f}. Reopen the type and review both versions before saving.`);let m=i.path.lastIndexOf("/"),h=m>=0?i.path.slice(0,m):"",g=(0,L.normalizePath)(`${h?`${h}/`:""}${o}.md`)||d;if(g!==i.path&&await this.app.vault.adapter.exists(g))throw new Error(`Cannot rename type file to ${g}; file already exists.`);let b=!1;try{g!==i.path&&(await this.app.fileManager.renameFile(i,g),b=!0);let v=this.app.vault.getAbstractFileByPath(g);if(!(v instanceof L.TFile))throw new Error(`Unable to access updated type file: ${g}`);return await this.app.vault.modify(v,l),this.invalidateSchemaCache(),v}catch(v){try{let S=this.app.vault.getAbstractFileByPath(b?g:f);S instanceof L.TFile&&(await this.app.vault.modify(S,p),b&&await this.app.fileManager.renameFile(S,f))}catch(S){throw new Error(`Saving the type failed and automatic recovery also failed. Review '${f}' and '${g}'. ${v instanceof Error?v.message:String(v)}; recovery: ${S instanceof Error?S.message:String(S)}`)}throw v}}}; +`,u=(0,L.normalizePath)(t.settings.types_folder),d=(0,L.normalizePath)(`${u}/${o}.md`);if(!i){if(await this.ensureFolderExists(u),await this.app.vault.adapter.exists(d))throw new Error(`Type already exists: ${d}`);let v=await this.app.vault.create(d,l);return this.invalidateSchemaCache(),v}let f=i.path,p=await this.app.vault.cachedRead(i);if(s&&Qm(p)!==s)throw new Error(`The source changed after this draft was opened: ${f}. Reopen the type and review both versions before saving.`);let h=i.path.lastIndexOf("/"),m=h>=0?i.path.slice(0,h):"",g=(0,L.normalizePath)(`${m?`${m}/`:""}${o}.md`)||d;if(g!==i.path&&await this.app.vault.adapter.exists(g))throw new Error(`Cannot rename type file to ${g}; file already exists.`);let b=!1;try{g!==i.path&&(await this.app.fileManager.renameFile(i,g),b=!0);let v=this.app.vault.getAbstractFileByPath(g);if(!(v instanceof L.TFile))throw new Error(`Unable to access updated type file: ${g}`);return await this.app.vault.modify(v,l),this.invalidateSchemaCache(),v}catch(v){try{let S=this.app.vault.getAbstractFileByPath(b?g:f);S instanceof L.TFile&&(await this.app.vault.modify(S,p),b&&await this.app.fileManager.renameFile(S,f))}catch(S){throw new Error(`Saving the type failed and automatic recovery also failed. Review '${f}' and '${g}'. ${v instanceof Error?v.message:String(v)}; recovery: ${S instanceof Error?S.message:String(S)}`)}throw v}}}; diff --git a/main.ts b/main.ts index beaaeed..98cb880 100644 --- a/main.ts +++ b/main.ts @@ -36,7 +36,7 @@ import { import type { StoredTypeDraft, TypeEditorModel } from "./src/typeEditorTypes"; import { ConnectSyncController, - normalizeSelectiveSync, + normalizeMirrorProfile, type MirrorProfile, } from "./src/connectSync"; import { @@ -93,24 +93,6 @@ const DEFAULT_SETTINGS: MdbasePluginSettings = { /** Vault-scoped device storage key; Obsidian keeps it out of the vault and out of plugin data. */ const DEVICE_ID_KEY = "mdbase-sync-device-id"; -function isMirrorProfile(value: unknown): value is MirrorProfile { - if (!value || typeof value !== "object" || Array.isArray(value)) return false; - const profile = value as Partial; - return profile.version === 1 - && typeof profile.syncUrl === "string" - && typeof profile.controlUrl === "string" - && typeof profile.collectionId === "string" - && typeof profile.replicaId === "string" - && (profile.mode === "read_only" || profile.mode === "read_write") - && typeof profile.name === "string" - && typeof profile.enrollmentId === "string" - && typeof profile.accessTokenExpiresAt === "string" - && (profile.selectiveSync === undefined || ( - Array.isArray(profile.selectiveSync.file_classes) - && Array.isArray(profile.selectiveSync.excluded_folders) - )); -} - function escapeRegExp(value: string): string { return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } @@ -356,16 +338,7 @@ export default class MdbasePlugin extends Plugin { this.settings.autoSync = true; this.settings.syncSettingsVersion = 2; } - if (!isMirrorProfile(this.settings.mirrorProfile)) { - this.settings.mirrorProfile = null; - } else { - try { - this.settings.mirrorProfile.selectiveSync = normalizeSelectiveSync(this.settings.mirrorProfile.selectiveSync); - } catch { - // Fail closed for corrupted legacy data without discarding enrollment. - this.settings.mirrorProfile.selectiveSync = normalizeSelectiveSync(); - } - } + this.settings.mirrorProfile = normalizeMirrorProfile(this.settings.mirrorProfile); if (!this.settings.typeDrafts || typeof this.settings.typeDrafts !== "object" || Array.isArray(this.settings.typeDrafts)) { this.settings.typeDrafts = {}; } @@ -1071,7 +1044,7 @@ export default class MdbasePlugin extends Plugin { * echoes. The scheduler syncs once the burst of edits settles. */ private observeLocalMirrorChange(path: string): void { - if (!this.getMirrorProfile() || this.connectSync.isEngineWrite(path)) return; + if (!this.getMirrorProfile() || this.connectSync.consumeEngineWrite(path)) return; const normalized = normalizePath(path); const reservedFolders = [this.app.vault.configDir, ".mdbase", ".trash", ".git"]; if (reservedFolders.some((folder) => normalized === folder || normalized.startsWith(`${folder}/`))) return; diff --git a/patches/@mdbase-dev+connect-sync+0.1.0-beta.120.patch b/patches/@mdbase-dev+connect-sync+0.1.0-beta.120.patch index dd598de..5ba24d6 100644 --- a/patches/@mdbase-dev+connect-sync+0.1.0-beta.120.patch +++ b/patches/@mdbase-dev+connect-sync+0.1.0-beta.120.patch @@ -1,8 +1,8 @@ diff --git a/node_modules/@mdbase-dev/connect-sync/dist/directory-mirror.d.ts b/node_modules/@mdbase-dev/connect-sync/dist/directory-mirror.d.ts -index dd5830c..e774a50 100644 +index dd5830c..868ba93 100644 --- a/node_modules/@mdbase-dev/connect-sync/dist/directory-mirror.d.ts +++ b/node_modules/@mdbase-dev/connect-sync/dist/directory-mirror.d.ts -@@ -34,6 +34,11 @@ export declare class DirectoryMirror; checkpointStatus(): Promise; private checkpointStatusUnlocked; + authorityPromotionManifest(): Promise; + previewInitialization(): Promise; +- resolveConflict(identity: string, decisionId: string, resolution: "local" | "remote"): Promise; ++ /** An optional merged record is written conditionally before the durable conflict is cleared. */ ++ resolveConflict(identity: string, decisionId: string, resolution: "local" | "remote", mergedDocument?: string): Promise; + private resolveConflictUnlocked; + private installRemoteRecord; + private installRemoteFile; diff --git a/node_modules/@mdbase-dev/connect-sync/dist/directory-mirror.js b/node_modules/@mdbase-dev/connect-sync/dist/directory-mirror.js -index a9018ff..80cc6e3 100644 +index a9018ff..ba68459 100644 --- a/node_modules/@mdbase-dev/connect-sync/dist/directory-mirror.js +++ b/node_modules/@mdbase-dev/connect-sync/dist/directory-mirror.js -@@ -68,7 +68,7 @@ export class DirectoryMirror { +@@ -8,6 +8,7 @@ import { checkpointMirrorStatus, mirrorStatusFromPlan } from "./mirror-status.js + import { PlanOnlyMirrorInspector } from "./sync-inspector.js"; + import { PlanOnlySyncExecutor } from "./sync-executor.js"; + import { PlanRevalidator } from "./sync-revalidator.js"; ++import { runtimeDocumentRevision } from "./mirror-format.js"; + import { abandonStaleBatch, prepareSyncBatch } from "./sync-journal.js"; + import { advanceEmptySyncCheckpoint, advanceSyncCheckpoint } from "./sync-checkpoint.js"; + import { loadMirrorSnapshot } from "./sync-snapshot-loader.js"; +@@ -68,7 +69,7 @@ export class DirectoryMirror { } if (state?.last_completed_plan === plan.fingerprint) { const checkpoint = checkpointMirrorStatus(state, this.mode); @@ -27,7 +43,7 @@ index a9018ff..80cc6e3 100644 } const inspection = await this.inspectDetailed(state); if (inspection.plan.fingerprint !== plan.fingerprint) { -@@ -126,6 +126,9 @@ export class DirectoryMirror { +@@ -126,6 +127,9 @@ export class DirectoryMirror { }) }).execute(state, signal); if (result.status !== "effects_complete") { @@ -37,7 +53,7 @@ index a9018ff..80cc6e3 100644 const checkpoint = checkpointMirrorStatus(state, this.mode); return mirrorApplyResult(result.status === "blocked" ? "failed" : result.status, batch.plan, checkpoint, result.completed, result.failure); } -@@ -135,7 +138,8 @@ export class DirectoryMirror { +@@ -135,7 +139,8 @@ export class DirectoryMirror { const checkpoint = checkpointMirrorStatus(state, this.mode); const attention = checkpoint.conflicts.length > 0 || checkpoint.local_issues.length > 0 @@ -47,7 +63,7 @@ index a9018ff..80cc6e3 100644 return mirrorApplyResult(attention ? "attention" : "applied", plan, checkpoint, result.completed); } inspectDetailed(state) { -@@ -196,13 +200,21 @@ export class DirectoryMirror { +@@ -196,13 +201,21 @@ export class DirectoryMirror { planned_conflicts: {} }; } @@ -75,6 +91,90 @@ index a9018ff..80cc6e3 100644 } async checkpointStatus() { return this.lease.runExclusive(() => this.checkpointStatusUnlocked()); +@@ -263,10 +276,10 @@ export class DirectoryMirror { + .map((issue) => ({ code: "invalid_frontmatter", message: issue.message, path: issue.path })) + }; + } +- async resolveConflict(identity, decisionId, resolution) { +- await this.lease.runExclusive(() => this.resolveConflictUnlocked(identity, decisionId, resolution)); ++ async resolveConflict(identity, decisionId, resolution, mergedDocument) { ++ await this.lease.runExclusive(() => this.resolveConflictUnlocked(identity, decisionId, resolution, mergedDocument)); + } +- async resolveConflictUnlocked(identity, decisionId, resolution) { ++ async resolveConflictUnlocked(identity, decisionId, resolution, mergedDocument) { + if (this.mode !== "read_write") { + throw new SyncError("mirror_read_only", "Receive-only mirrors have no writable conflicts."); + } +@@ -280,12 +293,9 @@ export class DirectoryMirror { + } + if ((planned.decision_id ?? "") !== decisionId) + throw staleConflict(); +- const revalidator = new PlanRevalidator(this.fileSystem, this.runtime); +- if (planned.local.state === "exact") { +- await revalidator.validateExpected(planned.local); +- } +- else if (planned.remote.state === "exact") { +- await revalidator.validateExpectedAt(planned.remote.object.path, planned.local); ++ if (mergedDocument !== undefined && (resolution !== "local" ++ || planned.entity !== "record" || planned.local.state !== "exact")) { ++ throw new SyncError("invalid_conflict_resolution", "A merged document requires an exact local record conflict."); + } + const snapshot = await loadMirrorSnapshot(this.replicaId, this.transport, this.mode, this.selectiveSync, this.runtime); + const currentRecord = planned.entity === "record" +@@ -299,6 +309,15 @@ export class DirectoryMirror { + : fileStateMatches(planned.remote, currentFile); + if (!remoteMatches) + throw staleConflict(); ++ // Snapshot loading can take arbitrarily long. Fence the decision's local ++ // bytes after that network wait, not before it. ++ const revalidator = new PlanRevalidator(this.fileSystem, this.runtime); ++ if (planned.local.state === "exact") { ++ await revalidator.validateExpected(planned.local); ++ } ++ else if (planned.remote.state === "exact") { ++ await revalidator.validateExpectedAt(planned.remote.object.path, planned.local); ++ } + if (resolution === "remote") { + if (planned.entity === "record") { + await this.installRemoteRecord(state, identity, currentRecord); +@@ -307,6 +326,17 @@ export class DirectoryMirror { + await this.installRemoteFile(state, identity, currentFile); + } + } ++ if (mergedDocument !== undefined) { ++ const path = planned.local.object.path; ++ const expected = await this.fileSystem.read(path); ++ if (expected === null || runtimeDocumentRevision(expected, this.runtime) !== planned.local.object.payload_revision) { ++ throw staleConflict(); ++ } ++ // Persist both halves in the merged file before clearing the durable ++ // conflict. A crash or failed write must never authorize an upload ++ // of the original, unmerged local document over the hosted edit. ++ await this.fileSystem.write(path, mergedDocument, expected); ++ } + delete state.planned_conflicts?.[identity]; + if (resolution === "remote") + delete state.local_bindings?.[identity]; +@@ -314,14 +344,12 @@ export class DirectoryMirror { + } + async installRemoteRecord(state, identity, current) { + if (current) { +- const conflict = state.planned_conflicts?.[identity]; +- const acceptedDocument = await this.fileSystem.read(current.path); +- const pathBelongsToIdentity = state.records[identity]?.path === current.path +- || (conflict?.local.state === "exact" && conflict.local.object.path === current.path); ++ // Accept only the local version named by the conflict decision. Never ++ // authorize whatever bytes happen to be present after an async reread. ++ const local = state.planned_conflicts?.[identity]?.local; + await this.materializer.put(state, current, { +- inspectionPreflighted: false, +- ...(pathBelongsToIdentity && acceptedDocument !== null +- ? { acceptedHash: this.runtime.digest(acceptedDocument) } ++ ...(local?.state === "exact" && local.object.path === current.path ++ ? { acceptedHash: local.object.payload_revision.replace(/^sha256:/u, "") } + : {}) + }); + return; diff --git a/node_modules/@mdbase-dev/connect-sync/dist/mirror-materializer.js b/node_modules/@mdbase-dev/connect-sync/dist/mirror-materializer.js index 6936f79..64b0670 100644 --- a/node_modules/@mdbase-dev/connect-sync/dist/mirror-materializer.js diff --git a/patches/README.md b/patches/README.md index 0c2b254..d4824ce 100644 --- a/patches/README.md +++ b/patches/README.md @@ -48,6 +48,22 @@ addition is the optional `ancestor_document` below): - `sync-executor.js`: the special receive-only malformed-frontmatter repair allowance applies only to that explicitly identified target, never every download in a partial plan. Conditional writes remain enforced. +- `directory-mirror.js`: a hosted conflict resolution accepts only the inspected + local document revision, not whatever bytes happen to exist after loading the + authority snapshot. A user edit or recreated file during that await leaves + the decision stale instead of silently overwriting bytes absent from the copy. + Ported exactly from mdbase-connect `56dabd74` (local revalidation after the + snapshot, decision-bound `acceptedHash`). Integration regression: + `test/connectSync.settlement.test.ts`. +- `directory-mirror.js` / `.d.ts`: `resolveConflict(identity, decisionId, "local", + mergedDocument?)` optionally persists a merged record with the adapter's + conditional write before clearing its durable conflict. Without this ordering, + a hard restart between clearing and the plugin's write could upload unmerged + local text over the hosted edit. Only an exact local record accepts a merged + document; a failed write leaves the conflict intact. No protocol or persisted + state change. This additional SDK API needs an upstream source port before + upgrading/removing the patch. Regressions simulate restart at the write + boundary, disk-full failure, and a user edit during the atomic write. - `directory-mirror.js`: partial completion reports attention, not failure or falsely complete synchronization, while preserving its unresolved diagnostics. - `directory-mirror.js`: release stale batches at the SDK's existing safe journal diff --git a/scripts/test-sync-layout.cjs b/scripts/test-sync-layout.cjs new file mode 100644 index 0000000..780e923 --- /dev/null +++ b/scripts/test-sync-layout.cjs @@ -0,0 +1,96 @@ +const fs = require('fs'); +// Opt-in visual acceptance in a marked, disposable Obsidian vault. No live Connect calls. +const path = require('path'); +const cdpUrl = process.env.MDBASE_UX_CDP_URL; +const vault = process.env.MDBASE_UX_VAULT; +const shots = process.env.MDBASE_UX_SHOTS; +if (!/^http:\/\/127\.0\.0\.1:\d+$/.test(cdpUrl || '') || !vault || !shots + || !fs.existsSync(path.join(vault, '.obsidian', 'mdbase-ux-disposable'))) { + throw Error('Set MDBASE_UX_CDP_URL, MDBASE_UX_VAULT and MDBASE_UX_SHOTS for a marked disposable vault; see docs/sync-ux-acceptance.md'); +} +const { chromium } = require(process.env.MDBASE_UX_PLAYWRIGHT || '@playwright/test'); +const prefix = process.argv[2] || 'sync-layout'; +fs.mkdirSync(shots, {recursive:true}); +(async () => { + const browser = await chromium.connectOverCDP(cdpUrl); + const page = browser.contexts()[0].pages().find(p => p.url().startsWith('app://')); + if (await page.evaluate(() => app.vault.adapter.basePath) !== vault) throw Error('Wrong disposable vault'); + await page.evaluate(async()=>{ + await app.plugins.disablePlugin('mdbase-obsidian'); await app.plugins.enablePlugin('mdbase-obsidian'); + const p=app.plugins.plugins['mdbase-obsidian']; + p.syncScheduler.stop();p.settings.autoSync=false;p.settings.mirrorProfile=null; + p.connectSync.status=async()=>p.sync.state.status; + p.sync.historyRuns=()=>window.fixtureRuns||[]; + window.uxView=await p.openWorkspace('sync'); + app.workspace.leftSplit.collapse();app.workspace.rightSplit.collapse(); + window.open=()=>null; + }); + const states=['healthy','offline','auth','copied','paused','internal','progress','first-sync','deletions','rebuild','conflict','history','enrollment','upload']; + const results=[]; + for(const state of states) { + await page.evaluate(state=>{ + const p=app.plugins.plugins['mdbase-obsidian'], view=uxView; + const longPath='Projects/ExtremelyLongFilenameWithoutSpacesOrBreaks_ABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789_ABCDEFGHIJKLMNOPQRSTUVWXYZ.md'; + p.settings.mirrorProfile={name:'Project notes',collectionId:'ux-fixture',replicaId:'ux-device',mode:'read_write',controlUrl:'https://connect.example',syncUrl:'https://connect.example',enrollmentId:'ux-fixture',accessTokenExpiresAt:'2099-01-01T00:00:00Z',selectiveSync:{file_classes:[],excluded_folders:[]}}; + p.sync.reset();view.busy=false;view.message='';view.schema=null;view.destination='sync'; + view.sync.enrollmentVerification='';view.sync.enrollmentAbort=null;view.sync.conflictComparisons.clear(); + view.sync.transferQuery='';view.sync.transferFilter='all';view.disclosures.clear();window.fixtureRuns=[]; + p.sync.update({status:{state:'up_to_date',last_synced_at:new Date().toISOString(),conflicts:[],local_issues:[],pending:0}}); + const problems={ + offline:{kind:'offline',title:"Can't reach mdbase Connect",message:'Your changes are saved on this device and sync automatically when the connection returns.',action:'retry',actionLabel:'Retry now'}, + auth:{kind:'auth',title:'Connect approval is required again',message:'Your local files and mirror checkpoint are safe. Approve this vault again to restore access.',action:'reauthorize',actionLabel:'Sign in again'}, + copied:{kind:'device',title:'Set up sync on this device',message:"This vault's sync settings came from another device or another copy of the vault. Approve this copy to give it its own connection. Your files stay as they are.",action:'reauthorize',actionLabel:'Set up this device'}, + internal:{kind:'internal',title:'Sync stopped unexpectedly',message:'An unexpected error stopped synchronization. Your files are safe. Copy diagnostics if it happens again.',action:'retry',actionLabel:'Try again'} + }; + if(problems[state])p.sync.update({problem:{code:'fixture',...problems[state]},retryAt:state==='offline'?Date.now()+40000:null}); + if(state==='paused')p.sync.update({paused:true}); + if(state==='progress')p.sync.update({fileProgress:{direction:'upload',path:longPath,transferredBytes:32768,totalBytes:8388608}}); + if(['first-sync','deletions','rebuild'].includes(state)) { + const count=state==='deletions'?25:1; + const command=state==='first-sync'?'put_remote':state==='deletions'?'delete_remote':'write_local'; + const action=command.startsWith('delete')?'delete':'create'; + const direction=command.endsWith('remote')?'upload':'download'; + const entries=Array.from({length:count},(_,i)=>({kind:'document',path:count>1?`Archive/Note ${i+1}.md`:longPath,direction,action,detail:action==='delete'?'Delete from Connect.':direction==='download'?'Download from Connect.':'Upload to Connect.'})); + const actions=entries.map(entry=>({command,target:{path:entry.path}})); + const kind=state==='first-sync'?'initial':state==='rebuild'?'rebuild':'incremental'; + p.sync.update({preview:{phase:kind,entries,plan:{kind,actions,issues:[],summary:{blocking_issues:0}},collisions:[],local_issues:[]}}); + } + if(state==='conflict') { + p.sync.update({status:{state:'attention',conflicts:[{entity:'record',object_id:'record',decision_id:'decision',path:longPath,message:'Both versions changed. Choose which version to sync.'}],local_issues:[]}}); + view.sync.conflictComparisons.set('record:decision',{entity:'record',objectId:'record',decisionId:'decision',local:{state:'exact',document:'Line from this device'},remote:{state:'exact',document:'Line from another device'}}); + } + if(state==='history') { + const at=new Date().toISOString(); + window.fixtureRuns=[{id:'fixture-conflict',collectionId:'ux-fixture',startedAt:at,finishedAt:at,outcome:'event',files:[],summary:'Kept both versions of '+longPath.split('/').pop(),message:"This device's version was saved as "+longPath.replace('.md',' (local conflict copy).md'),path:longPath,tone:'attention',needsAcknowledgement:true}]; + } + if(['enrollment','upload'].includes(state)) { + p.settings.mirrorProfile=null; + if(state==='upload')view.schema={config:{spec_version:'0.3.0'},types:new Map(),contracts:new Map()}; + } + view.render(); + },state); + for(const width of [1100,390])for(const theme of ['theme-dark','theme-light']) { + await page.setViewportSize({width,height:900}); + await page.evaluate(theme=>{document.body.classList.remove('theme-dark','theme-light');document.body.classList.add(theme)},theme); + const checks=await page.locator('.mdbase-sync-document').evaluate(el=>{ + const content=el.closest('.mdbase-workspace-content'); + const buttons=[...el.querySelectorAll('.mod-cta, .mdbase-activity-row > button')].map(b=>({text:b.textContent,height:b.getBoundingClientRect().height})); + return {paneWidth:content.clientWidth,headingWidth:el.querySelector('.mdbase-sync-heading')?.getBoundingClientRect().width,scrollWidth:content.scrollWidth,overflow:content.scrollWidth>content.clientWidth+1,buttons}; + }); + const box=await page.locator('.mdbase-workspace').boundingBox(); + const cdp=await page.context().newCDPSession(page); + const capture=await cdp.send('Page.captureScreenshot',{format:'png',captureBeyondViewport:true,clip:{...box,scale:1}}); + await cdp.detach();fs.writeFileSync(`${shots}/${prefix}-${state}-${width}-${theme}.png`,Buffer.from(capture.data,'base64')); + const failures=[]; + if(checks.overflow)failures.push('Horizontal overflow'); + if(width===390&&checks.headingWidth!=null&&checks.headingWidthb.height<43.5))failures.push('Primary/dismiss target below 44px'); + results.push({state,width,theme,...checks,failures}); + if(failures.length)console.log(JSON.stringify(results.at(-1))); + } + } + fs.writeFileSync(`${shots}/${prefix}-checks.json`,JSON.stringify(results,null,2)+'\n'); + console.log(JSON.stringify({states:states.length,checks:results.length,failed:results.filter(r=>r.failures.length).length})); + await browser.close(); + process.exitCode=results.some(r=>r.failures.length)?1:0; +})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/src/connectSync.ts b/src/connectSync.ts index 78fd652..ce831fc 100644 --- a/src/connectSync.ts +++ b/src/connectSync.ts @@ -111,6 +111,29 @@ export interface MirrorProfile { deviceId?: string; } +/** Validate stored connection identity, then fail closed on a corrupt sync policy. */ +export function normalizeMirrorProfile(value: unknown): MirrorProfile | null { + if (!isRecord(value)) return null; + const profile = value as unknown as MirrorProfile; + if (!(profile.version === 1 + && typeof profile.syncUrl === "string" + && typeof profile.controlUrl === "string" + && typeof profile.collectionId === "string" + && typeof profile.replicaId === "string" + && (profile.mode === "read_only" || profile.mode === "read_write") + && typeof profile.name === "string" + && typeof profile.enrollmentId === "string" + && typeof profile.accessTokenExpiresAt === "string" + && (profile.deviceId === undefined || typeof profile.deviceId === "string"))) return null; + let selectiveSync: SelectiveSyncPolicy; + try { + selectiveSync = normalizeSelectiveSync(profile.selectiveSync); + } catch { + selectiveSync = normalizeSelectiveSync(); + } + return { ...profile, selectiveSync }; +} + export interface EnrollMirrorInput { controlUrl: string; mirrorName: string; @@ -955,14 +978,20 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { const path = safeMirrorPath(this.vault, input); // The SDK supplies its inspected text. Standalone callers still get a // conditional write rather than a read/modify race inside this adapter. - // `undefined` after reading means the bytes are not text (a receive-only - // repair replacing invalid UTF-8): there is no text to compare against. - let before: string | null | undefined = expected; + const stale = () => new SyncError("sync_plan_stale", `${path} changed before it could be written. Review sync again.`); + let before = expected; if (before === undefined) { const observed = await this.readText(path); - before = typeof observed === "string" || observed === null ? observed : undefined; + if (typeof observed === "string" || observed === null) before = observed; + else { + // Receive-only repair can replace invalid UTF-8, but still uses the + // atomic text transform. Compare the same decoded view Vault.process + // will see, after proving these are still the inspected invalid bytes. + const bytes = await this.vault.adapter.readBinary(path); + if ((await binaryInfo(bytes)).content_digest !== observed.revision) throw stale(); + before = new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes); + } } - const stale = () => new SyncError("sync_plan_stale", `${path} changed before it could be written. Review sync again.`); const slash = path.lastIndexOf("/"); if (slash >= 0) await ensureFolder(this.vault, path.slice(0, slash)); const existing = this.vault.getAbstractFileByPath(path); @@ -970,19 +999,19 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { throw new SyncError("mirror_path_collision", `A folder blocks the mirror file ${path}.`); } this.assertActive(); - this.observeWrite(path); - if (existing instanceof TFile && before === undefined) { - await this.vault.modify(existing, value); - } else if (existing instanceof TFile) { + if (existing instanceof TFile) { await this.vault.process(existing, (current) => { this.assertActive(); + if (existing.path !== path || this.vault.getAbstractFileByPath(path) !== existing) throw stale(); if (current !== before && current !== value) throw stale(); + this.observeWrite(path); return value; }); } else { if (before !== null) throw stale(); // Vault.create refuses an occupied destination, including one created // after the existence check. Never fall back to overwriting it. + this.observeWrite(path); await this.vault.create(path, value); } } @@ -1248,7 +1277,8 @@ export class IndexedDbMirrorBlobStore implements MirrorBlobStore { private open(): Promise { if (typeof indexedDB === "undefined") throw new SyncError("storage_unavailable", "IndexedDB is required for binary file sync."); - this.database ??= new Promise((resolve, reject) => { + if (this.database) return this.database; + const opening = new Promise((resolve, reject) => { const request = indexedDB.open(BLOB_DATABASE, 1); request.onupgradeneeded = () => { if (!request.result.objectStoreNames.contains(BLOB_MANIFEST_STORE)) request.result.createObjectStore(BLOB_MANIFEST_STORE); @@ -1257,7 +1287,11 @@ export class IndexedDbMirrorBlobStore implements MirrorBlobStore { request.onerror = () => reject(indexedDbError(request.error, "binary store open")); request.onsuccess = () => resolve(request.result); }); - return this.database; + this.database = opening; + void opening.catch(() => { + if (this.database === opening) this.database = null; + }); + return opening; } } @@ -1306,7 +1340,8 @@ export class IndexedDbMirrorStateStore implements MirrorStateStore { if (typeof indexedDB === "undefined") { throw new SyncError("storage_unavailable", "IndexedDB is required for persistent mirror state."); } - this.database ??= new Promise((resolve, reject) => { + if (this.database) return this.database; + const opening = new Promise((resolve, reject) => { const request = indexedDB.open(STATE_DATABASE, 1); request.onupgradeneeded = () => { if (!request.result.objectStoreNames.contains(STATE_STORE)) { @@ -1316,7 +1351,11 @@ export class IndexedDbMirrorStateStore implements MirrorStateStore { request.onerror = () => reject(indexedDbError(request.error, "mirror state store open")); request.onsuccess = () => resolve(request.result); }); - return this.database; + this.database = opening; + void opening.catch(() => { + if (this.database === opening) this.database = null; + }); + return opening; } } @@ -1937,7 +1976,15 @@ export class ConnectSyncController { * conflict that changes again while this runs is left for the next sync. */ async autoResolveConflicts(): Promise { - const status = await this.status(); + // The decision, copy and merged write form one controller operation. Sync + // must not run between clearing a conflict and installing its merged text. + return this.withMirrorOperation(() => this.autoResolveConflictsActive()); + } + + private async autoResolveConflictsActive(): Promise { + if (!this.settingsHost.getMirrorProfile()) return []; + const mirror = await this.createMirror(); + const status = await mirror.status(); if (!status?.conflicts.length || status.recovery_required) return []; const profile = this.requireProfile(); const state = await this.stateStoreFor(profile).read(); @@ -1951,7 +1998,7 @@ export class ConnectSyncController { const planned = state.planned_conflicts?.[conflict.object_id]; if (!planned) continue; try { - resolutions.push(await this.autoResolve(conflict, planned, remoteRecords.get(conflict.object_id))); + resolutions.push(await this.autoResolve(mirror, conflict, planned, remoteRecords.get(conflict.object_id))); } catch (error) { if (error instanceof SyncError && ["conflict_decision_stale", "sync_plan_stale"].includes(error.code)) continue; resolutions.push({ @@ -1965,6 +2012,7 @@ export class ConnectSyncController { } private async autoResolve( + mirror: DirectoryMirror, conflict: MirrorStatus["conflicts"][number], planned: NonNullable[string], remote: RemoteRecord | undefined, @@ -1977,11 +2025,11 @@ export class ConnectSyncController { // it under another name would only be refused again; a person must decide. if (planned.conflict_kind === "rejected") return { path, outcome: "unresolved", reason: conflict.message }; if (localPath === null) { - await this.resolveConflict(id, decision, "remote"); + await mirror.resolveConflict(id, decision, "remote"); return { path, outcome: remotePath ? "restored" : "took_hosted" }; } if (remotePath === null) { - await this.resolveConflict(id, decision, "local"); + await mirror.resolveConflict(id, decision, "local"); return { path, outcome: "kept_local" }; } if ( @@ -1999,21 +2047,16 @@ export class ConnectSyncController { if (base !== undefined && local !== null) { const merged = mergeDocuments(base, local, remote.document, validYamlMapping); if (merged.clean) { - await this.resolveConflict(id, decision, "local"); - try { - await this.fileSystem.write(localPath, merged.text, local); - } catch (error) { - // The note changed between the check and the write. Keep the hosted - // text beside it so the merge's other half is never lost. - const copy = await this.writeConflictCopy(localPath, remote.document, "hosted conflict copy"); - return { path, outcome: "kept_both", copyPath: copy, reason: error instanceof Error ? error.message : String(error) }; - } + // The SDK writes conditionally before clearing its durable decision; + // interrupted/failed merges remain conflicts instead of authorizing + // an unmerged local upload over the hosted half on the next run. + await mirror.resolveConflict(id, decision, "local", merged.text); return { path, outcome: "merged" }; } } } const copyPath = await this.preserveConflictCopy(localPath); - await this.resolveConflict(id, decision, "remote"); + await mirror.resolveConflict(id, decision, "remote"); return { path, outcome: "kept_both", copyPath }; } @@ -2035,11 +2078,6 @@ export class ConnectSyncController { return found; } - private async writeConflictCopy(pathInput: string, document: string, label: string): Promise { - const path = safeMirrorPath(this.app.vault, pathInput); - return this.createConflictCopy(path, new TextEncoder().encode(document).buffer, label); - } - private async createConflictCopy(path: string, document: ArrayBuffer, label: string): Promise { const slash = path.lastIndexOf("/"); const dot = path.lastIndexOf("."); @@ -2172,9 +2210,13 @@ export class ConnectSyncController { this.engineWrites.set(normalizePath(path), now); } - isEngineWrite(path: string): boolean { - const at = this.engineWrites.get(normalizePath(path)); - return at !== undefined && Date.now() - at <= ENGINE_WRITE_ECHO_MS; + /** Suppress one echo, not every user edit arriving soon after that write. */ + consumeEngineWrite(path: string): boolean { + const key = normalizePath(path); + const at = this.engineWrites.get(key); + this.engineWrites.delete(key); + const elapsed = at === undefined ? -1 : Date.now() - at; + return elapsed >= 0 && elapsed <= ENGINE_WRITE_ECHO_MS; } isSyncing(): boolean { diff --git a/src/mdbaseCore.ts b/src/mdbaseCore.ts index 92d9123..20cba35 100644 --- a/src/mdbaseCore.ts +++ b/src/mdbaseCore.ts @@ -682,7 +682,15 @@ export interface CollectionRecord { /** Parsed frontmatter for every record the collection validates. Unparseable notes are skipped. */ export async function readCollectionRecords(vault: Vault, config: MdbaseConfig): Promise { const records: CollectionRecord[] = []; + let yieldedAt = performance.now(); for (const file of vault.getMarkdownFiles()) { + // cachedRead can resolve in a microtask: awaiting it alone does not let the + // editor paint or process input. Yield by time, not once per tiny file. + if (performance.now() - yieldedAt >= 8) { + // eslint-disable-next-line obsidianmd/prefer-window-timers -- Host-independent cooperative yield, like collection validation below. + await new Promise(resolve => setTimeout(resolve, 0)); + yieldedAt = performance.now(); + } if (isExcluded(file.path, config)) continue; const parsed = parseFrontmatter(await vault.cachedRead(file)); if (parsed.error) continue; diff --git a/src/settingsTab.ts b/src/settingsTab.ts index ae2b01a..98a7d78 100644 --- a/src/settingsTab.ts +++ b/src/settingsTab.ts @@ -82,8 +82,13 @@ export class MdbaseSettingTab extends PluginSettingTab { .setDesc(`${profile.mode === "read_write" ? "Read and write" : "Read only"} · ${new URL(profile.controlUrl).host}`) .addButton((button) => button.setButtonText("Reconnect").onClick(async () => { button.setDisabled(true); - await plugin.openWorkspace("sync").then((view) => view.reconnectCollection()); - button.setDisabled(false); + try { + await plugin.openWorkspace("sync").then((view) => view.reconnectCollection()); + } catch (error) { + new Notice(error instanceof Error ? error.message : String(error)); + } finally { + button.setDisabled(false); + } })); new Setting(containerEl) @@ -101,9 +106,11 @@ export class MdbaseSettingTab extends PluginSettingTab { const apply = async (next: SelectiveSyncPolicy) => { try { await plugin.sync.configureSelectiveSync(next); + return true; } catch (error) { new Notice(error instanceof Error ? error.message : String(error)); this.display(); + return false; } }; for (const [value, label] of FILE_CLASSES) { @@ -127,8 +134,14 @@ export class MdbaseSettingTab extends PluginSettingTab { const exclusions = new Setting(containerEl).setName("Excluded folders").setDesc(ATTACHMENT_SCOPE_DESCRIPTION); renderFolderExclusions(this.app, exclusions.controlEl, folders, next => { folders = next; }); exclusions.addButton(button => button.setButtonText("Apply").onClick(async () => { - await apply({ ...plugin.connectSync.getSelectiveSync(), excluded_folders: folders }); - new Notice("Excluded folders updated. The next sync applies them."); + button.setDisabled(true); + try { + if (await apply({ ...plugin.connectSync.getSelectiveSync(), excluded_folders: folders })) { + new Notice("Excluded folders updated. The next sync applies them."); + } + } finally { + button.setDisabled(false); + } })); new Setting(containerEl) diff --git a/src/syncHistory.ts b/src/syncHistory.ts index 595ccdd..b46d902 100644 --- a/src/syncHistory.ts +++ b/src/syncHistory.ts @@ -244,11 +244,14 @@ export class SyncHistoryStore { ) {} async load(): Promise { - const loaded = await this.adapter.exists(this.path) - ? parseHistory(await this.adapter.read(this.path)) - : []; - this.runs = pruneRuns(loaded, this.limits); - if (this.runs.length !== loaded.length) await this.rewrite(); + await this.enqueue(async () => { + const source = await this.adapter.exists(this.path) ? await this.adapter.read(this.path) : ""; + const loaded = pruneRuns(parseHistory(source), this.limits); + const repaired = serializeRuns(loaded); + // Drop corrupt/torn lines before append can join a new entry to them. + if (source !== repaired) await this.adapter.write(this.path, repaired); + this.runs = loaded; + }); } list(collectionId?: string): SyncHistoryRun[] { @@ -256,29 +259,35 @@ export class SyncHistoryStore { } append(run: SyncHistoryRun): Promise { - const before = this.runs.length + 1; - this.runs = pruneRuns([...this.runs, run], this.limits); - const pruned = this.runs.length !== before; return this.enqueue(async () => { - if (pruned || !await this.adapter.exists(this.path)) await this.rewrite(); + const next = pruneRuns([...this.runs, run], this.limits); + const pruned = next.length !== this.runs.length + 1; + if (pruned || !await this.adapter.exists(this.path)) await this.rewrite(next); else await this.adapter.append(this.path, `${JSON.stringify(run)}\n`); + this.runs = next; }); } - /** Removes one entry, e.g. a dismissed event. */ - remove(id: string): Promise { - this.runs = this.runs.filter((run) => run.id !== id); - return this.enqueue(() => this.rewrite()); + /** Dismisses the pinned notice, retaining its evidence in ordinary history. */ + acknowledge(id: string): Promise { + return this.enqueue(async () => { + const next = this.runs.map((run) => run.id === id ? { ...run, needsAcknowledgement: false } : run); + await this.rewrite(next); + this.runs = next; + }); } /** Clears history but keeps events that still need acknowledgement. */ clear(): Promise { - this.runs = this.runs.filter((run) => run.needsAcknowledgement); - return this.enqueue(() => this.rewrite()); + return this.enqueue(async () => { + const next = this.runs.filter((run) => run.needsAcknowledgement); + await this.rewrite(next); + this.runs = next; + }); } - private rewrite(): Promise { - return this.adapter.write(this.path, this.runs.map((run) => `${JSON.stringify(run)}\n`).join("")); + private rewrite(runs: readonly SyncHistoryRun[]): Promise { + return this.adapter.write(this.path, serializeRuns(runs)); } private enqueue(operation: () => Promise): Promise { @@ -287,6 +296,10 @@ export class SyncHistoryStore { } } +function serializeRuns(runs: readonly SyncHistoryRun[]): string { + return runs.map((run) => `${JSON.stringify(run)}\n`).join(""); +} + const PAST_TENSE: Record = { create: "created", update: "updated", diff --git a/src/syncHttp.ts b/src/syncHttp.ts index ad63975..38309d7 100644 --- a/src/syncHttp.ts +++ b/src/syncHttp.ts @@ -117,7 +117,7 @@ export function reliableSend(send: HttpSend, policy: RetryPolicy = DEFAULT_RETRY */ export function platformSend(desktop: FetchStack | null = privilegedDesktopStack()): HttpSend { return desktop - ? (request) => fetchSend(request, desktop.fetch, desktop.AbortController) + ? (request) => fetchSend(request, desktop.fetch, desktop.AbortController, desktop.headers) : (request) => requestUrlSend(request); } @@ -125,6 +125,8 @@ export function platformSend(desktop: FetchStack | null = privilegedDesktopStack export interface FetchStack { fetch: typeof window.fetch; AbortController: typeof AbortController; + /** Serialize Headers in the process that owns them, without renderer callbacks. */ + headers: (headers: Headers) => Record; } /** @@ -141,8 +143,15 @@ export function privilegedDesktopStack(): FetchStack | null { }).remote; const fetch = remote?.net?.fetch; const MainAbortController = remote?.getGlobal?.("AbortController") as typeof AbortController | undefined; - if (!fetch || !remote?.net || typeof MainAbortController !== "function") return null; - return { fetch: fetch.bind(remote.net), AbortController: MainAbortController }; + const MainObject = remote?.getGlobal?.("Object") as typeof Object | undefined; + if (!fetch || !remote?.net || typeof MainAbortController !== "function" || !MainObject) return null; + return { + fetch: fetch.bind(remote.net), + AbortController: MainAbortController, + // remote callbacks arrive asynchronously; remote iterators cannot be + // consumed in the renderer either. Keep enumeration in the main process. + headers: (headers) => MainObject.fromEntries(headers), + }; } catch { return null; } @@ -153,6 +162,7 @@ export async function fetchSend( request: HttpRequest, send: typeof window.fetch, StackAbortController: typeof AbortController = AbortController, + readHeaders: FetchStack["headers"] = (headers) => Object.fromEntries(headers), ): Promise { const { signal, dispose } = deadline(request.signal, request.timeoutMs ?? DEFAULT_TIMEOUT_MS); // The stack's own controller is aborted whenever ours is, without a reason @@ -178,11 +188,7 @@ export async function fetchSend( if (request.throw !== false && response.status >= 400) { throw new HttpStatusError(`http_${response.status}`, `Request failed with status ${response.status}`, response.status); } - const responseHeaders: Record = {}; - response.headers.forEach((value, name) => { - responseHeaders[name] = value; - }); - return { status: response.status, headers: responseHeaders, arrayBuffer, json: parseJson(text), text }; + return { status: response.status, headers: readHeaders(response.headers), arrayBuffer, json: parseJson(text), text }; } finally { signal.removeEventListener("abort", abortStack); dispose(); diff --git a/src/syncMerge.ts b/src/syncMerge.ts index 54d8fd7..e03c4b5 100644 --- a/src/syncMerge.ts +++ b/src/syncMerge.ts @@ -75,19 +75,32 @@ function mergeLines(base: string, local: string, remote: string): string | null const b = base.split("\n"); const l = local.split("\n"); const r = remote.split("\n"); + // Trim only text that all three versions leave identical. Large notes often + // have tiny edits near one end; unchanged bulk must not force conflict copies. + let start = 0; + while (start < b.length && start < l.length && start < r.length + && b[start] === l[start] && b[start] === r[start]) start += 1; + let endB = b.length; + let endL = l.length; + let endR = r.length; + while (endB > start && endL > start && endR > start + && b[endB - 1] === l[endL - 1] && b[endB - 1] === r[endR - 1]) { + endB -= 1; + endL -= 1; + endR -= 1; + } // node-diff3's LCS is quadratic in the worst case (especially repeated // lines). Never freeze Obsidian's UI trying to merge a pathological note: - // the caller keeps both exact documents instead. Ordinary field/body edits - // above avoid diffing an unchanged body regardless of its size. - const work = b.length * (l.length + r.length); + // the caller keeps both exact documents instead. + const work = (endB - start) * (endL + endR - 2 * start); if (work > 4_000_000) return null; - const regions = diff3Merge(l, b, r, { excludeFalseConflicts: true }); + const regions = diff3Merge(l.slice(start, endL), b.slice(start, endB), r.slice(start, endR), { excludeFalseConflicts: true }); const merged: string[] = []; for (const region of regions) { if (region.conflict) return null; for (const line of region.ok ?? []) merged.push(line); } - return merged.join("\n"); + return b.slice(0, start).concat(merged, b.slice(endB)).join("\n"); } const PREAMBLE = "\u0000preamble"; @@ -127,7 +140,7 @@ function mergeFrontmatter(base: string[], local: string[], remote: string[]): st return ancestor.order.filter((key) => common.has(key)).join("\n") !== changed.order.filter((key) => common.has(key)).join("\n"); }; - if (!b || !l || !r || reordered(b, l) || reordered(b, r)) { + if (!b || !l || !r || reordered(b, l) || reordered(b, r) || reordered(l, r)) { return mergeLines(base.join("\n"), local.join("\n"), remote.join("\n"))?.split("\n") ?? null; } const merged = new Map(); diff --git a/src/syncPreview.ts b/src/syncPreview.ts index cf0d29b..53b4327 100644 --- a/src/syncPreview.ts +++ b/src/syncPreview.ts @@ -126,14 +126,17 @@ export function actionEntry(action: MirrorPlanAction): SyncPreviewEntry { : creates ? "create" : "update"; - const operation = action.command.split("_")[0]; - const movement = action.command.startsWith("move_") ? ` from ${object.path}` : ""; + const detail = verb === "delete" + ? localCommand ? "Move this device's copy to trash." : "Delete from Connect." + : verb === "rename" + ? `Rename ${localCommand ? "on this device" : "in Connect"} from ${object.path}.` + : localCommand ? "Download from Connect." : "Upload to Connect."; return { kind: object.entity === "file" ? "file" : "document", path, direction: localCommand ? "download" : "upload", action: verb, - detail: `${localCommand ? "Hosted" : "Local"} ${object.entity} will ${operation}${movement}.`, + detail, ...(object.entity === "file" && object.size !== undefined ? { estimatedBytes: object.size } : {}), ...(object.entity === "record" ? { recordId: object.identity } : {}), ...(object.entity === "file" ? { fileId: object.identity } : {}), diff --git a/src/syncScheduler.ts b/src/syncScheduler.ts index c7a7486..90abf47 100644 --- a/src/syncScheduler.ts +++ b/src/syncScheduler.ts @@ -109,6 +109,9 @@ export class SyncScheduler { /** Something outside the scheduler (settings, a manual sync) changed what is due. */ requestSoon(): void { + // Settings can change the local projection, or re-enable pending uploads, + // without advancing the hosted cursor. A probe alone cannot see that work. + this.changed = true; this.schedule(this.clock.now()); } @@ -124,6 +127,13 @@ export class SyncScheduler { let retryIn: number | null = null; try { retryIn = await this.decide(); + } catch (error) { + // A host operation may reject before returning a SyncNowResult. Keep + // that failure inside the scheduler's retry boundary, not an unhandled + // timer rejection that forgets the local changes this attempt consumed. + this.host.reportProblem(error); + const kind = this.host.problemKind(); + retryIn = kind && WAITING_FOR_PERSON.has(kind) ? this.settled() : this.failed(isTransientError(error)); } finally { this.running = false; const now = this.clock.now(); @@ -162,8 +172,8 @@ export class SyncScheduler { if (!due) return null; this.lastSyncAt = now; const result = await this.host.autoSync(); - if (result === "busy") { - this.changed ||= local; + if (result === "busy" || result === "pending") { + this.changed ||= local || result === "pending"; return 2_000; } if (result === "failed") { diff --git a/src/syncSession.ts b/src/syncSession.ts index 573113c..2d07f0b 100644 --- a/src/syncSession.ts +++ b/src/syncSession.ts @@ -37,7 +37,7 @@ export interface SyncSessionState { retryAt: number | null; } -export type SyncNowResult = "applied" | "up_to_date" | "needs_review" | "failed" | "busy" | "paused"; +export type SyncNowResult = "applied" | "up_to_date" | "needs_review" | "failed" | "busy" | "paused" | "pending"; /** Rounds of inspect, apply and settle conflicts one Sync now may take before it stops. */ const MAX_SYNC_ROUNDS = 4; @@ -62,7 +62,7 @@ type SyncController = Pick< export interface SyncHistoryLog { list(collectionId?: string): SyncHistoryRun[]; append(run: SyncHistoryRun): Promise; - remove(id: string): Promise; + acknowledge(id: string): Promise; clear(): Promise; } @@ -150,7 +150,7 @@ export class SyncSession { } async dismissEvent(id: string): Promise { - await this.history?.remove(id); + await this.history?.acknowledge(id); this.update({}); } @@ -219,7 +219,9 @@ export class SyncSession { if (!preview.plan.actions.length) { const settled = await this.settleConflicts(); if (this.current.paused) return "paused"; + if (settled === null) return "failed"; if (settled) continue; + if (this.current.status?.conflicts.length) return "needs_review"; if (!applied && !options.quiet) this.update({ message: "Already up to date." }); return applied ? "applied" : "up_to_date"; } @@ -235,10 +237,14 @@ export class SyncSession { if (this.current.paused) return "paused"; const settled = await this.settleConflicts(); if (this.current.paused) return "paused"; + if (settled === null) return "failed"; if (settled) continue; + if (this.current.status?.conflicts.length) return "needs_review"; if (!this.current.preview) return "applied"; } - return applied ? "applied" : "up_to_date"; + // Yield after a bounded number of changing plans, but keep the scheduler + // chasing the remaining work instead of declaring it settled for 15 min. + return "pending"; }, options.quiet); return result ?? "failed"; } @@ -256,15 +262,16 @@ export class SyncSession { if (this.current.retryAt !== retryAt) this.update({ retryAt }); } - /** Settle open conflicts; true when that changed files that now need syncing. */ - private async settleConflicts(): Promise { + /** True when files changed, false when none did, null when settling failed. */ + private async settleConflicts(): Promise { if (!this.current.status?.conflicts.length) return false; let resolutions: AutoResolution[]; try { resolutions = await this.controller.autoResolveConflicts(); } catch (error) { - this.update({ problem: syncProblem(error) }); - return false; + const problem = syncProblem(error); + this.update({ problem, message: problem.message }); + return null; } for (const resolution of resolutions) { await this.recordEvent(conflictEvent(resolution)); @@ -408,11 +415,15 @@ export class SyncSession { /** One inspection gives both the plan and the status. Null when it failed. */ private async loadPreview(): Promise { + const profile = this.getProfile(); + if (!profile) return null; try { const { preview, status } = await this.controller.inspect(); + if (!sameProfile(profile, this.getProfile())) return null; this.update({ preview, status, problem: null }); return preview; } catch (error) { + if (!sameProfile(profile, this.getProfile())) return null; const problem = syncProblem(error); this.update({ problem, message: problem.message }); return null; @@ -524,7 +535,9 @@ export class SyncSession { } function sameProfile(a: MirrorProfile | null, b: MirrorProfile | null): boolean { - return a?.collectionId === b?.collectionId; + return a?.collectionId === b?.collectionId + && a?.replicaId === b?.replicaId + && a?.enrollmentId === b?.enrollmentId; } function conflictEvent(resolution: AutoResolution): SyncEventInput { diff --git a/src/workspace/syncPane.ts b/src/workspace/syncPane.ts index 6e9981f..7e5b638 100644 --- a/src/workspace/syncPane.ts +++ b/src/workspace/syncPane.ts @@ -121,12 +121,18 @@ export class SyncPane { action: "resume", actionLabel: "Resume recovery", } : null); - const label = syncing ? "Syncing" : state.busy ? "Checking…" + const authorizing = Boolean(this.enrollmentAbort); + const preview = state.preview; + const safety = this.session.safety(); + const reviewing = Boolean(preview?.plan.actions.length || preview?.entries.length); + const label = authorizing ? "Waiting for approval" : syncing ? "Syncing" : state.busy ? "Checking…" : recoveryProblem?.kind === "paused" ? "Paused" : recoveryProblem?.kind === "offline" ? "Offline" : recoveryProblem?.kind === "auth" ? "Approval needed" : recoveryProblem?.kind === "device" ? "Set up this device" - : recoveryProblem ? "Needs attention" : syncStateLabel(state.status); + : recoveryProblem ? "Needs attention" + : reviewing && safety && !safety.safe ? "Review needed" + : preview?.plan.actions.length ? "Changes waiting" : syncStateLabel(state.status); const status = document.createEl("section", { cls: "mdbase-sync-status" }); status.setAttr("data-state", state.status?.state ?? "checking"); @@ -153,6 +159,7 @@ export class SyncPane { const total = state.fileProgress?.totalBytes ?? state.progress?.total ?? null; const completed = state.fileProgress?.transferredBytes ?? state.progress?.completed ?? 0; const progress = progressArea.createEl("progress"); + progress.setAttr("aria-label", "Sync progress"); progress.max = total ?? 1; progress.value = total == null ? 0 : completed; if (total == null) progress.removeAttribute("value"); @@ -167,6 +174,7 @@ export class SyncPane { : "Applying changes"} · ${completed}${total == null ? "" : ` of ${total}`}`, }); const cancel = progressArea.createEl("button", { text: "Stop" }); + cancel.setAttr("data-focus-key", "sync-stop"); cancel.onclick = () => this.session.cancel(); } @@ -178,25 +186,27 @@ export class SyncPane { }); } - if (recoveryProblem) this.renderRecoveryCard(status, recoveryProblem); + if (authorizing) this.renderApproval(status, false); + else if (recoveryProblem) this.renderRecoveryCard(status, recoveryProblem); const busy = this.ctx.busy || state.busy || syncing; - const preview = state.preview; // Comparisons belong to the plan they were opened from. if (preview !== this.comparedPreview) { this.previewComparisons.clear(); this.comparedPreview = preview; this.transferPages.clear(); } - const safety = this.session.safety(); - const reviewing = Boolean(preview?.plan.actions.length || preview?.entries.length); - if (!syncing && !recoveryProblem) { + if (reviewing && safety && !safety.safe && preview?.plan.actions.length) { + status.createDiv({ cls: "mdbase-muted mdbase-review-reasons", text: `${safety.reasons.join(", ")}.` }); + } + if (!syncing && !recoveryProblem && !authorizing) { const actions = status.createDiv({ cls: "mdbase-sync-actions" }); if (reviewing && preview) { // The plan needs consent: apply exactly what is listed below. const presentation = syncReviewPresentation(preview.plan, preview.entries.length, busy); if (preview.plan.actions.length && !presentation.actionDisabled) { const sync = actions.createEl("button", { text: presentation.actionLabel, cls: "mod-cta" }); + sync.setAttr("data-focus-key", "sync-apply"); sync.disabled = presentation.actionDisabled; sync.onclick = () => void this.session.apply(); } @@ -206,13 +216,11 @@ export class SyncPane { } else { // One action: routine changes apply at once; anything risky stops for review. const sync = actions.createEl("button", { text: state.busy ? "Checking…" : "Sync now", cls: "mod-cta" }); + sync.setAttr("data-focus-key", "sync-now"); sync.disabled = busy; sync.onclick = () => void this.session.syncNow(); } } - if (reviewing && safety && !safety.safe && preview?.plan.actions.length) { - status.createDiv({ cls: "mdbase-muted mdbase-review-reasons", text: `Review needed: ${safety.reasons.join(", ").toLowerCase()}.` }); - } if (preview && reviewing) this.renderMirrorPreview(document, preview); if (state.status?.conflicts.length) this.renderConflicts(document, state.status); @@ -250,6 +258,7 @@ export class SyncPane { } const buttons = card.createDiv({ cls: "mdbase-recovery-actions" }); const action = buttons.createEl("button", { text: problem.actionLabel, cls: "mod-cta" }); + action.setAttr("data-focus-key", "sync-recovery"); action.disabled = this.ctx.busy || this.session.state.busy; action.onclick = () => { if (problem.kind === "auth") void this.reconnectCollection(); @@ -259,34 +268,62 @@ export class SyncPane { }; if (problem.kind === "internal" || problem.kind === "recovery") { const copy = buttons.createEl("button", { text: "Copy diagnostics" }); + copy.setAttr("data-focus-key", "sync-diagnostics"); copy.onclick = () => void this.ctx.host.copySyncDiagnostics(); } } + /** The same approval wait, whether enrolling or restoring an existing connection. */ + private renderApproval(container: HTMLElement, showStatus = true): void { + const approval = container.createDiv({ cls: "mdbase-approval-link" }); + if (showStatus) approval.createSpan({ text: this.enrollmentVerification ? "Waiting for approval · " : "Connecting… " }).setAttr("role", "status"); + if (this.enrollmentVerification) { + const link = approval.createEl("a", { text: "Open Connect", href: this.enrollmentVerification }); + link.setAttr("target", "_blank"); + link.setAttr("rel", "noopener noreferrer"); + link.setAttr("data-focus-key", "approval-link"); + } + const stop = approval.createEl("button", { text: "Stop waiting" }); + stop.setAttr("data-focus-key", "stop-approval"); + stop.onclick = () => { + this.enrollmentAbort?.abort(); + this.enrollmentVerification = ""; + this.ctx.render(); + }; + } + private async reauthorizeCollection(): Promise { this.enrollmentAbort?.abort(); const abort = new AbortController(); this.enrollmentAbort = abort; + this.ctx.pendingFocusKey = "stop-approval"; + this.ctx.render(); try { await this.session.reauthorize({ signal: abort.signal, onVerification: (verification) => { this.enrollmentVerification = verification.verificationUri; - this.ctx.message = "Approve this vault again in Connect. Its local files and checkpoint remain unchanged."; + this.ctx.message = ""; window.open(verification.verificationUri, "_blank", "noopener,noreferrer"); this.ctx.render(); }, onStatus: (status) => { this.ctx.message = status.state === "waiting_for_approval" - ? "Waiting for approval in Connect…" + ? "" : `Connect is retrying approval (attempt ${status.attempt}).`; this.ctx.render(); }, }); - this.enrollmentVerification = ""; this.ctx.message = ""; + } catch (error) { + if (!isAbortError(error)) throw error; + this.ctx.message = "Cancelled. Your files and connection are unchanged."; + this.ctx.pendingFocusKey = "sync-recovery"; } finally { - if (this.enrollmentAbort === abort) this.enrollmentAbort = null; + if (this.enrollmentAbort === abort) { + this.enrollmentAbort = null; + this.enrollmentVerification = ""; + } } } @@ -297,7 +334,12 @@ export class SyncPane { const section = this.ctx.disclosure(container, "sync-activity", "History", pinned.length > 0); section.addClass("mdbase-activity"); section.id = "mdbase-sync-activity"; + const disclosure = section.parentElement as HTMLDetailsElement; + this.renderHistoryOnToggle(disclosure); + if (!disclosure.open) return; for (const run of [...pinned].reverse()) this.renderEventRow(section, run); + const completed = runs.filter((run) => !run.needsAcknowledgement); + if (!completed.length) return; const header = section.createDiv({ cls: "mdbase-section-header mdbase-history-controls" }); const query = header.createEl("input", { type: "search" }); @@ -312,12 +354,16 @@ export class SyncPane { }; if (runs.length > pinned.length) { const clear = header.createEl("button", { text: "Clear history" }); + clear.setAttr("data-focus-key", "history-clear"); clear.disabled = this.ctx.busy; - clear.onclick = () => void this.session.clearHistory(); + clear.onclick = () => void this.ctx.perform(async () => { + await this.session.clearHistory(); + this.ctx.pendingFocusKey = this.session.historyRuns().length ? "disclosure-sync-activity" : "destination-sync"; + }); } const needle = this.historyQuery.trim().toLowerCase(); - const timeline = filterRuns(runs.filter((run) => !run.needsAcknowledgement), needle) + const timeline = filterRuns(completed, needle) .sort((a, b) => b.finishedAt.localeCompare(a.finishedAt)); if (!timeline.length) { section.createDiv({ cls: "mdbase-muted", text: needle ? "No synced files match." : "No completed syncs." }); @@ -337,6 +383,14 @@ export class SyncPane { } } + /** Hidden history can contain thousands of rows; construct it only when opened. */ + private renderHistoryOnToggle(details: HTMLDetailsElement): void { + const renderedOpen = details.open; + details.addEventListener("toggle", () => { + if (this.ctx.containerEl.contains(details) && details.open !== renderedOpen) this.ctx.render(); + }); + } + private renderHistoryRun(container: HTMLElement, run: SyncHistoryRun, filtered: boolean): void { const details = container.createEl("details", { cls: "mdbase-history-run" }); const key = `history-run-${run.id}`; @@ -360,6 +414,8 @@ export class SyncPane { }); if (run.message && run.outcome !== "applied") body.createDiv({ text: run.message }); setIcon(summary.createSpan({ cls: "mdbase-history-chevron" }), "chevron-right"); + this.renderHistoryOnToggle(details); + if (!details.open) return; const ledger = details.createDiv({ cls: "mdbase-transfer-ledger mdbase-history-files" }); for (const file of run.files.slice(0, 250)) { @@ -378,6 +434,7 @@ export class SyncPane { const open = pathLine.createEl("button", { cls: "mdbase-link-button mdbase-transfer-open" }); open.createEl("code", { text: file.path }); open.setAttr("title", `Open ${file.path}`); + open.setAttr("data-focus-key", `history-open-${run.id}-${file.path}`); open.onclick = () => void this.ctx.host.openFileByPath(file.path); } else pathLine.createEl("code", { text: file.path }); if (file.fromPath) direction.createDiv({ cls: "mdbase-muted", text: `From ${file.fromPath}` }); @@ -400,14 +457,29 @@ export class SyncPane { const summary = run.summary ?? ""; if (run.message && run.message !== summary) { const details = body.createEl("details"); - details.createEl("summary", { text: summary }); + const key = `history-event-${run.id}`; + details.dataset.disclosure = key; + details.open = this.ctx.disclosures.get(key) ?? Boolean(run.needsAcknowledgement); + details.createEl("summary", { text: summary }).setAttr("data-focus-key", `disclosure-${key}`); details.createDiv({ text: run.message }); } else body.createEl("strong", { text: summary }); body.createSpan({ cls: "mdbase-muted", text: formatHistoryTime(run.finishedAt) }); + if (run.path && this.ctx.app.vault.getAbstractFileByPath(run.path)) { + const path = run.path; + const open = body.createEl("button", { cls: "mdbase-link-button mdbase-transfer-open", text: path }); + open.setAttr("title", `Open ${path}`); + open.setAttr("data-focus-key", `event-open-${run.id}`); + open.onclick = () => void this.ctx.host.openFileByPath(path); + } if (run.needsAcknowledgement) { const dismiss = row.createEl("button", { text: "Dismiss" }); + dismiss.setAttr("data-focus-key", `event-dismiss-${run.id}`); dismiss.disabled = this.ctx.busy; - dismiss.onclick = () => void this.session.dismissEvent(run.id); + dismiss.onclick = () => void this.ctx.perform(async () => { + await this.session.dismissEvent(run.id); + this.ctx.pendingFocusKey = run.message && run.message !== summary + ? `disclosure-history-event-${run.id}` : "disclosure-sync-activity"; + }); } } @@ -472,19 +544,8 @@ export class SyncPane { const section = container.createEl("section", { cls: "mdbase-editor-section mdbase-enrollment" }); section.createEl("h3", { text: "Copy a collection from Connect" }); section.createEl("p", { cls: "mdbase-muted", text: "Connect holds the collection; this vault syncs a copy. Choose a collection in Connect, then review the first sync." }); - if (this.enrollmentVerification) { - const approval = section.createDiv({ cls: "mdbase-approval-link" }); - approval.createSpan({ text: "Waiting for approval · " }); - const link = approval.createEl("a", { - text: "Open Connect", - href: this.enrollmentVerification, - }); - link.setAttr("target", "_blank"); - link.setAttr("rel", "noopener noreferrer"); - } - if (this.enrollmentAbort && this.enrollmentVerification) { - const stop = section.createEl("button", { text: "Stop waiting" }); - stop.onclick = () => this.enrollmentAbort?.abort(); + if (this.enrollmentAbort) { + this.renderApproval(section); return; } inputRow(section, "Device name", this.enrollmentMirrorName, (value) => { @@ -494,6 +555,7 @@ export class SyncPane { const accessLabel = access.createEl("label", { text: "Access" }); const select = access.createEl("select"); accessLabel.htmlFor = select.id = "mdbase-enrollment-access"; + select.setAttr("data-focus-key", "enrollment-access"); select.createEl("option", { value: "read_write", text: "Read and write" }); select.createEl("option", { value: "read_only", text: "Read only" }); select.value = this.enrollmentMode; @@ -526,14 +588,17 @@ export class SyncPane { }, { placeholder: "Choose during approval" }); this.renderFilePolicyControls(advanced); const enrollmentActions = section.createDiv({ cls: "mdbase-actions mdbase-enrollment-actions" }); - const button = enrollmentActions.createEl("button", { text: this.enrollmentAbort ? "Waiting for approval…" : "Connect" }); + const button = enrollmentActions.createEl("button", { text: "Connect" }); button.setAttr("title", "Opens Connect in your browser to choose a collection"); + button.setAttr("data-focus-key", "enrollment-connect"); button.addClass("mod-cta"); button.disabled = this.ctx.busy; button.onclick = () => void this.ctx.perform(async () => { this.enrollmentAbort?.abort(); const abort = new AbortController(); this.enrollmentAbort = abort; + this.ctx.pendingFocusKey = "stop-approval"; + this.ctx.render(); try { await this.ctx.host.connectSync.enroll({ controlUrl: this.enrollmentControlUrl, @@ -551,35 +616,37 @@ export class SyncPane { }, onStatus: (status) => { this.ctx.message = status.state === "waiting_for_approval" - ? "Waiting for approval in Connect…" + ? "" : `Connect is retrying enrollment (attempt ${status.attempt}).`; this.ctx.render(); }, }); this.enrollmentVerification = ""; - // The first sync always stops for review; show it straight away. - const preview = await this.session.review(); - const bytes = preview?.entries.reduce((sum, entry) => sum + (entry.estimatedBytes ?? 0), 0) ?? 0; - const items = preview?.entries.length ?? 0; - this.ctx.message = `Connected. Review ${items} ${items === 1 ? "item" : "items"}${bytes ? ` · ${formatBytes(bytes)}` : ""} before syncing.`; - this.ctx.render(); + if (this.enrollmentAbort === abort) this.enrollmentAbort = null; + // Copying from Connect consents to downloads, not uploading existing notes. + const result = await this.session.syncNow(); + const preview = this.session.state.preview; + if (result === "needs_review" && preview) { + const bytes = preview.entries.reduce((sum, entry) => sum + (entry.estimatedBytes ?? 0), 0); + const items = preview.entries.length; + this.ctx.message = `Connected. Review ${items} ${items === 1 ? "item" : "items"}${bytes ? ` · ${formatBytes(bytes)}` : ""} before syncing.`; + this.ctx.pendingFocusKey = "sync-apply"; + } else { + this.ctx.message = ""; + this.ctx.pendingFocusKey = this.session.state.problem ? "sync-recovery" : result === "busy" ? "sync-stop" : "sync-now"; + } } catch (error) { + this.ctx.pendingFocusKey = "enrollment-connect"; if (!isAbortError(error)) throw error; this.enrollmentVerification = ""; this.ctx.message = "Cancelled. No files synced."; } finally { - if (this.enrollmentAbort === abort) this.enrollmentAbort = null; + if (this.enrollmentAbort === abort) { + this.enrollmentAbort = null; + this.enrollmentVerification = ""; + } } }); - if (this.enrollmentAbort) { - const cancel = enrollmentActions.createEl("button", { text: "Stop waiting" }); - cancel.onclick = () => { - this.enrollmentAbort?.abort(); - this.enrollmentVerification = ""; - this.ctx.message = "Cancelled. No files synced."; - this.ctx.render(); - }; - } } private renderLocalAdoption(container: HTMLElement): void { @@ -826,6 +893,7 @@ export class SyncPane { query.oninput = () => { this.transferQuery = query.value; this.transferPages.clear(); this.ctx.render(); }; const filter = controls.createEl("select"); filter.setAttr("aria-label", "Filter transfers"); + filter.setAttr("data-focus-key", "transfer-filter"); for (const [value, label] of [["all", "All changes"], ["delete", "Deletes"], ["replace", "Replacements"], ["upload", "Uploads"], ["download", "Downloads"], ["attention", "Needs attention"]]) { filter.createEl("option", { value, text: label }); } @@ -865,6 +933,7 @@ export class SyncPane { const open = pathLine.createEl("button", { cls: "mdbase-link-button mdbase-transfer-open" }); open.createEl("code", { text: entry.path }); open.setAttr("title", `Open ${entry.path}`); + open.setAttr("data-focus-key", `preview-open-${entry.path}`); open.onclick = () => void this.ctx.host.openFileByPath(localPath); } else pathLine.createEl("code", { text: entry.path }); if (entry.estimatedBytes !== undefined) { diff --git a/src/workspaceView.ts b/src/workspaceView.ts index 0378e0f..30c6f92 100644 --- a/src/workspaceView.ts +++ b/src/workspaceView.ts @@ -32,6 +32,8 @@ export class MdbaseWorkspaceView extends ItemView implements WorkspaceContext { readonly types = new TypesPane(this); readonly sync = new SyncPane(this); readonly issues = new IssuesPane(this); + private static nextNavigationId = 0; + private readonly navigationId = `mdbase-workspace-${++MdbaseWorkspaceView.nextNavigationId}`; private refreshVersion = 0; private unsubscribeSync: (() => void) | null = null; private syncRenderTimer: number | null = null; @@ -127,15 +129,16 @@ export class MdbaseWorkspaceView extends ItemView implements WorkspaceContext { const schema = await this.host.loadWorkspaceSchema(forceReload); if (!isCurrent()) return; this.schema = schema; - await this.types.onSchemaLoaded(forceReload, isCurrent); + if (this.destination === "types") { + await this.types.onSchemaLoaded(forceReload, isCurrent); + if (!isCurrent()) return; + const records = schema ? await this.host.loadCollectionRecords() : null; + if (!isCurrent()) return; + const recordsChanged = records !== this.records; + this.records = records; + this.types.onRecordsLoaded(recordsChanged || forceReload); + } else if (this.destination === "sync") await this.sync.refresh(); if (!isCurrent()) return; - if (this.destination === "sync") await this.sync.refresh(); - if (!isCurrent()) return; - const records = schema ? await this.host.loadCollectionRecords() : null; - if (!isCurrent()) return; - const recordsChanged = records !== this.records; - this.records = records; - this.types.onRecordsLoaded(recordsChanged || forceReload); this.render(); } catch (error) { if (!isCurrent()) return; @@ -147,7 +150,8 @@ export class MdbaseWorkspaceView extends ItemView implements WorkspaceContext { showDestination(destination: Destination): void { this.destination = destination; this.render(); - if (destination === "sync") void this.sync.refresh().then(() => this.render()); + if (destination === "types") void this.refresh(); + else if (destination === "sync") void this.sync.refresh().then(() => this.render()); } /** Open Issues filtered to one note. */ @@ -195,13 +199,16 @@ export class MdbaseWorkspaceView extends ItemView implements WorkspaceContext { } const content = shell.createDiv({ cls: "mdbase-workspace-content" }); content.setAttr("data-scroll-key", "workspace"); + content.id = `${this.navigationId}-${this.destination}-panel`; + content.setAttr("role", "tabpanel"); + content.setAttr("aria-labelledby", `${this.navigationId}-${this.destination}-tab`); if (this.destination === "types") this.types.render(content); else if (this.destination === "sync") this.sync.render(content); else this.issues.render(content); this.restoreRenderSnapshot(root, snapshot); this.app.workspace?.requestSaveLayout(); if (this.pendingFocusKey) { - root.querySelector(`[data-focus-key="${this.pendingFocusKey}"]`)?.focus(); + this.focusTarget(root, this.pendingFocusKey)?.focus(); this.pendingFocusKey = null; } if (this.destination === "types") this.types.afterRender(root); @@ -221,10 +228,14 @@ export class MdbaseWorkspaceView extends ItemView implements WorkspaceContext { private renderTopbarOnly(): void { const topbar = this.containerEl.querySelector(".mdbase-topbar"); if (!topbar) return; + const snapshot = this.captureRenderSnapshot(topbar); const replacement = this.containerEl.ownerDocument.createElement("div"); this.renderTopbar(replacement); const next = replacement.firstElementChild; - if (next) topbar.replaceWith(next); + if (next) { + topbar.replaceWith(next); + this.restoreRenderSnapshot(next as HTMLElement, snapshot); + } } private captureRenderSnapshot(root: HTMLElement): RenderSnapshot { @@ -256,7 +267,7 @@ export class MdbaseWorkspaceView extends ItemView implements WorkspaceContext { element.scrollLeft = position.left; } if (!snapshot.focusKey) return; - const active = root.querySelector(`[data-focus-key="${snapshot.focusKey}"]`); + const active = this.focusTarget(root, snapshot.focusKey); active?.focus({ preventScroll: true }); if ( (active instanceof HTMLInputElement || active instanceof HTMLTextAreaElement) @@ -265,6 +276,12 @@ export class MdbaseWorkspaceView extends ItemView implements WorkspaceContext { ) active.setSelectionRange(snapshot.selectionStart, snapshot.selectionEnd); } + /** Paths and field names are opaque keys, not CSS selector fragments. */ + private focusTarget(root: HTMLElement, key: string): HTMLElement | undefined { + return Array.from(root.querySelectorAll("[data-focus-key]")) + .find((element) => element.getAttr("data-focus-key") === key); + } + iconButton(container: HTMLElement, icon: string, label: string): HTMLButtonElement { const button = container.createEl("button", { cls: "clickable-icon mdbase-icon-button" }); button.setAttr("aria-label", label); @@ -291,10 +308,15 @@ export class MdbaseWorkspaceView extends ItemView implements WorkspaceContext { const topbar = container.createDiv({ cls: "mdbase-topbar" }); const nav = topbar.createDiv({ cls: "mdbase-nav" }); nav.setAttr("role", "tablist"); - for (const [destination, label] of [["types", "Types"], ["sync", "Sync"], ["issues", "Issues"]] as const) { + nav.setAttr("aria-label", "mdbase destinations"); + const destinations = [["types", "Types"], ["sync", "Sync"], ["issues", "Issues"]] as const; + for (const [index, [destination, label]] of destinations.entries()) { const button = nav.createEl("button", { text: label, cls: "clickable-icon" }); button.addClass("mdbase-nav-button"); button.setAttr("role", "tab"); + button.id = `${this.navigationId}-${destination}-tab`; + if (this.destination === destination) button.setAttr("aria-controls", `${this.navigationId}-${destination}-panel`); + button.tabIndex = this.destination === destination ? 0 : -1; button.setAttr("data-focus-key", `destination-${destination}`); button.setAttr("aria-selected", String(this.destination === destination)); if (this.destination === destination) button.addClass("is-active"); @@ -309,6 +331,16 @@ export class MdbaseWorkspaceView extends ItemView implements WorkspaceContext { count.setAttr("title", attention.label); } button.onclick = () => this.showDestination(destination); + button.onkeydown = (event) => { + const nextIndex = event.key === "ArrowRight" ? (index + 1) % destinations.length + : event.key === "ArrowLeft" ? (index + destinations.length - 1) % destinations.length + : event.key === "Home" ? 0 + : event.key === "End" ? destinations.length - 1 : null; + if (nextIndex === null) return; + event.preventDefault(); + this.pendingFocusKey = `destination-${destinations[nextIndex][0]}`; + this.showDestination(destinations[nextIndex][0]); + }; } } diff --git a/styles.css b/styles.css index af99d77..b1b18b8 100644 --- a/styles.css +++ b/styles.css @@ -56,7 +56,7 @@ .mdbase-status-bar[data-state="waiting"] { color: var(--text-muted); } .mdbase-status-bar[data-state="attention"], .mdbase-status-bar[data-state="paused"] { color: var(--text-warning); } -.mdbase-status-bar[data-state="offline"] { color: var(--text-error); } +.mdbase-status-bar[data-state="offline"] { color: var(--text-muted); } .mdbase-note-status { cursor: pointer; @@ -1137,10 +1137,19 @@ button.mdbase-yaml-problem:disabled { } .mdbase-approval-link { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; padding: 10px 0; color: var(--text-muted); } +.mdbase-approval-link button { + min-height: 44px; + margin-left: auto; +} + .mdbase-sync-document progress { width: 100%; height: 8px; @@ -1149,6 +1158,7 @@ button.mdbase-yaml-problem:disabled { .mdbase-progress-label { margin-top: 5px; + overflow-wrap: anywhere; } /* Default surfaces are quiet; configuration and diagnostics expand in place. */ @@ -1224,7 +1234,10 @@ button.mdbase-yaml-problem:disabled { } .mdbase-sync-status > .mdbase-sync-progress, -.mdbase-sync-status > .mdbase-recovery-card { +.mdbase-sync-status > .mdbase-recovery-card, +.mdbase-sync-status > .mdbase-approval-link, +.mdbase-sync-status > .mdbase-notice, +.mdbase-sync-status > .mdbase-review-reasons { grid-column: 1 / -1; } @@ -1496,6 +1509,7 @@ button.mdbase-yaml-problem:disabled { .mdbase-activity-row[data-tone="error"] > span:first-child { color: var(--text-error); } .mdbase-activity-row svg { width: 16px; height: 16px; } .mdbase-activity-row strong { display: block; } +.mdbase-activity-row > div { min-width: 0; overflow-wrap: anywhere; } .mdbase-activity-row > div > div { margin: 2px 0; color: var(--text-muted); } /* Sync history: runs expand to the files they changed. */ @@ -1561,7 +1575,7 @@ button.mdbase-yaml-problem:disabled { gap: 16px; } -.mdbase-conflict-summary { min-width: 0; } +.mdbase-conflict-summary { min-width: 0; overflow-wrap: anywhere; } .mdbase-conflict-comparison { grid-column: 1 / -1; margin-top: 12px; } .mdbase-conflict-legend { @@ -2331,7 +2345,11 @@ button.mdbase-transfer-open:hover code { min-height: 44px; } - .mdbase-conflict-row, + .mdbase-conflict-row { + grid-template-columns: minmax(0, 1fr); + gap: 12px; + } + .mdbase-document-header { align-items: stretch; flex-direction: column; @@ -2354,13 +2372,25 @@ button.mdbase-transfer-open:hover code { min-width: 44px; } + .mdbase-sync-status { + grid-template-columns: minmax(0, 1fr); + } + + .mdbase-sync-status > .mdbase-sync-actions { + grid-column: 1; + grid-row: auto; + justify-content: flex-start; + } + .mdbase-sync-actions { flex-wrap: wrap; } .mdbase-sync-actions button, .mdbase-sync-progress button, - .mdbase-transfer-row button { + .mdbase-transfer-row button, + .mdbase-recovery-actions button, + .mdbase-activity-row button { min-height: 44px; } diff --git a/test/connectSync.settlement.test.ts b/test/connectSync.settlement.test.ts index 8e426c5..7308480 100644 --- a/test/connectSync.settlement.test.ts +++ b/test/connectSync.settlement.test.ts @@ -1,18 +1,22 @@ import "fake-indexeddb/auto"; import * as assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import type { CollectionFileDescriptor } from "@mdbase-dev/connect-protocol"; import { test } from "node:test"; import type { TFile } from "obsidian"; import { MemoryAuthority, type SyncTransport } from "@mdbase-dev/connect-sync"; -import { MemoryMirrorBlobStore, MemoryMirrorStateStore, WritableDirectoryMirror } from "@mdbase-dev/connect-sync/mirror"; +import { MemoryMirrorBlobStore, MemoryMirrorStateStore, WritableDirectoryMirror, type MirrorState } from "@mdbase-dev/connect-sync/mirror"; import { ConnectSyncController, ObsidianMirrorFileSystem, type MirrorProfile } from "../src/connectSync"; import { MemoryVault } from "./memoryVault"; -async function pair(document = "base line\n") { +async function pair(document = "base line\n", extraRecords: { record_id: string; path: string; document: string }[] = []) { const hosted = new MemoryAuthority(); - hosted.seed([{ record_id: "plan", path: "plan.md", frontmatter: {}, body: document, document, types: [] }]); + hosted.seed([{ record_id: "plan", path: "plan.md", frontmatter: {}, body: document, document, types: [] }, + ...extraRecords.map((record) => ({ ...record, frontmatter: {}, body: record.document, types: [] }))]); const replicaId = hosted.registerReplica({ name: "Here", mode: "read_write" }); const vault = new MemoryVault(); const state = new MemoryMirrorStateStore(); + const blobs = new MemoryMirrorBlobStore(); await vault.createFolder(".mdbase"); await vault.create(".mdbase/connect-role.json", JSON.stringify({ version: 1, role: "mirror", collection_id: hosted.collectionId })); let profile: MirrorProfile | null = { @@ -20,6 +24,7 @@ async function pair(document = "base line\n") { controlUrl: "https://connect.example", collectionId: hosted.collectionId, replicaId, mode: "read_write", name: "Here", enrollmentId: "11111111-1111-4111-8111-111111111111", accessTokenExpiresAt: "2099-01-01T00:00:00.000Z", + selectiveSync: { file_classes: ["image"], excluded_folders: [] }, }; let wrapTransport = (transport: SyncTransport) => transport; const controller = new ConnectSyncController({ vault, secretStorage: { @@ -28,7 +33,7 @@ async function pair(document = "base line\n") { getMirrorProfile: () => profile, saveMirrorProfile: async (next) => { profile = next; }, deviceId: () => "test-device", }, { - stateStoreFactory: () => state, blobStoreFactory: () => new MemoryMirrorBlobStore(), + stateStoreFactory: () => state, blobStoreFactory: () => blobs, fileSystem: new ObsidianMirrorFileSystem(vault as never), transportFactory: () => wrapTransport(hosted.transport(replicaId)), }); @@ -58,6 +63,35 @@ function interceptSnapshot(transport: SyncTransport, intercept: () => Promise { await intercept(); return transport.snapshot(id, page); } }; } +test("unclean Markdown/YAML corpus keeps both exact documents through the next sync", async () => { + const fields = [ + "state: 'seed-value' # inline comment", + "state: |\n seed-value\n literal --- and 🥒", + "state: >-\n seed-value\n continuation", + "state: [seed-value, α, 🥒]", + "state: {nested: seed-value, values: [a, b]}", + "state:\n nested: seed-value\n values:\n - α\n - 🥒", + ]; + for (const field of fields) for (let format = 0; format < 3; format++) { + const eol = format === 1 ? "\r\n" : "\n"; + const bom = format === 2 ? "\uFEFF" : ""; + const base = `${bom}---\n# header\n${field}\n---\nBody\n\n---\ninside body${format === 2 ? "" : "\n"}`.split("\n").join(eol); + const local = base.replace("seed-value", "local-α🥒"); + const remote = base.replace("seed-value", "hosted-β🌈"); + const here = await pair(base); + await here.conflict(local, remote); + const [result] = await here.controller.autoResolveConflicts(); + assert.equal(result?.outcome, "kept_both", `${field} / format ${format}`); + assert.equal(here.vault.read("plan.md"), remote); + assert.equal(here.vault.read(result!.copyPath!), local); + await here.sync(); + await here.remoteMirror.sync(); + assert.equal(here.remoteVault.read("plan.md"), remote); + assert.equal(here.remoteVault.read(result!.copyPath!), local); + assert.deepEqual(await here.controller.autoResolveConflicts(), []); + } +}); + test("repeated settling of a stale local decision does not multiply identical copies", async () => { const here = await pair(); await here.conflict(); @@ -103,10 +137,123 @@ test("a merged write racing a user edit preserves the edit and the hosted half", await here.vault.modify(file, local + "user edit during merge\n"); return process(file, transform); }; - const [result] = await here.controller.autoResolveConflicts(); - assert.equal(result?.outcome, "kept_both"); + const results = await here.controller.autoResolveConflicts(); + assert.deepEqual(results, [], "a stale atomic merge stays open for the next sync"); assert.equal(here.vault.read("plan.md"), local + "user edit during merge\n"); - assert.equal(here.vault.read(result!.copyPath!), remote); + assert.equal(here.remoteVault.read("plan.md"), remote); + assert.ok((await here.state.read())?.planned_conflicts?.plan); + assert.deepEqual(copies(here.vault), []); +}); + +test("restart at the merged-write boundary cannot upload unmerged local over hosted edits", async () => { + const base = "---\nstatus: open\npriority: low\n---\nBody\n"; + const here = await pair(base); + const local = base.replace("status: open", "status: done"); + const remote = base.replace("priority: low", "priority: high"); + await here.conflict(local, remote); + let atWrite: MirrorState | null = null; + const process = here.vault.process.bind(here.vault); + here.vault.process = async (file, transform) => { + atWrite = structuredClone(await here.state.read()); + return process(file, transform); + }; + await here.controller.autoResolveConflicts(); + assert.ok(atWrite); + // Reconstruct only durable state and bytes available immediately before the + // merged write, as if Obsidian had crashed at that exact async boundary. + const recoveredState = new MemoryMirrorStateStore(); + await recoveredState.write(atWrite); + const recoveredVault = new MemoryVault(); + await recoveredVault.create("plan.md", local); + const replicaId = (atWrite as MirrorState).replica_id; + const restarted = new WritableDirectoryMirror(replicaId, here.hosted.transport(replicaId), { + fileSystem: new ObsidianMirrorFileSystem(recoveredVault as never), stateStore: recoveredState, + blobStore: new MemoryMirrorBlobStore(), selectiveSync: { file_classes: ["image"], excluded_folders: [] }, + }); + await restarted.sync(); + await here.remoteMirror.sync(); + assert.equal(here.remoteVault.read("plan.md"), remote, "a restart must leave the hosted half intact until the merge is durable"); + assert.equal(recoveredVault.read("plan.md"), local); +}); + +test("failed checkpoint after a merged write retains both edits through retry", async () => { + const base = "---\nstatus: open\npriority: low\n---\nBody\n"; + const here = await pair(base); + await here.conflict(base.replace("status: open", "status: done"), base.replace("priority: low", "priority: high")); + const write = here.state.write.bind(here.state); + let failed = false; + here.state.write = async (next) => { + if (!failed && !next.planned_conflicts?.plan) { + failed = true; + throw new Error("checkpoint unavailable after merged file write"); + } + await write(next); + }; + const [result] = await here.controller.autoResolveConflicts(); + assert.equal(result?.outcome, "unresolved"); + assert.ok((await here.state.read())?.planned_conflicts?.plan); + assert.match(here.vault.read("plan.md")!, /status: done[\s\S]*priority: high/); + await here.sync(); + await here.controller.autoResolveConflicts(); + await here.sync(); + await here.remoteMirror.sync(); + assert.equal((await here.controller.status())?.conflicts.length, 0); + assert.match(here.remoteVault.read("plan.md")!, /status: done[\s\S]*priority: high/); + assert.deepEqual(copies(here.vault), []); +}); + +test("SDK refuses a merged document supplied to hosted-side resolution", async () => { + const here = await pair(); + await here.conflict(); + const state = (await here.state.read())!; + const mirror = new WritableDirectoryMirror(state.replica_id, here.hosted.transport(state.replica_id), { + fileSystem: new ObsidianMirrorFileSystem(here.vault as never), stateStore: here.state, + blobStore: new MemoryMirrorBlobStore(), selectiveSync: { file_classes: ["image"], excluded_folders: [] }, + }); + await assert.rejects(mirror.resolveConflict("plan", state.planned_conflicts!.plan!.decision_id!, "remote", "invalid merged text"), + (error: unknown) => (error as { code?: string }).code === "invalid_conflict_resolution"); + assert.equal(here.vault.read("plan.md"), "local line\n"); + assert.ok((await here.state.read())?.planned_conflicts?.plan); +}); + +test("failed merged write keeps the conflict durable without requiring a recovery-copy write", async () => { + const base = "---\nstatus: open\npriority: low\n---\nBody\n"; + const here = await pair(base); + const local = base.replace("status: open", "status: done"); + const remote = base.replace("priority: low", "priority: high"); + await here.conflict(local, remote); + const process = here.vault.process.bind(here.vault); + const createBinary = here.vault.createBinary.bind(here.vault); + here.vault.process = async () => { throw new Error("disk full on merged write"); }; + here.vault.createBinary = async () => { throw new Error("disk full on recovery copy"); }; + const [result] = await here.controller.autoResolveConflicts(); + assert.equal(result?.outcome, "unresolved"); + assert.equal(here.vault.read("plan.md"), local); + assert.ok((await here.state.read())?.planned_conflicts?.plan, "failed recovery must not authorize a later upload over hosted edits"); + here.vault.process = process; + here.vault.createBinary = createBinary; + await here.sync(); + await here.controller.autoResolveConflicts(); + await here.sync(); + await here.remoteMirror.sync(); + assert.match(here.remoteVault.read("plan.md")!, /status: done[\s\S]*priority: high/); +}); + +test("taking hosted after keeping a copy cannot overwrite a newer local edit during snapshot loading", async () => { + const here = await pair(); + await here.conflict(); + let snapshots = 0; + here.wrap((transport) => interceptSnapshot(transport, async () => { + snapshots += 1; + // One snapshot for merging, then the SDK's conflict-resolution snapshot. + if (snapshots === 2) { + await here.vault.modify(here.vault.getAbstractFileByPath("plan.md") as TFile, "new user edit after copy\n"); + } + })); + await here.controller.autoResolveConflicts(); + const texts = here.vault.getMarkdownFiles().map((file) => here.vault.read(file.path)); + assert.ok(texts.includes("new user edit after copy\n"), "newer edit must survive somewhere"); + assert.ok(texts.includes("local line\n"), "the original kept copy survives too"); }); test("an old conflict without ancestor capture keeps both and settles only once", async () => { @@ -161,6 +308,140 @@ test("a conflict on a conflict copy does not nest copy labels", async () => { assert.equal(path, "plan (local conflict copy 2).md"); }); +test("concurrent settling reports one resolution, not a spurious missing-conflict error", async () => { + const here = await pair(); + await here.conflict(); + const outcomes = (await Promise.all([ + here.controller.autoResolveConflicts(), + here.controller.autoResolveConflicts(), + ])).flat(); + assert.deepEqual(outcomes.map((result) => result.outcome), ["kept_both"]); + assert.equal(copies(here.vault).length, 1); +}); + +test("inspection cannot see a cleared conflict before its merged write completes", async () => { + const base = "---\nstatus: open\npriority: low\n---\nBody\n"; + const here = await pair(base); + await here.conflict(base.replace("status: open", "status: done"), base.replace("priority: low", "priority: high")); + let writing!: () => void; + const enteredWrite = new Promise((resolve) => { writing = resolve; }); + let release!: () => void; + const gate = new Promise((resolve) => { release = resolve; }); + const process = here.vault.process.bind(here.vault); + here.vault.process = async (file, transform) => { writing(); await gate; return process(file, transform); }; + const settle = here.controller.autoResolveConflicts(); + await enteredWrite; + let inspected = false; + const inspection = here.controller.inspect().then((value) => { inspected = true; return value; }); + try { + await new Promise((resolve) => setTimeout(resolve, 20)); + assert.equal(inspected, false, "inspection must queue behind the whole settlement"); + } finally { + release(); + await settle; + await inspection; + } + assert.match(here.vault.read("plan.md")!, /status: done[\s\S]*priority: high/); +}); + +test("Connect-rejected changes remain explicit and are not retried as copies", async () => { + const here = await pair(); + let mutations = 0; + here.wrap((transport) => ({ ...transport, mutate: async (mutation) => { + mutations += 1; + return { mutation_id: mutation.mutation_id, status: "rejected", error: { code: "schema_validation_failed", message: "Record rejected by collection rules." } }; + } })); + await here.vault.modify(here.vault.getAbstractFileByPath("plan.md") as TFile, "rejected local edit\n"); + await here.sync(); + assert.equal((await here.state.read())?.planned_conflicts?.plan?.conflict_kind, "rejected"); + const before = mutations; + for (let attempt = 0; attempt < 3; attempt++) { + const [result] = await here.controller.autoResolveConflicts(); + assert.equal(result?.outcome, "unresolved"); + } + assert.equal(mutations, before); + assert.deepEqual(copies(here.vault), []); + assert.equal(here.vault.read("plan.md"), "rejected local edit\n"); +}); + +test("recorded path_occupied conflicts keep both rather than attempting a text merge", async () => { + const here = await pair(); + await here.conflict(); + const state = (await here.state.read())!; + // The SDK can persist this kind for move collisions. Exercise the host's + // settlement branch independently of identity/path-matching heuristics. + state.planned_conflicts!.plan!.conflict_kind = "path_occupied"; + await here.state.write(state); + const [result] = await here.controller.autoResolveConflicts(); + assert.equal(result?.outcome, "kept_both"); + assert.equal(here.vault.read("plan.md"), "remote line\n"); + assert.equal(here.vault.read(result!.copyPath!), "local line\n"); + assert.deepEqual(await here.controller.autoResolveConflicts(), []); +}); + +test("local rename into a hosted occupied path settles without copy loops", async () => { + const here = await pair("base line\n", [{ record_id: "other", path: "occupied.md", document: "unrelated hosted note\n" }]); + await here.remoteVault.modify(here.remoteVault.getAbstractFileByPath("occupied.md") as TFile, "unrelated hosted note revised\n"); + await here.remoteMirror.sync(); + await here.vault.delete(here.vault.getAbstractFileByPath("occupied.md") as TFile); + await here.vault.rename(here.vault.getAbstractFileByPath("plan.md") as TFile, "occupied.md"); + await here.sync(); + assert.ok(Object.keys((await here.state.read())!.planned_conflicts!).length > 0); + for (let attempt = 0; attempt < 3; attempt++) { + const results = await here.controller.autoResolveConflicts(); + assert.ok(results.every((result) => result.outcome !== "unresolved"), JSON.stringify(results)); + await here.sync(); + } + assert.equal((await here.controller.status())?.conflicts.length, 0); + assert.equal(here.vault.read("occupied.md"), "unrelated hosted note revised\n"); + assert.ok(copies(here.vault).length <= 1); + assert.ok(here.vault.getMarkdownFiles().some((file) => here.vault.read(file.path) === "base line\n")); +}); + +test("local rename plus hosted edit retains both changes without repeated settling", async () => { + const here = await pair(); + await here.remoteVault.modify(here.remoteVault.getAbstractFileByPath("plan.md") as TFile, "hosted edit while renamed\n"); + await here.remoteMirror.sync(); + await here.vault.rename(here.vault.getAbstractFileByPath("plan.md") as TFile, "renamed.md"); + await here.sync(); + await here.controller.autoResolveConflicts(); + await here.sync(); + assert.equal((await here.controller.status())?.conflicts.length, 0); + const texts = here.vault.getMarkdownFiles().map((file) => here.vault.read(file.path)); + assert.ok(texts.includes("hosted edit while renamed\n")); + assert.ok(texts.includes("base line\n")); + assert.deepEqual(await here.controller.autoResolveConflicts(), []); +}); + +test("binary conflicts keep exact bytes on both sides and settle only once", async () => { + const here = await pair(); + const bytes = new Uint8Array([0, 255, 1, 128]); + const descriptor = (content: Uint8Array): CollectionFileDescriptor => { + const digest = createHash("sha256").update(content).digest("hex"); + return { file_id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", path: "image.png", revision: `file:${digest}`, + content_digest: `sha256:${digest}`, size: content.length, media_class: "image", media_type: "image/png", + modified_at: "2026-10-01T00:00:00.000Z" }; + }; + let hostedBytes = bytes; + here.wrap((transport) => ({ ...transport, + fileSnapshot: async (id, page) => ({ ...await transport.fileSnapshot(id, page), files: [descriptor(hostedBytes)] }), + changes: async (after, limit) => ({ ...await transport.changes(after, limit), reset_required: true }), + downloadFile: async function* () { yield hostedBytes; }, + })); + const firstFileSync = await here.sync(); + assert.deepEqual(here.vault.readBytes("image.png"), bytes, JSON.stringify(firstFileSync)); + const localBytes = new Uint8Array([0, 254, 1, 128, 42]); + await here.vault.modifyBinary(here.vault.getAbstractFileByPath("image.png") as TFile, localBytes.buffer); + hostedBytes = new Uint8Array([0, 253, 1, 127, 43]); + await here.sync(); + const [result] = await here.controller.autoResolveConflicts(); + assert.equal(result?.outcome, "kept_both"); + assert.deepEqual(here.vault.readBytes("image.png"), hostedBytes); + assert.deepEqual(here.vault.readBytes(result!.copyPath!), localBytes); + assert.deepEqual(await here.controller.autoResolveConflicts(), []); + assert.equal(copies(here.vault).length, 1); +}); + test("hosted rename plus local edit retains both versions without waiting", async () => { const here = await pair(); await here.remoteVault.rename(here.remoteVault.getAbstractFileByPath("plan.md") as TFile, "renamed.md"); diff --git a/test/connectSync.transport.test.ts b/test/connectSync.transport.test.ts index 8d33067..30070be 100644 --- a/test/connectSync.transport.test.ts +++ b/test/connectSync.transport.test.ts @@ -57,6 +57,7 @@ test("platform send uses the privileged desktop stack with that stack's own abor } const send = platformSend({ AbortController: TrackingController, + headers: (headers) => Object.fromEntries(headers), fetch: async (_input: RequestInfo | URL, init?: RequestInit) => { desktopCalls += 1; assert.equal(new Headers(init?.headers).get("authorization"), "Bearer device-secret"); @@ -76,6 +77,31 @@ test("platform send uses the privileged desktop stack with that stack's own abor assert.equal(desktopCalls, 1); }); +test("desktop response headers are serialized in their owning process before returning", async () => { + // Electron remote callbacks and iterators do not synchronously enumerate in + // the renderer. In particular, missing ETag breaks every multipart upload. + const remoteHeaders = { + forEach: (callback: (value: string, name: string) => void) => { + setTimeout(() => callback('"part-etag"', "etag"), 0); + }, + [Symbol.iterator]: function* () {}, + }; + const send = platformSend({ + AbortController, + fetch: async () => ({ + status: 200, + headers: remoteHeaders, + arrayBuffer: async () => new ArrayBuffer(0), + }) as unknown as Response, + headers: (headers: Headers) => { + assert.equal(headers, remoteHeaders); + return { etag: '"part-etag"', "retry-after": "7", "content-length": "0" }; + }, + }); + const result = await send({ url: "https://objects.example/part", method: "PUT", throw: false }); + assert.deepEqual(result.headers, { etag: '"part-etag"', "retry-after": "7", "content-length": "0" }); +}); + test("a desktop request that never answers times out instead of hanging sync", async () => { const hung = (_input: RequestInfo | URL, init?: RequestInit) => new Promise((_resolve, reject) => { init?.signal?.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError"))); diff --git a/test/indexedDb.test.ts b/test/indexedDb.test.ts index e58c95a..ae285a7 100644 --- a/test/indexedDb.test.ts +++ b/test/indexedDb.test.ts @@ -24,6 +24,32 @@ test("aborted IndexedDB writes reject without replacing the last durable checkpo assert.deepEqual(await new IndexedDbMirrorStateStore(key).read(), original); }); +test("a transient IndexedDB open failure does not poison either adapter forever", async () => { + const adapters = [ + { store: new IndexedDbMirrorStateStore(crypto.randomUUID()), read: function () { return this.store.read(); } }, + { store: new IndexedDbMirrorBlobStore(crypto.randomUUID()), read: function () { return this.store.has(digest); } }, + ]; + for (const adapter of adapters) { + const open = indexedDB.open; + let opens = 0; + indexedDB.open = function (...args: Parameters) { + opens++; + if (opens > 1) return open.apply(this, args); + const request = { error: new DOMException("temporary storage error", "UnknownError") } as IDBOpenDBRequest; + queueMicrotask(() => request.onerror?.call(request, new Event("error"))); + return request; + }; + try { + await assert.rejects(adapter.read(), /temporary storage error/); + await adapter.read(); + assert.equal(opens, 2, "the next retry must really reopen storage"); + } finally { + indexedDB.open = open; + adapter.store.close(); + } + } +}); + test("old binary-stage cleanup failure cannot corrupt a published replacement", async () => { const store = new IndexedDbMirrorBlobStore(crypto.randomUUID()); await store.write(digest, bytes()); diff --git a/test/mdbaseCore.test.ts b/test/mdbaseCore.test.ts index c76da1d..40728cc 100644 --- a/test/mdbaseCore.test.ts +++ b/test/mdbaseCore.test.ts @@ -16,12 +16,41 @@ import { loadTypeDefinitions, normalizeSafeRelativePath, parseFrontmatter, + readCollectionRecords, schemaFromV03Fields, validateCollection, validateFile, isExcluded, } from "../src/mdbaseCore"; +test("record scans yield to UI timers even when every vault read is cached", async () => { + const vault = new MockVault(); + for (let index = 0; index < 100; index++) await vault.create(`${index}.md`, `---\ntitle: ${index}\n---\nBody`); + const config: MdbaseConfig = { + spec_version: "0.3.0", + settings: { types_folder: "_types", exclude: [], explicit_type_keys: ["type", "types"] }, + }; + const cachedRead = vault.cachedRead.bind(vault); + let reads = 0; + vault.cachedRead = async (file) => { + reads++; + // Model cached frontmatter parsing without an I/O macrotask boundary. + const start = performance.now(); + while (performance.now() - start < 0.5) { /* simulated CPU work */ } + return cachedRead(file); + }; + let readsWhenTimerRan = -1; + const timer = setTimeout(() => { readsWhenTimerRan = reads; }, 0); + try { + const records = await readCollectionRecords(vault as never, config); + assert.equal(records.length, 100); + assert.ok(readsWhenTimerRan >= 0 && readsWhenTimerRan < 100, + `A UI timer must run before the scan finishes, not at read ${readsWhenTimerRan}`); + } finally { + clearTimeout(timer); + } +}); + interface StoredFile { file: TFile; content: string; diff --git a/test/obsidian-mock.cjs b/test/obsidian-mock.cjs index adcaa4d..469f802 100644 --- a/test/obsidian-mock.cjs +++ b/test/obsidian-mock.cjs @@ -79,7 +79,48 @@ class Modal { } class SuggestModal extends Modal {} -class Notice {} +class Notice { + static messages = []; + constructor(message) { Notice.messages.push(message); } +} +class PluginSettingTab { + constructor(app, plugin) { + this.app = app; + this.plugin = plugin; + this.containerEl = document.createElement("div"); + } +} +class Setting { + constructor(container) { + this.settingEl = container.createDiv({ cls: "setting-item" }); + this.nameEl = this.settingEl.createDiv(); + this.descEl = this.settingEl.createDiv(); + this.controlEl = this.settingEl.createDiv(); + } + setName(name) { this.nameEl.textContent = name; return this; } + setDesc(desc) { this.descEl.textContent = desc; return this; } + setHeading() { return this; } + addButton(build) { + const el = this.controlEl.createEl("button"); + const api = { + setButtonText(text) { el.textContent = text; return api; }, + setDisabled(value) { el.disabled = value; return api; }, + setWarning() { el.classList.add("mod-warning"); return api; }, + onClick(handler) { el.onclick = handler; return api; }, + }; + build(api); + return this; + } + addToggle(build) { + const el = this.controlEl.createEl("input", { type: "checkbox" }); + const api = { + setValue(value) { el.checked = value; return api; }, + onChange(handler) { el.onchange = () => handler(el.checked); return api; }, + }; + build(api); + return this; + } +} // Records the most recently shown menu so tests can invoke its items. class Menu { constructor() { this.items = []; } @@ -121,6 +162,8 @@ module.exports = { Modal, SuggestModal, Notice, + PluginSettingTab, + Setting, Platform, setIcon, requestUrl, diff --git a/test/settingsTab.test.ts b/test/settingsTab.test.ts new file mode 100644 index 0000000..543be54 --- /dev/null +++ b/test/settingsTab.test.ts @@ -0,0 +1,97 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { JSDOM } from "jsdom"; +import { Notice } from "obsidian"; +import { MdbaseSettingTab } from "../src/settingsTab"; + +function fixture() { + const dom = new JSDOM(""); + Object.assign(globalThis, { window: dom.window, document: dom.window.document }); + Object.assign(dom.window.HTMLElement.prototype, { + createEl(this: HTMLElement, tag: string, options: Record = {}) { + const el = this.ownerDocument.createElement(tag); + for (const [key, value] of Object.entries(options)) { + if (key === "text") el.textContent = String(value); + else if (key === "cls") el.className = String(value); + else if (key === "attr") for (const [name, val] of Object.entries(value as object)) el.setAttribute(name, String(val)); + else el.setAttribute(key, String(value)); + } + this.appendChild(el); + return el; + }, + createDiv(this: HTMLElement, options = {}) { return this.createEl("div", options); }, + setAttr(this: HTMLElement, name: string, value: string) { this.setAttribute(name, value); }, + empty(this: HTMLElement) { this.replaceChildren(); }, + }); + const notices = (Notice as unknown as { messages: string[] }).messages; + notices.length = 0; + let policy = { file_classes: [], excluded_folders: [] }; + const plugin = { + settings: { autoSync: true }, + saveSettings: async () => undefined, + requestSync: () => undefined, + getMirrorProfile: () => ({ name: "Notes", mode: "read_write", controlUrl: "https://connect.example" }), + openWorkspace: async () => ({ reconnectCollection: async () => undefined }), + connectSync: { getSelectiveSync: () => policy }, + sync: { + isSyncing: () => false, + configureSelectiveSync: async (next: typeof policy) => { policy = next; }, + }, + }; + const tab = new MdbaseSettingTab({ vault: { getAllLoadedFiles: () => [] } } as never, plugin as never); + tab.display(); + return { dom, plugin, tab, root: tab.containerEl, notices, policy: () => policy }; +} + +function button(root: HTMLElement, label: string): HTMLButtonElement { + const result = Array.from(root.querySelectorAll("button")).find(el => el.textContent === label); + assert.ok(result, `Missing button: ${label}`); + return result; +} + +const settle = () => new Promise(resolve => setImmediate(resolve)); + +test("failed exclusion changes report only failure and leave the saved scope unchanged", async () => { + const f = fixture(); + f.plugin.sync.configureSelectiveSync = async () => { throw new Error("Settings could not be saved"); }; + const input = f.root.querySelector("[aria-label='Excluded folder']")!; + input.value = "Private"; + button(f.root, "Exclude folder").click(); + button(f.root, "Apply").click(); + await settle(); + assert.deepEqual(f.policy().excluded_folders, []); + assert.deepEqual(f.notices, ["Settings could not be saved"]); + assert.equal(button(f.root, "Apply").disabled, false); + f.dom.window.close(); +}); + +test("applying exclusions waits for persistence and prevents duplicate requests", async () => { + const f = fixture(); + let save: () => void = () => assert.fail("Save not started"); + let calls = 0; + f.plugin.sync.configureSelectiveSync = async () => { + calls++; + await new Promise(resolve => { save = resolve; }); + }; + const apply = button(f.root, "Apply"); + apply.click(); + assert.equal(apply.disabled, true); + apply.click(); + assert.equal(calls, 1); + assert.deepEqual(f.notices, []); + save(); + await settle(); + assert.deepEqual(f.notices, ["Excluded folders updated. The next sync applies them."]); + assert.equal(apply.disabled, false); + f.dom.window.close(); +}); + +test("reconnect failures restore the settings action and report the error", async () => { + const f = fixture(); + f.plugin.openWorkspace = async () => { throw new Error("Workspace could not open"); }; + button(f.root, "Reconnect").click(); + await settle(); + assert.equal(button(f.root, "Reconnect").disabled, false); + assert.deepEqual(f.notices, ["Workspace could not open"]); + f.dom.window.close(); +}); diff --git a/test/syncHistory.test.ts b/test/syncHistory.test.ts index 987ade1..1a0131d 100644 --- a/test/syncHistory.test.ts +++ b/test/syncHistory.test.ts @@ -207,6 +207,29 @@ test("the store appends one line per run, filters by collection and survives a r assert.equal(adapter.files.get("history.jsonl"), ""); }); +test("concurrent history appends never duplicate entries on disk", async () => { + const adapter = new MemoryAdapter(); + const now = new Date().toISOString(); + const store = new SyncHistoryStore(adapter, "history.jsonl"); + await store.load(); + await Promise.all(Array.from({ length: 5 }, (_, index) => store.append(run(String(index), now, [`${index}.md`])))); + const reloaded = new SyncHistoryStore(adapter, "history.jsonl"); + await reloaded.load(); + assert.deepEqual(reloaded.list().map((entry) => entry.id), ["0", "1", "2", "3", "4"]); +}); + +test("history repairs a torn tail before appending the next run", async () => { + const adapter = new MemoryAdapter(); + const now = new Date().toISOString(); + adapter.files.set("history.jsonl", `${JSON.stringify(run("first", now, ["a.md"]))}\n{"id":"torn`); + const store = new SyncHistoryStore(adapter, "history.jsonl"); + await store.load(); + await store.append(run("next", now, ["b.md"])); + const reloaded = new SyncHistoryStore(adapter, "history.jsonl"); + await reloaded.load(); + assert.deepEqual(reloaded.list().map((entry) => entry.id), ["first", "next"]); +}); + test("events share the log: they filter by path, appear in note history, and pinned ones survive clearing", async () => { const adapter = new MemoryAdapter(); const store = new SyncHistoryStore(adapter, "history.jsonl"); @@ -222,8 +245,13 @@ test("events share the log: they filter by path, appear in note history, and pin assert.deepEqual(historyForPath(store.list("c1"), "notes/a.md").map(({ run }) => run.id), [decision.id]); await store.clear(); assert.deepEqual(store.list("c1").map((r) => r.id), [pinned.id]); - await store.remove(pinned.id); - assert.deepEqual(store.list("c1"), []); + await store.acknowledge(pinned.id); + assert.deepEqual(store.list("c1").map((r) => [r.id, r.needsAcknowledgement]), [[pinned.id, false]]); + const reloaded = new SyncHistoryStore(adapter, "history.jsonl"); + await reloaded.load(); + assert.deepEqual(reloaded.list("c1").map((r) => [r.id, r.needsAcknowledgement]), [[pinned.id, false]]); + await reloaded.clear(); + assert.deepEqual(reloaded.list("c1"), []); }); test("pruning bounds the number of entries as well as their files", () => { diff --git a/test/syncMerge.properties.test.ts b/test/syncMerge.properties.test.ts index 8b107f6..0c447bb 100644 --- a/test/syncMerge.properties.test.ts +++ b/test/syncMerge.properties.test.ts @@ -62,6 +62,36 @@ for (const seed of [1, 0xC0FFEE, 0xDEADBEEF]) { }); } +test("seeded insert/delete/replace mutations preserve the exact union of disjoint edits", () => { + const next = random(0x51A7E); + for (let iteration = 0; iteration < 400; iteration++) { + const fields = Array.from({ length: 10 }, (_, index) => field(`field${index}`, `base-${index}`, Math.floor(next() * 6))); + const body = Array.from({ length: 16 }, (_, index) => `line-${index}-α🥒`); + const mutate = (lines: string[], slot: number, actor: string, yaml: boolean) => { + const mode = Math.floor(next() * 3); + const change = yaml ? field(`field${slot}`, `${actor}-${iteration}`, Math.floor(next() * 6)) : `${actor}-${iteration}-🌈`; + const extra = yaml ? field(`added_${actor}`, `${actor}-${iteration}`, Math.floor(next() * 6)) : `${actor}-${iteration}-inserted`; + return lines.map((line, index) => index === slot ? mode === 0 ? [change] : mode === 1 ? [] : [line, extra] : [line]); + }; + const localFields = mutate(fields, 2, "local", true); + const remoteFields = mutate(fields, 7, "hosted", true); + const localBody = mutate(body, 2, "local", false); + const remoteBody = mutate(body, 12, "hosted", false); + const eol = next() < 0.5 ? "\n" : "\r\n"; + const bom = next() < 0.5 ? "" : "\uFEFF"; + const trailing = next() < 0.5 ? "" : "\n"; + const render = (f: string[][], b: string[][]) => `${bom}---\n# header\n${f.flat().join("\n")}\n---\n${b.flat().join("\n")}${trailing}`.split("\n").join(eol); + const base = render(fields.map((line) => [line]), body.map((line) => [line])); + const local = render(localFields, body.map((line) => [line])); + const remote = render(remoteFields, body.map((line) => [line])); + const expected = render(localFields.map((lines, index) => index === 7 ? remoteFields[index]! : lines), localBody.map((lines, index) => index === 12 ? remoteBody[index]! : lines)); + // Both devices also mutate well-separated body slots. + const l = local.replace(body.join(eol), localBody.flat().join(eol)); + const r = remote.replace(body.join(eol), remoteBody.flat().join(eol)); + assert.deepEqual(merge(base, l, r), { clean: true, text: expected }, `iteration ${iteration}`); + } +}); + test("overlapping generated fields keep both, including block scalars and nested maps", () => { for (let style = 0; style < 6; style++) { const render = (value: string) => `---\n${field("value", value, style)}\n---\nBody`; @@ -89,13 +119,13 @@ test("added or removed frontmatter with another body edit keeps both", () => { }); // Isolate performance cases so a regression cannot hang the entire test runner. -async function largeMerge(scenario: string): Promise { +async function largeMerge(scenario: string, mustMerge = false): Promise { const moduleUrl = new URL("../src/syncMerge.js", import.meta.url).href; const worker = new Worker(` const { parentPort } = require("node:worker_threads"); import(${JSON.stringify(moduleUrl)}).then(({ mergeDocuments }) => { const body = "a\\n".repeat(512 * 1024); - const base = "---\\nstatus: open\\n---\\n" + body; + let base = "---\\nstatus: open\\n---\\n" + body; ${scenario} parentPort.postMessage(mergeDocuments(base, local, remote, () => true)); }); @@ -107,6 +137,7 @@ async function largeMerge(scenario: string): Promise { worker.once("message", (result: { clean: boolean; text?: string }) => { clearTimeout(timer); try { + if (mustMerge) assert.equal(result.clean, true, "unchanged bulk must not prevent a small clean merge"); // Keeping both is acceptable for pathological diffs; a clean merge // must retain both edits, not return a partial result. if (result.clean) { @@ -127,6 +158,12 @@ test("1 MB repeated-line body with independent frontmatter edit stays responsive const remote = base + "hosted edit\\n";`); }); +test("1 MB unchanged prefix does not force conflict copies for small disjoint edits", async () => { + await largeMerge(`base += "alpha\\n\\nbeta\\n\\ngamma\\n"; + const local = base.replace("alpha", "local edit"); + const remote = base.replace("gamma", "hosted edit");`, true); +}); + test("1 MB repeated-line body edited on both sides stays responsive", async () => { await largeMerge(`const local = base.replace("---\\na", "---\\nlocal edit"); const remote = base + "hosted edit\\n";`); diff --git a/test/syncMerge.test.ts b/test/syncMerge.test.ts index 275d652..64ad0f6 100644 --- a/test/syncMerge.test.ts +++ b/test/syncMerge.test.ts @@ -99,6 +99,13 @@ test("a hosted field reorder is never silently discarded", () => { if (result.clean) assert.equal(result.text, doc("priority: low\ntitle: Plan\nstatus: done", "Body\n")); }); +test("the same field added at incompatible positions is not silently placed on only one side", () => { + const base = doc("a: 1\nb: 2", "Body\n"); + const local = doc("a: 1\nc: 3\nb: 2", "Body\n"); + const remote = doc("a: 1\nb: 2\nc: 3", "Body\n"); + assert.equal(merge(base, local, remote).clean, false); +}); + test("changes to a closing fence's line ending are not silently discarded", () => { const base = doc("status: open", "Body\n"); const local = doc("status: done", "Body\n"); diff --git a/test/syncPreview.test.ts b/test/syncPreview.test.ts index f4ea88e..a4de31f 100644 --- a/test/syncPreview.test.ts +++ b/test/syncPreview.test.ts @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; import type { MirrorSyncPlan } from "@mdbase-dev/connect-sync/mirror"; -import { previewFromPlan, syncPlanSafety } from "../src/syncPreview"; +import { actionEntry, previewFromPlan, syncPlanSafety } from "../src/syncPreview"; function plan(overrides: Partial = {}): MirrorSyncPlan { return { @@ -259,6 +259,23 @@ const deleteLocal = (path: string): MirrorSyncPlan["actions"][number] => ({ reason: "remote_change", }); +test("destructive transfer details name where the deletion or rename happens", () => { + assert.equal(actionEntry(deleteLocal("notes/gone.md")).detail, "Move this device's copy to trash."); + assert.equal(actionEntry({ + command: "delete_remote", action_id: "delete-hosted", depends_on: [], target: ref("record", "notes/gone.md"), + expected_remote: { state: "absent" }, expected_local: { state: "absent" }, idempotency_key: "delete-hosted", reason: "local_change", + }).detail, "Delete from Connect."); + for (const command of ["move_local", "move_remote"] as const) { + const action = { + command, action_id: command, depends_on: [], source: ref("record", "notes/old.md"), target_path: "notes/new.md", + expected_source_owner: { state: "absent" }, expected_target_owner: { state: "absent" }, reason: "remote_change", + } as MirrorSyncPlan["actions"][number]; + assert.equal(actionEntry(action).detail, command === "move_local" + ? "Rename on this device from notes/old.md." + : "Rename in Connect from notes/old.md."); + } +}); + test("deletions, conflicts, attachment uploads and large transfers sync without review", () => { const deletion = previewFromPlan(plan({ actions: [deleteLocal("notes/gone.md")] })); assert.deepEqual(syncPlanSafety(deletion), { safe: true, reasons: [] }); diff --git a/test/syncReliability.test.ts b/test/syncReliability.test.ts index 4adb822..a04728e 100644 --- a/test/syncReliability.test.ts +++ b/test/syncReliability.test.ts @@ -6,11 +6,13 @@ import { MemoryAuthority, type SyncTransport } from "@mdbase-dev/connect-sync"; import { MemoryMirrorBlobStore, MemoryMirrorStateStore, + type MirrorState, WritableDirectoryMirror, } from "@mdbase-dev/connect-sync/mirror"; import type { MirrorEnrollmentClient } from "@mdbase-dev/connect-sync/enrollment"; -import { ConnectSyncController, ObsidianMirrorFileSystem, type MirrorProfile } from "../src/connectSync"; +import { ConnectSyncController, normalizeMirrorProfile, ObsidianMirrorFileSystem, type MirrorProfile } from "../src/connectSync"; import { MemoryVault } from "./memoryVault"; +import { SyncSession } from "../src/syncSession"; /** Enforces Obsidian's SecretStorage ID rule, which the plugin must respect. */ class MemorySecrets { @@ -278,8 +280,71 @@ test("the mirror's own writes are recognised as echoes, not edits", async () => const { preview } = await controller.inspect(); await controller.sync(preview); assert.equal(vault.read("notes/a.md")?.endsWith("a\n"), true); - assert.equal(controller.isEngineWrite("notes/a.md"), true); - assert.equal(controller.isEngineWrite("notes/other.md"), false); + assert.equal(controller.consumeEngineWrite("notes/a.md"), true); + await edit(vault, "notes/a.md", "typed immediately after the download\n"); + assert.equal(controller.consumeEngineWrite("notes/a.md"), false, "the next edit event is not another echo just because it arrived within two seconds"); + assert.equal(controller.consumeEngineWrite("notes/other.md"), false); +}); + +test("text downloads cannot follow a TFile renamed while Vault.process is queued", async () => { + const vault = new MemoryVault(); + const file = await vault.create("note.md", "base\n"); + const fs = new ObsidianMirrorFileSystem(vault as never); + const process = vault.process.bind(vault); + vault.process = async (target, transform) => { + // Real Obsidian renames the TFile object in place, unlike MemoryVault.rename. + const entry = vault.files.get(target.path)!; + vault.files.delete(target.path); + target.path = "moved.md"; + vault.files.set(target.path, entry); + return process(target, transform); + }; + await assert.rejects(fs.write("note.md", "hosted update\n", "base\n"), (error: unknown) => + (error as { code?: string }).code === "sync_plan_stale"); + assert.equal(file.path, "moved.md"); + assert.equal(vault.read("moved.md"), "base\n", "the engine must not write through the moved object"); +}); + +test("a stale conditional text write does not reserve an echo for a user's edit", async () => { + const vault = new MemoryVault(); + await vault.create("note.md", "base\n"); + const writes: string[] = []; + const fs = new ObsidianMirrorFileSystem(vault as never, undefined, undefined, (path) => writes.push(path)); + const process = vault.process.bind(vault); + vault.process = async (file, transform) => { + await vault.modify(file, "user edit\n"); + return process(file, transform); + }; + await assert.rejects(fs.write("note.md", "hosted\n", "base\n"), (error: unknown) => + (error as { code?: string }).code === "sync_plan_stale"); + assert.deepEqual(writes, [], "an abandoned write must not hide the real modify event"); +}); + +test("receive-only UTF-8 repair cannot overwrite an edit queued before the Vault write", async () => { + const vault = new MemoryVault(); + await vault.createBinary("note.md", Uint8Array.of(0x80).buffer); + const fs = new ObsidianMirrorFileSystem(vault as never); + const modify = vault.modify.bind(vault); + const process = vault.process.bind(vault); + vault.modify = async (file, value) => { + await modify(file, "user repaired the note\n"); + await modify(file, value); + }; + vault.process = async (file, transform) => { + await modify(file, "user repaired the note\n"); + return process(file, transform); + }; + await assert.rejects(fs.write("note.md", "hosted version\n"), (error: unknown) => + (error as { code?: string }).code === "sync_plan_stale"); + assert.equal(await fs.read("note.md"), "user repaired the note\n"); +}); + +test("receive-only UTF-8 repair still writes when the invalid text is unchanged", async () => { + const vault = new MemoryVault(); + await vault.createBinary("note.md", Uint8Array.of(0x80).buffer); + const fs = new ObsidianMirrorFileSystem(vault as never); + await fs.write("note.md", "hosted version\n"); + assert.equal(await fs.read("note.md"), "hosted version\n"); }); test("binary edits made while a download stream is consumed are not overwritten", async () => { @@ -336,6 +401,18 @@ test("a vault copied to another device or folder refuses to sync until it is set assert.equal((await original.syncOnce()).status, "applied"); }); +test("malformed stored selective-sync policies fail closed without losing the enrollment", async () => { + const hosted = new MemoryAuthority(); + const id = await collectionId(hosted); + const here = await device(hosted, id); + for (const policy of [null, false, "bad", [], {}, { file_classes: "image", excluded_folders: [] }, { file_classes: [], excluded_folders: null }]) { + const normalized = normalizeMirrorProfile({ ...here.profile(), selectiveSync: policy }); + assert.equal(normalized?.replicaId, here.replicaId, `policy ${JSON.stringify(policy)} retains credentials' identity`); + assert.deepEqual(normalized?.selectiveSync, { file_classes: [], excluded_folders: [] }); + } + for (const input of [null, [], "bad", { ...here.profile(), collectionId: 12 }]) assert.equal(normalizeMirrorProfile(input), null); +}); + test("profiles from before device ownership are claimed by the first device to open them", async () => { const hosted = new MemoryAuthority(); const id = await collectionId(hosted); @@ -498,6 +575,116 @@ test("reauthorization refuses to discard a batch prepared while browser approval assert.equal(here.vault.read("b.md"), "new note\n"); }); +test("every checkpoint-write boundary survives a quota error and a retry without losing files", async () => { + class FaultStore extends MemoryMirrorStateStore { + writes = 0; + failAt: number | null = null; + failures = 0; + override async write(state: MirrorState): Promise { + this.writes++; + if (this.writes === this.failAt) { + this.failures++; + throw new DOMException("Injected quota failure", "QuotaExceededError"); + } + return super.write(state); + } + } + for (let boundary = 1; boundary <= 20; boundary++) { + const hosted = new MemoryAuthority(); + hosted.seed(["a", "b", "c"].map((name) => ({ record_id: name, path: `${name}.md`, frontmatter: {}, body: `${name}\n`, types: [] }))); + const id = await collectionId(hosted); + const state = new FaultStore(); + const here = await device(hosted, id, { state }); + const there = otherDevice(hosted); + await here.syncOnce(); + await there.mirror.sync(); + await edit(there.vault, "b.md", "hosted edit\n"); + await there.mirror.sync(); + await edit(here.vault, "a.md", "local edit\n"); + await here.vault.create("d.md", "new local note\n"); + await here.vault.delete(here.vault.getAbstractFileByPath("c.md") as TFile); + state.failAt = state.writes + boundary; + const session = new SyncSession(here.controller, here.profile, null); + let result = await session.autoSync(); + state.failAt = null; + for (let retry = 0; retry < 8 && !["applied", "up_to_date"].includes(result); retry++) result = await session.syncNow(); + assert.ok(["applied", "up_to_date"].includes(result), `write boundary ${boundary}: ${result}, ${session.state.problem?.message}`); + await session.syncNow(); + await there.mirror.sync(); + for (const vault of [here.vault, there.vault]) { + assert.equal(vault.read("a.md"), "local edit\n", `write boundary ${boundary}`); + assert.equal(vault.read("b.md"), "hosted edit\n", `write boundary ${boundary}`); + assert.equal(vault.read("c.md"), null, `write boundary ${boundary}`); + assert.equal(vault.read("d.md"), "new local note\n", `write boundary ${boundary}`); + } + assert.equal((await state.read())?.batch, undefined, `write boundary ${boundary}: no wedged batch`); + here.controller.dispose(); + } +}); + +test("offline edit bursts converge despite intermittent quota errors, with every latest field edit intact", async () => { + const seeds = Number(process.env.MDBASE_RELIABILITY_SEEDS ?? 3); + const offset = Number(process.env.MDBASE_RELIABILITY_SEED_OFFSET ?? 0); + for (let seed = offset + 1; seed <= offset + seeds; seed++) { + let randomState = seed; + const randomIndex = (count: number) => { + randomState = (Math.imul(randomState, 1664525) + 1013904223) >>> 0; + return Math.floor(randomState / 2 ** 32 * count); + }; + const hosted = new MemoryAuthority(); + const count = 16; + hosted.seed(Array.from({ length: count }, (_, index) => ({ + record_id: `n${index}`, path: `notes/n${index}.md`, frontmatter: { left: 0, right: 0 }, body: "Body\n", types: [], + }))); + const id = await collectionId(hosted); + const state = new MemoryMirrorStateStore(); + const here = await device(hosted, id, { state }); + const there = otherDevice(hosted); + const session = new SyncSession(here.controller, here.profile, null); + await here.syncOnce(); + await there.mirror.sync(); + const left = new Array(count).fill(0); + const right = new Array(count).fill(0); + for (let editNumber = 1; editNumber <= 200; editNumber++) { + const localIndex = randomIndex(count); + const remoteIndex = randomIndex(count); + const localPath = `notes/n${localIndex}.md`; + const remotePath = `notes/n${remoteIndex}.md`; + left[localIndex] = editNumber; + right[remoteIndex] = editNumber; + await edit(here.vault, localPath, here.vault.read(localPath)!.replace(/left: \d+/, `left: ${editNumber}`)); + await edit(there.vault, remotePath, there.vault.read(remotePath)!.replace(/right: \d+/, `right: ${editNumber}`)); + } + await there.mirror.sync(); + if (seed % 2 === 0) { + const quotaBoundary = randomIndex(12) + 1; + let writes = 0; + const write = state.write.bind(state); + state.write = async (next) => { + if (++writes === quotaBoundary) throw new DOMException("Intermittent quota error", "QuotaExceededError"); + return write(next); + }; + } + for (let round = 0; round < 8; round++) { + const result = await session.autoSync(); + assert.ok(["applied", "up_to_date", "pending", "failed", "needs_review"].includes(result), `seed ${seed}: ${result}`); + if (["applied", "up_to_date"].includes(result) && !session.state.status?.conflicts.length + && !session.state.preview?.plan.actions.length) break; + } + await there.mirror.sync(); + for (let index = 0; index < count; index++) { + const path = `notes/n${index}.md`; + const document = here.vault.read(path)!; + assert.match(document, new RegExp(`left: ${left[index]}\\n`), `seed ${seed}: latest local edit at ${path}`); + assert.match(document, new RegExp(`right: ${right[index]}\\n`), `seed ${seed}: latest hosted edit at ${path}`); + assert.equal(there.vault.read(path), document, `seed ${seed}: devices agree at ${path}`); + } + assert.equal((await here.controller.status())?.conflicts.length, 0); + assert.equal((await here.controller.status())?.pending, 0); + here.controller.dispose(); + } +}); + test("overlapping operations share one token renewal instead of revoking each other's token", async () => { const hosted = new MemoryAuthority(); const id = await collectionId(hosted); diff --git a/test/syncScheduler.test.ts b/test/syncScheduler.test.ts index b04567c..ff9426c 100644 --- a/test/syncScheduler.test.ts +++ b/test/syncScheduler.test.ts @@ -196,6 +196,32 @@ test("returning to the app checks at once; in the background it checks rarely", assert.ok(h.calls.probe > hiddenProbes, "coming back to the front checks immediately"); }); +test("a settings change requests inspection even when the remote cursor did not advance", async () => { + const h = harness(); + h.scheduler.start(); + await h.clock.advance(0); + assert.equal(h.calls.autoSync, 1); + // Enabling an attachment class changes the local projection, not the + // authority head. A change-feed probe cannot discover the required rebuild. + h.scheduler.requestSoon(); + await h.clock.advance(0); + assert.equal(h.calls.autoSync, 2, "inspect the new scope immediately, without waiting for a note edit or the safety net"); +}); + +test("turning automatic sync back on syncs edits already observed while it was off", async () => { + let automatic = false; + const h = harness({ automatic: () => automatic }); + h.scheduler.start(); + await h.clock.advance(0); + h.scheduler.noteLocalChange(); + await h.clock.advance(SYNC_TIMING.localQuietMs); + assert.equal(h.calls.refresh, 2, "manual mode has already consumed the edit trigger to refresh status"); + automatic = true; + h.scheduler.requestSoon(); + await h.clock.advance(0); + assert.equal(h.calls.autoSync, 1, "enabling automatic sync catches up without needing another edit"); +}); + test("with automatic sync off, the scheduler only keeps status fresh", async () => { const h = harness({ automatic: () => false }); h.scheduler.start(); @@ -208,6 +234,27 @@ test("with automatic sync off, the scheduler only keeps status fresh", async () assert.equal(h.calls.autoSync, 0); }); +test("a rejected automatic run reports the failure and keeps retrying instead of escaping the timer", async () => { + let attempts = 0; + let reported = 0; + const h = harness({ + autoSync: async () => { + attempts++; + if (attempts === 1) throw new NetworkError("network_unreachable", "offline"); + return "applied"; + }, + reportProblem: () => { reported++; }, + }); + h.scheduler.start(); + // tick's public promise must absorb failures just like its timer callback. + await h.scheduler.tick(); + assert.equal(reported, 1); + assert.equal(h.retryAt(), SYNC_TIMING.retryBaseMs); + await h.clock.advance(SYNC_TIMING.retryBaseMs); + assert.ok(attempts >= 2, "the pending run is retried"); + assert.equal(h.retryAt(), null); +}); + test("a run that finds sync busy tries again shortly and keeps the pending edits", async () => { const h = harness(); h.setResult("busy"); @@ -218,6 +265,16 @@ test("a run that finds sync busy tries again shortly and keeps the pending edits assert.equal(h.calls.autoSync, 2); }); +test("a bounded run with work remaining gets a prompt follow-up without another vault event", async () => { + const h = harness(); + h.setResult("pending"); + h.scheduler.start(); + await h.clock.advance(0); + h.setResult("applied"); + await h.clock.advance(2_000); + assert.equal(h.calls.autoSync, 2, "local work left by a bounded run must not wait for the safety net"); +}); + test("a trigger that fires while a sync is running is not lost, and later syncs still happen", async () => { // Regression: a timer firing mid-run left a stale due time that made every // later schedule() think a timer was already pending, so sync stopped forever. diff --git a/test/syncSession.test.ts b/test/syncSession.test.ts index 9210f55..d1aa729 100644 --- a/test/syncSession.test.ts +++ b/test/syncSession.test.ts @@ -7,7 +7,7 @@ import { SyncSession } from "../src/syncSession"; import type { AutoResolution } from "../src/connectSync"; const digest = `sha256:${"4".repeat(64)}`; -const profile = { collectionId: "c1", name: "Notes" }; +const profile = { collectionId: "c1", replicaId: "r1", name: "Notes" }; function status(overrides: Partial = {}): MirrorStatus { return { @@ -110,11 +110,16 @@ function harness(initial: MdbaseSyncPreview, options: HarnessOptions = {}) { const history = { list: () => runs, append: async (run: SyncHistoryRun) => { runs.push(run); }, - remove: async () => undefined, + acknowledge: async () => undefined, clear: async () => undefined, }; - const session = new SyncSession(controller as never, () => profile as never, history); - return { session, controller, applied, runs, resolveCalls: () => resolveCalls, setNext: (preview: MdbaseSyncPreview) => { next = preview; } }; + let currentProfile: typeof profile | null = profile; + const session = new SyncSession(controller as never, () => currentProfile as never, history); + return { + session, controller, applied, runs, resolveCalls: () => resolveCalls, + setNext: (preview: MdbaseSyncPreview) => { next = preview; }, + setProfile: (next: typeof profile | null) => { currentProfile = next; }, + }; } test("progress and unrelated updates do not rescan a large plan's consent policy", () => { @@ -190,6 +195,17 @@ test("a plan that changed underneath is inspected again and applied, not shown a assert.equal(session.state.problem, null); }); +test("continually stale plans request a follow-up instead of claiming the vault is up to date", async () => { + const h = harness(previewFromPlan(plan([write("a.md")])), { + outcomes: Array.from({ length: 4 }, () => ({ status: "stale" })), + }); + assert.equal(await h.session.autoSync(), "pending"); + assert.equal(h.applied.length, 4, "one attempt remains bounded so the vault stays responsive"); + assert.equal(h.session.state.problem, null, "a changing plan is routine, not a defect"); + assert.ok(h.session.state.preview?.plan.actions.length); + assert.equal(await h.session.autoSync(), "applied", "a later attempt can finish"); +}); + test("a failure recorded by the engine is a problem, and an offline one is retried quietly", async () => { const offline = harness(previewFromPlan(plan([write("a.md")])), { outcomes: [{ status: "failed", failure: { code: "network_unreachable", message: "offline" } }], @@ -219,6 +235,26 @@ test("conflicts are settled after a sync and the settled files synced in the sam assert.ok(runs.some((run) => run.summary === "Merged edits to a.md")); }); +test("a failed conflict settlement remains a failed sync eligible for retry", async () => { + const conflict = { entity: "record", object_id: "r1", decision_id: "d1", path: "a.md", kind: "conflicted", message: "c" } as const; + const h = harness(previewFromPlan(plan([])), { conflicts: [conflict] }); + h.controller.autoResolveConflicts = async () => { + throw Object.assign(new Error("offline while loading conflict versions"), { code: "network_unreachable" }); + }; + assert.equal(await h.session.syncNow(), "failed"); + assert.equal(h.session.state.problem?.kind, "offline"); + assert.notEqual(h.session.state.message, "Already up to date."); +}); + +test("an unresolved conflict never reports Already up to date", async () => { + const conflict = { entity: "record", object_id: "r1", decision_id: "d1", path: "a.md", kind: "conflicted", message: "refused" } as const; + const h = harness(previewFromPlan(plan([])), { + conflicts: [conflict], resolutions: [{ path: "a.md", outcome: "unresolved", reason: "Connect refused this change." }], + }); + assert.equal(await h.session.syncNow(), "needs_review"); + assert.notEqual(h.session.state.message, "Already up to date."); +}); + test("automatic sync waits while paused or while Connect needs approval", async () => { const { session, applied } = harness(previewFromPlan(plan([write("a.md")]))); session.cancel(); @@ -264,6 +300,38 @@ test("reconnect reports when Connect needs a fresh approval instead of failing", assert.equal(session.state.busy, false); }); +test("a status request from a retired replica cannot overwrite the reauthorized session", async () => { + const h = harness(previewFromPlan(plan([]))); + let release!: () => void; + h.controller.status = () => new Promise((resolve) => { release = () => resolve(status({ cursor: 99 })); }); + const refreshing = h.session.refreshStatus(); + h.setProfile({ ...profile, replicaId: "r2" }); + h.session.update({ status: status({ cursor: 4 }) }); + release(); + assert.equal(await refreshing, null); + assert.equal(h.session.state.status?.cursor, 4); +}); + +test("inspection finishing after disconnect cannot restore the old preview or problems", async () => { + const h = harness(previewFromPlan(plan([write("a.md")]))); + const inspect = h.controller.inspect; + let release!: () => void; + h.controller.inspect = async () => { + h.controller.inspect = inspect; + await new Promise((resolve) => { release = resolve; }); + return inspect(); + }; + const running = h.session.syncNow(); + h.setProfile(null); + h.session.reset(); + release(); + await running; + assert.equal(h.session.state.status, null); + assert.equal(h.session.state.preview, null); + assert.equal(h.session.state.problem, null); + assert.equal(h.applied.length, 0); +}); + test("listeners hear every state change", async () => { const { session } = harness(previewFromPlan(plan([write("a.md")]))); let calls = 0; diff --git a/test/workspaceView.test.ts b/test/workspaceView.test.ts index 5cf2225..b46accb 100644 --- a/test/workspaceView.test.ts +++ b/test/workspaceView.test.ts @@ -55,7 +55,10 @@ function fixture(connected = false) { const history = { list: () => historyRuns, append: async (run: SyncHistoryRun) => { historyRuns.push(run); }, - remove: async (id: string) => { historyRuns.splice(historyRuns.findIndex((run) => run.id === id), 1); }, + acknowledge: async (id: string) => { + const run = historyRuns.find((run) => run.id === id); + if (run) run.needsAcknowledgement = false; + }, clear: async () => { historyRuns.length = 0; }, }; let settingsOpened = 0; @@ -84,7 +87,7 @@ function fixture(connected = false) { } as Record, sync: null as unknown as SyncSession, }; - host.sync = new SyncSession(host.connectSync as never, () => profile as never, history); + host.sync = new SyncSession(host.connectSync as never, () => host.getMirrorProfile() as never, history); const view = new MdbaseWorkspaceView({ containerEl: root, app: { vault: { getName: () => "Notes", getAbstractFileByPath: () => null, getAllLoadedFiles: () => [], createFolder: async () => undefined, create: async () => ({ path: "export.txt" }) } } } as never, host as never); const views = view as unknown as { types: { dirty: boolean; model: TypeModel; originalModel: TypeModel; selectedPath: string }; @@ -133,6 +136,29 @@ function button(root: HTMLElement, label: string): HTMLButtonElement { return result; } +test("Sync and Issues refreshes do not parse all records or run type impact scans", async () => { + const f = fixture(true); + let recordLoads = 0; + Object.assign(f.host, { + loadWorkspaceSchema: async () => ({ config: { spec_version: "0.3.0" }, types: new Map(), contracts: new Map() }), + loadCollectionRecords: async () => { recordLoads++; return []; }, + }); + await f.view.refresh(); + assert.equal(recordLoads, 0, "Sync does not consume collection records"); + f.state.destination = "issues"; + await f.view.refresh(); + assert.equal(recordLoads, 0, "Issues does not consume collection records either"); + let pending: Promise | null = null; + const refresh = f.view.refresh.bind(f.view); + f.view.refresh = (...args) => (pending = refresh(...args)); + f.view.showDestination("types"); + assert.ok(pending, "switching to Types must load its record statistics"); + await pending; + assert.equal(recordLoads, 1); + await f.view.onClose(); + f.dom.window.close(); +}); + test("transfer notifications coalesce renders, keep completion immediate, and cancel on close", async () => { const f = fixture(true); await f.view.onOpen(); @@ -232,6 +258,92 @@ test("enrollment exposes only essential controls but retains the upload warning f.dom.window.close(); }); +test("signing in again exposes approval and cancellation, then clears the used link", async () => { + const f = fixture(true); + f.dom.window.open = () => null; + Object.assign(f.host.connectSync, { + reconnect: async () => { throw Object.assign(new Error("Approval needed"), { code: "mirror_credentials_missing" }); }, + reauthorize: async (callbacks: { signal: AbortSignal; onVerification(value: { verificationUri: string }): void; onStatus(value: { state: string }): void }) => { + callbacks.onVerification({ verificationUri: "https://connect.example/approve/temporary" }); + callbacks.onStatus({ state: "waiting_for_approval" }); + await new Promise((_resolve, reject) => callbacks.signal.addEventListener("abort", () => reject(new DOMException("Cancelled", "AbortError")))); + }, + }); + const pending = f.view.reconnectCollection(); + await settle(); + const link = f.root.querySelector(".mdbase-approval-link a"); + assert.equal(link?.href, "https://connect.example/approve/temporary"); + assert.equal(link?.rel, "noopener noreferrer"); + assert.ok(button(f.root, "Stop waiting")); + assert.doesNotMatch(f.text(), /Sign in again|Sync now/); + button(f.root, "Stop waiting").click(); + await pending; + assert.equal(f.root.querySelector(".mdbase-approval-link"), null); + assert.match(f.text(), /Cancelled/); + assert.ok(button(f.root, "Sign in again")); + f.dom.window.close(); +}); + +test("enrollment can be cancelled before verification and never retains a failed approval link", async () => { + const f = fixture(); + f.dom.window.open = () => null; + let callbacks: { onVerification(value: { verificationUri: string }): void } | null = null; + let rejectEnrollment: (error: Error) => void = () => assert.fail("Enrollment not started"); + Object.assign(f.host.connectSync, { + enroll: async (_input: unknown, cb: NonNullable) => { + callbacks = cb; + await new Promise((_resolve, reject) => { rejectEnrollment = reject; }); + }, + }); + f.state.render(); + button(f.root, "Connect").click(); + assert.ok(button(f.root, "Stop waiting"), "initial request can be stopped too"); + assert.equal(f.root.querySelector("input[data-focus-key='form-device-name']"), null, "no editable setup while waiting"); + assert.ok(callbacks); + (callbacks as { onVerification(value: { verificationUri: string }): void }).onVerification({ verificationUri: "https://connect.example/approve/expired" }); + assert.ok(f.root.querySelector(".mdbase-approval-link a")); + rejectEnrollment(new Error("Approval expired")); + await settle(); + assert.equal(f.root.querySelector(".mdbase-approval-link"), null); + assert.equal(button(f.root, "Connect").disabled, false); + assert.match(f.text(), /Approval expired/); + f.dom.window.close(); +}); + +test("connecting starts a download-only first sync but stops before uploading local notes", async () => { + for (const command of ["write_local", "put_remote"]) { + const f = fixture(); + let applied = 0; + const status = { state: "up_to_date", conflicts: [], local_issues: [] }; + const firstPreview = { + phase: "initial", plan: { kind: "initial", actions: [{ command }], issues: [], summary: { blocking_issues: 0 } }, + entries: [{ path: "Note.md", direction: command === "write_local" ? "download" : "upload", action: "create", detail: "Transfer note" }], collisions: [], local_issues: [], + }; + Object.assign(f.host.connectSync, { + enroll: async () => { + f.host.getMirrorProfile = () => ({ name: "Project notes", collectionId: "connected", mode: "read_write", controlUrl: "https://connect.example", selectiveSync: { file_classes: [], excluded_folders: [] } }); + }, + inspect: async () => ({ status, preview: applied ? { + ...firstPreview, phase: "incremental", entries: [], plan: { ...firstPreview.plan, kind: "incremental", actions: [] }, + } : firstPreview }), + sync: async () => { applied++; return { status: "applied", applied: 1, pending: 0 }; }, + }); + f.state.render(); + button(f.root, "Connect").click(); + await settle(); + if (command === "write_local") { + assert.equal(applied, 1, "copying from Connect already consents to ordinary downloads"); + assert.match(f.text(), /Sync complete/); + assert.doesNotMatch(f.text(), /Review .* before syncing|Waiting for approval/); + } else { + assert.equal(applied, 0, "existing local notes must wait for the first-sync review"); + assert.match(f.text(), /Connected.*Review 1 item.*before syncing/); + assert.ok(button(f.root, "Sync 1 change")); + } + f.dom.window.close(); + } +}); + test("type editing has one save location, optional sections, and an expandable review", () => { const f = fixture(); f.state.destination = "types"; @@ -294,6 +406,44 @@ test("restoring an empty YAML draft preserves the unsaved empty text", async () f.dom.window.close(); }); +test("destination tabs expose a labelled panel and native roving keyboard navigation", async () => { + const f = fixture(true); + f.state.destination = "issues"; + f.state.render(); + const selected = () => f.root.querySelector("[role='tab'][aria-selected='true']")!; + assert.equal(f.root.querySelectorAll("[role='tab'][tabindex='0']").length, 1); + assert.equal(f.root.querySelectorAll("[role='tab'][tabindex='-1']").length, 2); + const panel = f.root.querySelector("[role='tabpanel']")!; + assert.ok(panel); + assert.equal(panel.getAttribute("aria-labelledby"), selected().id); + assert.equal(selected().getAttribute("aria-controls"), panel.id); + selected().focus(); + for (const [key, destination] of [["ArrowRight", "types"], ["ArrowLeft", "issues"], ["Home", "types"], ["End", "issues"], ["ArrowLeft", "sync"]]) { + const event = new f.dom.window.KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }); + selected().dispatchEvent(event); + assert.equal(event.defaultPrevented, true); + assert.equal(f.state.destination, destination); + assert.equal(f.dom.window.document.activeElement, selected()); + assert.equal(selected().tabIndex, 0); + } + await settle(); + f.dom.window.close(); +}); + +test("background sync badge updates preserve keyboard focus on the destination tabs", async () => { + const f = fixture(true); + f.state.destination = "issues"; + Object.assign(f.host, { loadWorkspaceSchema: async () => null }); + await f.view.onOpen(); + const tab = f.root.querySelector("[data-focus-key='destination-issues']")!; + tab.focus(); + f.host.sync.update({ status: { state: "attention", conflicts: [{ path: "note.md" }], local_issues: [] } as never }); + assert.equal(f.dom.window.document.activeElement?.getAttribute("data-focus-key"), "destination-issues"); + assert.notEqual(f.dom.window.document.activeElement, tab, "focus follows the replacement tab"); + await f.view.onClose(); + f.dom.window.close(); +}); + test("empty Issues has no redundant filters, counts, or empty panels", () => { const f = fixture(); f.state.destination = "issues"; @@ -659,6 +809,47 @@ test("Issues grouped by rule offer one bulk fix and jump to the rule's field", a f.dom.window.close(); }); +test("sync actions and filters preserve focus across progress and review renders", () => { + const f = fixture(true); + f.state.render(); + button(f.root, "Sync now").focus(); + f.state.render(); + assert.equal(f.dom.window.document.activeElement, button(f.root, "Sync now")); + f.host.sync.update({ progress: { phase: "uploading", completed: 1, total: 10 } as never }); + f.state.render(); + button(f.root, "Stop").focus(); + f.host.sync.update({ progress: { phase: "uploading", completed: 2, total: 10 } as never }); + f.state.render(); + assert.equal(f.dom.window.document.activeElement, button(f.root, "Stop")); + assert.equal(f.root.querySelector("progress")?.getAttribute("aria-label"), "Sync progress"); + f.host.sync.update({ progress: null }); + f.state.mirrorPreview = { + phase: "incremental", plan: { actions: [{}], issues: [], summary: { blocking_issues: 0 } }, + entries: [{ path: "Plan.md", direction: "download", action: "update", detail: "Download change" }], collisions: [], local_issues: [], + }; + f.state.render(); + const filter = f.root.querySelector("[aria-label='Filter transfers']")!; + filter.focus(); + filter.value = "download"; + filter.dispatchEvent(new f.dom.window.Event("change")); + assert.equal(f.dom.window.document.activeElement?.getAttribute("aria-label"), "Filter transfers"); + f.dom.window.close(); +}); + +test("quoted transfer paths cannot break focus restoration while comparing changes", () => { + const f = fixture(true); + (f.view as unknown as { app: { vault: { getAbstractFileByPath(path: string): unknown } } }).app.vault.getAbstractFileByPath = () => ({}); + f.state.mirrorPreview = { + phase: "incremental", plan: { actions: [{}], issues: [], summary: { blocking_issues: 0 } }, + entries: [{ kind: "document", path: 'Notes/Review "draft".md', direction: "download", action: "update", detail: "Download change", recordId: "r1" }], collisions: [], local_issues: [], + }; + f.state.render(); + button(f.root, "Compare").focus(); + assert.doesNotThrow(() => f.state.render()); + assert.equal(f.dom.window.document.activeElement, button(f.root, "Compare")); + f.dom.window.close(); +}); + test("pending record updates can be compared before syncing", async () => { const f = fixture(true); Object.assign(f.state, { mirrorStatus: { state: "changes_waiting", conflicts: [], local_issues: [] } }); @@ -680,6 +871,29 @@ test("pending record updates can be compared before syncing", async () => { f.dom.window.close(); }); +test("collapsed history does not construct hidden transfer ledgers", () => { + const f = fixture(true); + const at = new Date().toISOString(); + f.historyRuns.push(...Array.from({ length: 20 }, (_, index) => ({ + id: `large-${index}`, collectionId: "hidden-collection-id", startedAt: at, finishedAt: at, outcome: "applied", + files: Array.from({ length: 250 }, (_, file) => ({ path: `${index}/${file}.md`, kind: "document" as const, + direction: "download" as const, action: "create" as const, status: "completed" as const, at })), + }))); + f.state.render(); + assert.equal(f.root.querySelectorAll(".mdbase-history-run").length, 0, "closed History needs only its heading"); + const history = f.root.querySelector("[data-disclosure='sync-activity']")!; + history.open = true; + history.dispatchEvent(new f.dom.window.Event("toggle")); + assert.equal(f.root.querySelectorAll(".mdbase-history-run").length, 10); + assert.equal(f.root.querySelectorAll(".mdbase-history-files .mdbase-transfer-row").length, 0, + "closed runs need only summaries, not 2,500 hidden rows"); + const run = f.root.querySelector("[data-disclosure='history-run-large-0']")!; + run.open = true; + run.dispatchEvent(new f.dom.window.Event("toggle")); + assert.equal(f.root.querySelectorAll(".mdbase-history-files .mdbase-transfer-row").length, 250); + f.dom.window.close(); +}); + test("sync history lists runs, expands to their files and filters by path", () => { const f = fixture(true); const at = new Date().toISOString(); @@ -712,6 +926,93 @@ test("sync history lists runs, expands to their files and filters by path", () = f.dom.window.close(); }); +test("pinned conflict events expose their retained copy without empty history controls", () => { + const f = fixture(true); + const at = new Date().toISOString(); + f.historyRuns.push({ + id: "conflict-event", collectionId: "hidden-collection-id", startedAt: at, finishedAt: at, outcome: "event", files: [], + summary: "Kept both versions of Plan.md", path: "Tasks/Plan.md", needsAcknowledgement: true, + message: "This device's version was saved as Tasks/Plan (local conflict copy).md.", tone: "attention", + }); + const opened: string[] = []; + Object.assign(f.host, { openFileByPath: async (path: string) => { opened.push(path); } }); + (f.view as unknown as { app: { vault: { getAbstractFileByPath(path: string): unknown } } }).app.vault.getAbstractFileByPath = () => ({}); + f.state.render(); + assert.match(f.text(), /local conflict copy/); + assert.equal(f.root.querySelector("[data-focus-key='history-search']"), null); + assert.doesNotMatch(f.text(), /No completed syncs|Clear history/); + button(f.root, "Tasks/Plan.md").click(); + assert.deepEqual(opened, ["Tasks/Plan.md"]); + const details = f.root.querySelector("[data-disclosure='history-event-conflict-event']")!; + assert.ok(details.open); + details.open = false; + f.state.render(); + assert.doesNotMatch(f.text(), /local conflict copy/); + assert.equal(f.root.querySelector("[data-disclosure='history-event-conflict-event']")?.open, false); + f.dom.window.close(); +}); + +test("dismissing a conflict event unpins it without erasing its history", async () => { + const f = fixture(true); + const at = new Date().toISOString(); + f.historyRuns.push({ + id: "conflict-event", collectionId: "hidden-collection-id", startedAt: at, finishedAt: at, outcome: "event", files: [], + summary: "Kept both versions of Plan.md", path: "Tasks/Plan.md", needsAcknowledgement: true, + message: "This device's version was saved as Tasks/Plan (local conflict copy).md.", tone: "attention", + }); + f.state.render(); + button(f.root, "Dismiss").focus(); + button(f.root, "Dismiss").click(); + await settle(); + f.state.render(); + assert.equal(f.dom.window.document.activeElement?.getAttribute("data-focus-key"), "disclosure-history-event-conflict-event"); + assert.equal(f.historyRuns.length, 1, "dismiss acknowledges a notice, not deletion of the audit trail"); + assert.equal(f.historyRuns[0].needsAcknowledgement, false); + assert.match(f.text(), /Kept both versions of Plan.md/); + assert.doesNotMatch(f.text(), /Dismiss/); + assert.ok(button(f.root, "Clear history"), "explicit Clear can remove acknowledged history"); + f.dom.window.close(); +}); + +test("history write failures are visible rather than unhandled UI rejections", async () => { + const f = fixture(true); + const at = new Date().toISOString(); + f.historyRuns.push({ + id: "event", collectionId: "hidden-collection-id", startedAt: at, finishedAt: at, outcome: "event", files: [], + summary: "Collection reconnected", tone: "success", + }); + f.host.sync.clearHistory = async () => { throw new Error("History could not be saved"); }; + f.state.render(); + f.root.querySelector("[data-disclosure='sync-activity']")!.open = true; + f.state.render(); + button(f.root, "Clear history").click(); + await settle(); + assert.match(f.text(), /History could not be saved/); + assert.equal(button(f.root, "Clear history").disabled, false); + f.dom.window.close(); +}); + +test("ordinary history event details retain disclosure and keyboard focus on redraw", () => { + const f = fixture(true); + const at = new Date().toISOString(); + f.historyRuns.push({ + id: "reconnect", collectionId: "hidden-collection-id", startedAt: at, finishedAt: at, outcome: "event", files: [], + summary: "Collection reconnected", message: "Credentials were renewed and the checkpoint was preserved.", tone: "success", + }); + f.state.render(); + f.root.querySelector("[data-disclosure='sync-activity']")!.open = true; + f.state.render(); + const details = f.root.querySelector("[data-disclosure='history-event-reconnect']")!; + assert.ok(details); + assert.equal(details.open, false); + details.open = true; + details.querySelector("summary")!.focus(); + f.state.render(); + assert.match(f.text(), /Credentials were renewed/); + assert.equal(f.dom.window.document.activeElement?.textContent, "Collection reconnected"); + f.dom.window.close(); +}); + test("expanding a field adds a collapse action without inserting a filter above the list", async () => { const f = typesFixture(); await f.view.selectType("_types/task.md"); @@ -761,7 +1062,9 @@ test("a plan held for review says why, offers to apply it, and badges the Sync t collisions: [], local_issues: [], }; f.state.render(); - assert.match(f.text(), /Review needed: mirror rebuild/); + assert.match(f.root.querySelector(".mdbase-sync-heading")!.textContent!, /Review needed/); + assert.doesNotMatch(f.root.querySelector(".mdbase-sync-heading")!.textContent!, /Up to date/); + assert.equal(f.root.querySelector(".mdbase-review-reasons")?.textContent, "Mirror rebuild."); assert.ok(button(f.root, "Sync 1 change").classList.contains("mod-cta")); assert.equal(f.root.querySelector(".mdbase-nav-button.is-active .mdbase-count")?.textContent, "1"); f.dom.window.close();