diff --git a/docs/perf/probe-chromium-2026-10-02.json b/docs/perf/probe-chromium-2026-10-02.json new file mode 100644 index 0000000..9ad7b7c --- /dev/null +++ b/docs/perf/probe-chromium-2026-10-02.json @@ -0,0 +1,24 @@ +{ + "notes": 20000, + "state_bytes": 43275829, + "summary_bytes": 55, + "baseline": { + "calls": 10, + "total_ms": 596.6, + "mean_ms": 59.66, + "max_call_ms": 82, + "max_frame_gap_ms": 79.1, + "ticks": 14, + "full_reads": 10 + }, + "optimized": { + "calls": 100, + "total_ms": 8.9, + "mean_ms": 0.089, + "max_call_ms": 0.7, + "max_frame_gap_ms": 16.1, + "ticks": 1, + "full_reads": 0, + "summary_reads": 100 + } +} \ No newline at end of file diff --git a/docs/perf/ui-after-2026-10-02.json b/docs/perf/ui-after-2026-10-02.json new file mode 100644 index 0000000..5707fe9 --- /dev/null +++ b/docs/perf/ui-after-2026-10-02.json @@ -0,0 +1,56 @@ +{ + "mode": "current", + "files": 20052, + "coldOpen": { + "ms": 80.5, + "max_frame_gap_ms": 81.8, + "ticks": 2, + "record_loads": 0 + }, + "records": { + "ms": 485.1, + "max_frame_gap_ms": 27.5, + "ticks": 31, + "value": 20000 + }, + "progress": { + "ms": 129.1, + "max_frame_gap_ms": 16.3, + "ticks": 9, + "value": { + "renders": 1 + } + }, + "closedHistory": { + "ms": 3.3, + "max_frame_gap_ms": 16.1, + "ticks": 1, + "value": { + "rows": 0, + "nodes": 20 + } + }, + "summariesHistory": { + "ms": 11.7, + "max_frame_gap_ms": 16.1, + "ticks": 1, + "value": { + "rows": 0, + "nodes": 134 + } + }, + "trace": { + "long_tasks": 1, + "max_task_ms": 69.408, + "top_tasks_ms": [ + 69.408, + 33.592, + 16.251, + 11.275, + 8.91, + 8.832, + 8.62, + 8.34 + ] + } +} \ No newline at end of file diff --git a/docs/perf/ui-before-2026-10-02.json b/docs/perf/ui-before-2026-10-02.json new file mode 100644 index 0000000..ccd851d --- /dev/null +++ b/docs/perf/ui-before-2026-10-02.json @@ -0,0 +1,56 @@ +{ + "mode": "baseline", + "files": 20052, + "coldOpen": { + "ms": 453, + "max_frame_gap_ms": 461, + "ticks": 2, + "record_loads": 3 + }, + "records": { + "ms": 253.5, + "max_frame_gap_ms": 257, + "ticks": 2, + "value": 20000 + }, + "progress": { + "ms": 593.6, + "max_frame_gap_ms": 484.3, + "ticks": 9, + "value": { + "renders": 1000 + } + }, + "closedHistory": { + "ms": 238.6, + "max_frame_gap_ms": 241.5, + "ticks": 2, + "value": { + "rows": 2500, + "nodes": 27644 + } + }, + "summariesHistory": { + "ms": 217.3, + "max_frame_gap_ms": 220.5, + "ticks": 2, + "value": { + "rows": 2500, + "nodes": 27644 + } + }, + "trace": { + "long_tasks": 6, + "max_task_ms": 469.234, + "top_tasks_ms": [ + 469.234, + 453.834, + 253.73, + 240.661, + 218.629, + 69.817, + 26.01, + 6.686 + ] + } +} \ No newline at end of file diff --git a/docs/sync-perf-2026-10-02.md b/docs/sync-perf-2026-10-02.md new file mode 100644 index 0000000..e4211ae --- /dev/null +++ b/docs/sync-perf-2026-10-02.md @@ -0,0 +1,59 @@ +# Large-vault sync performance — 2026-10-02 + +All data was generated. No personal vault, LAB, staging or hosted authority was used. Browser evidence used an isolated Obsidian profile, a disposable 20k-note vault and CDP. Timings are single samples under simultaneous campaign load, not a throughput SLA. + +## The polling fix + +`ConnectSyncController.remoteChangesWaiting()` used to clone the complete IndexedDB mirror checkpoint before requesting one change-feed event. It now uses `IndexedDbMirrorStateStore.readCheckpoint()`: a cursor, scope epoch and recovery-required boolean stored alongside the full state in **the same transaction**. Clear removes both atomically. String state keys and array summary keys cannot collide, and no database-version upgrade is required. + +A full state read primes/repairs the projection once per adapter lifetime, covering state written by older plugins, stale projections after downgrades, and missing projections. Normal startup inspection already performs that read. Subsequent polls retrieve the tiny projection and verify existence with `getKey`, which does not clone documents. Injected/test state stores without this optional port retain their full-read fallback. + +Real Chromium/Obsidian, 20k generated notes: + +| Metric | Old full-state probe | New controller probe | +| --- | ---: | ---: | +| State / summary size | 43,275,829 bytes | 55 bytes | +| Mean per call | 59.66ms (10 calls) | 0.089ms (100 calls) | +| Slowest call | 82ms | 0.7ms | +| Largest 16ms timer gap | 79.1ms | 16.1ms | +| Full-state reads | 10 | 0 | + +Raw evidence: [`perf/probe-chromium-2026-10-02.json`](perf/probe-chromium-2026-10-02.json). The baseline reproduces the old read-plus-feed operation; the optimized measurement invokes the real controller with a generated IndexedDB state and an in-memory transport override. + +Regression coverage includes 20 polls against 20k records with zero full-state `get` calls; recovery/uninitialized short-circuit behaviour; stale legacy summary reconciliation; atomic rollback when the summary write or delete aborts; and existing state-store failure/restart tests. Full plugin tests (342) and lint pass. + +## Frontend responsiveness + +Earlier CDP comparison of the campaign baseline against the first frontend fixes: + +| Operation | Before | After | +| --- | ---: | ---: | +| Open Sync from a fresh view | 453ms / 3 record-load calls | 80.5ms / 0 record-load calls | +| Read 20k cached collection records: largest frame gap | 257ms | 27.5ms | +| 1,000 transfer notifications | 1,000 redraws / 484ms gap | 1 redraw / 16.3ms gap | +| Five closed-history redraws | 239ms / 2,500 hidden rows | 3.3ms / 0 rows | +| Five open-history summary redraws | 217ms / 2,500 hidden rows | 11.7ms / 0 hidden rows | + +The record scan takes longer overall (254ms → 485ms) because it yields to input/painting by time budget. That is deliberate. Completion, failures, auth and consent changes remain immediate; only transfer-only presentation notifications coalesce. Actual history disclosure toggles and opening one run's ledger were verified in Obsidian. + +Raw evidence: [`perf/ui-before-2026-10-02.json`](perf/ui-before-2026-10-02.json), [`perf/ui-after-2026-10-02.json`](perf/ui-after-2026-10-02.json). These frontend captures precede the second integration round and later glob/history/probe fixes. + +Initial event-path trace found low direct handler cost: 1,000 modify callbacks ~4.6ms; 1,000 editor-change callbacks ~5.3ms. The expensive work was deferred whole-vault scans and rendering, not per-keystroke event dispatch. + +## Other guarded hotspots + +- Receipt history lookup: 20k actions previously caused 200,030,000 action-id reads; indexing once bounds it to 40,000. +- Consent policy: 100 progress notifications on a 20k plan previously caused 4,040,000 command reads; immutable-preview reuse bounds it to 40,000. +- Portable path globs: a small adversarial segment/path fixture previously copied 516,133 suffix arrays. Iterative wildcard matching removes recursive explosion and call-stack growth; Unicode/classes retain semantics. 100k seeded differential cases matched the old implementation. Typical 200k matches improved ~189ms → ~92ms in Node. +- Intact large history logs no longer stringify every transfer again at startup; malformed/torn lines and pruning still trigger serialized repair. A 50k-file history regression guards that path. + +## Remaining SDK costs and reproduction + +``` +npm run test:unit +node --expose-gc --loader ./test/obsidian-loader.mjs scripts/profile-large-sync.mjs 10000 20000 50000 +``` + +The harness generates MemoryAuthority records and notes plus 50 unselected attachments. It measures initial/incremental review, paging/read counts, one-edit apply, heap deltas, full state write volume and fake-indexeddb clone/probe cost. Fake IndexedDB is not a disk-latency measurement. To compare a built SDK candidate, set `MDBASE_PROFILE_SDK_ROOT=/absolute/path/to/packages/sync`. + +One 20k-note edit still reads the entire vault during review and again during apply, and writes roughly 216MB of full checkpoint copies across five durable writes. At 50k notes that becomes ~541MB. Do not remove durability or trust mtime/size-only caches to hide this. A tested SDK proposal reuses hashes and canonical structural proofs only after comparing freshly read exact bytes with the common authority document; its patch and evidence are in the campaign lead's `reports/perf-sdk/` directory. Journal-store adoption remains a separate, recovery-sensitive improvement. diff --git a/docs/sync-ux-acceptance.md b/docs/sync-ux-acceptance.md index 8176390..0bc70fa 100644 --- a/docs/sync-ux-acceptance.md +++ b/docs/sync-ux-acceptance.md @@ -23,6 +23,6 @@ node scripts/test-sync-layout.cjs after-layout `MDBASE_UX_PLAYWRIGHT` can be omitted if Playwright is already resolvable. It is not a plugin runtime dependency. -The audit captures 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. +The audit captures 23 states at 1100px and 390px, in dark and light themes: healthy, long excluded-folder scope, local file issue, offline, sign-in, copied device, paused, unexpected failure, progress, first-sync review, deletion-burst review, rebuild, unresolved conflict (both versions present, local absent, or hosted absent), pinned conflict history, enrollment, and local upload, plus five sync problems viewed from Issues (where mobile needs an in-workspace indicator). Desktop sidebars are collapsed for realistic narrow panes. Assertions reject horizontal overflow, hidden sync problems when viewing another destination, and primary/dismiss targets below 44px in narrow panes. Long, unbroken paths are intentional. `*-checks.json` records the measured bounds; the command exits nonzero on a regression. 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 ffe00cc..15b8aa2 100644 --- a/main.js +++ b/main.js @@ -3,98 +3,98 @@ THIS IS A GENERATED/BUNDLED FILE BY ESBUILD if you want to view the source, please visit the github repository of this plugin */ -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 +var eE=Object.create;var Ma=Object.defineProperty;var tE=Object.getOwnPropertyDescriptor;var rE=Object.getOwnPropertyNames;var nE=Object.getPrototypeOf,iE=Object.prototype.hasOwnProperty;var cy=(r,e)=>()=>(r&&(e=r(r=0)),e);var k=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ly=(r,e)=>{for(var t in e)Ma(r,t,{get:e[t],enumerable:!0})},dy=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of rE(e))!iE.call(r,i)&&i!==t&&Ma(r,i,{get:()=>e[i],enumerable:!(n=tE(e,i))||n.enumerable});return r};var Wn=(r,e,t)=>(t=r!=null?eE(nE(r)):{},dy(e||!r||!r.__esModule?Ma(t,"default",{value:r,enumerable:!0}):t,r)),sE=r=>dy(Ma({},"__esModule",{value:!0}),r);var qs=k(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.regexpCode=se.getEsmExportName=se.getProperty=se.safeStringify=se.stringify=se.strConcat=se.addCodeArg=se.str=se._=se.nil=se._Code=se.Name=se.IDENTIFIER=se._CodeOrName=void 0;var Fs=class{};se._CodeOrName=Fs;se.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Jn=class extends Fs{constructor(e){if(super(),!se.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};se.Name=Jn;var Lt=class extends Fs{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((t,n)=>`${t}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((t,n)=>(n instanceof Jn&&(t[n.str]=(t[n.str]||0)+1),t),{})}};se._Code=Lt;se.nil=new Lt("");function py(r,...e){let t=[r[0]],n=0;for(;n{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.ValueScope=ft.ValueScopeName=ft.Scope=ft.varKinds=ft.UsedValueState=void 0;var ut=qs(),Ud=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Oa;(function(r){r[r.Started=0]="Started",r[r.Completed=1]="Completed"})(Oa||(ft.UsedValueState=Oa={}));ft.varKinds={const:new ut.Name("const"),let:new ut.Name("let"),var:new ut.Name("var")};var Da=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof ut.Name?e:this.name(e)}name(e){return new ut.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){var t,n;if(!((n=(t=this._parent)===null||t===void 0?void 0:t._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};ft.Scope=Da;var Na=class extends ut.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:n}){this.value=e,this.scopePath=(0,ut._)`.${new ut.Name(t)}[${n}]`}};ft.ValueScopeName=Na;var wE=(0,ut._)`\n`,Vd=class extends Da{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?wE:ut.nil}}get(){return this._scope}name(e){return new Na(e,this._newName(e))}value(e,t){var n;if(t.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:s}=i,o=(n=t.key)!==null&&n!==void 0?n:t.ref,a=this._values[s];if(a){let u=a.get(o);if(u)return u}else a=this._values[s]=new Map;a.set(o,i);let c=this._scope[s]||(this._scope[s]=[]),l=c.length;return c[l]=t.ref,i.setValue(t,{property:s,itemIndex:l}),i}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,ut._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},t,n)}_reduceValues(e,t,n={},i){let s=ut.nil;for(let o in e){let a=e[o];if(!a)continue;let c=n[o]=n[o]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,Oa.Started);let u=t(l);if(u){let d=this.opts.es5?ft.varKinds.var:ft.varKinds.const;s=(0,ut._)`${s}${d} ${l} = ${u};${this.opts._n}`}else if(u=i?.(l))s=(0,ut._)`${s}${u}${this.opts._n}`;else throw new Ud(l);c.set(l,Oa.Completed)})}return s}};ft.ValueScope=Vd});var U=k(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.or=Y.and=Y.not=Y.CodeGen=Y.operators=Y.varKinds=Y.ValueScopeName=Y.ValueScope=Y.Scope=Y.Name=Y.regexpCode=Y.stringify=Y.getProperty=Y.nil=Y.strConcat=Y.str=Y._=void 0;var re=qs(),Xt=Hd(),ln=qs();Object.defineProperty(Y,"_",{enumerable:!0,get:function(){return ln._}});Object.defineProperty(Y,"str",{enumerable:!0,get:function(){return ln.str}});Object.defineProperty(Y,"strConcat",{enumerable:!0,get:function(){return ln.strConcat}});Object.defineProperty(Y,"nil",{enumerable:!0,get:function(){return ln.nil}});Object.defineProperty(Y,"getProperty",{enumerable:!0,get:function(){return ln.getProperty}});Object.defineProperty(Y,"stringify",{enumerable:!0,get:function(){return ln.stringify}});Object.defineProperty(Y,"regexpCode",{enumerable:!0,get:function(){return ln.regexpCode}});Object.defineProperty(Y,"Name",{enumerable:!0,get:function(){return ln.Name}});var qa=Hd();Object.defineProperty(Y,"Scope",{enumerable:!0,get:function(){return qa.Scope}});Object.defineProperty(Y,"ValueScope",{enumerable:!0,get:function(){return qa.ValueScope}});Object.defineProperty(Y,"ValueScopeName",{enumerable:!0,get:function(){return qa.ValueScopeName}});Object.defineProperty(Y,"varKinds",{enumerable:!0,get:function(){return qa.varKinds}});Y.operators={GT:new re._Code(">"),GTE:new re._Code(">="),LT:new re._Code("<"),LTE:new re._Code("<="),EQ:new re._Code("==="),NEQ:new re._Code("!=="),NOT:new re._Code("!"),OR:new re._Code("||"),AND:new re._Code("&&"),ADD:new re._Code("+")};var jr=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},zd=class extends jr{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let n=e?Xt.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=Mi(this.rhs,e,t)),this}get names(){return this.rhs instanceof re._CodeOrName?this.rhs.names:{}}},La=class extends jr{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(!(this.lhs instanceof re.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Mi(this.rhs,e,t),this}get names(){let e=this.lhs instanceof re.Name?{}:{...this.lhs.names};return ja(e,this.rhs)}},Kd=class extends La{constructor(e,t,n,i){super(e,n,i),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Wd=class extends jr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Gd=class extends jr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Jd=class extends jr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Yd=class extends jr{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=Mi(this.code,e,t),this}get names(){return this.code instanceof re._CodeOrName?this.code.names:{}}},Bs=class extends jr{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,i=n.length;for(;i--;){let s=n[i];s.optimizeNames(e,t)||(_E(e,s.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>Qn(e,t.names),{})}},qr=class extends Bs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Xd=class extends Bs{},Ci=class extends qr{};Ci.kind="else";var Yn=class r extends qr{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let t=this.else;if(t){let n=t.optimizeNodes();t=this.else=Array.isArray(n)?new Ci(n):n}if(t)return e===!1?t instanceof r?t:t.nodes:this.nodes.length?this:new r(my(e),t instanceof r?[t]:t.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,t){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,t),!!(super.optimizeNames(e,t)||this.else))return this.condition=Mi(this.condition,e,t),this}get names(){let e=super.names;return ja(e,this.condition),this.else&&Qn(e,this.else.names),e}};Yn.kind="if";var Xn=class extends qr{};Xn.kind="for";var Qd=class extends Xn{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=Mi(this.iteration,e,t),this}get names(){return Qn(super.names,this.iteration.names)}},Zd=class extends Xn{constructor(e,t,n,i){super(),this.varKind=e,this.name=t,this.from=n,this.to=i}render(e){let t=e.es5?Xt.varKinds.var:this.varKind,{name:n,from:i,to:s}=this;return`for(${t} ${n}=${i}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=ja(super.names,this.from);return ja(e,this.to)}},Fa=class extends Xn{constructor(e,t,n,i){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=i}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=Mi(this.iterable,e,t),this}get names(){return Qn(super.names,this.iterable.names)}},Us=class extends qr{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Us.kind="func";var Vs=class extends Bs{render(e){return"return "+super.render(e)}};Vs.kind="return";var eu=class extends qr{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(t=this.finally)===null||t===void 0||t.optimizeNodes(),this}optimizeNames(e,t){var n,i;return super.optimizeNames(e,t),(n=this.catch)===null||n===void 0||n.optimizeNames(e,t),(i=this.finally)===null||i===void 0||i.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&Qn(e,this.catch.names),this.finally&&Qn(e,this.finally.names),e}},Hs=class extends qr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Hs.kind="catch";var zs=class extends qr{render(e){return"finally"+super.render(e)}};zs.kind="finally";var tu=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?` +`:""},this._extScope=e,this._scope=new Xt.Scope({parent:e}),this._nodes=[new Xd]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,i){let s=this._scope.toName(t);return n!==void 0&&i&&(this._constants[s.str]=n),this._leafNode(new zd(e,s,n)),s}const(e,t,n){return this._def(Xt.varKinds.const,e,t,n)}let(e,t,n){return this._def(Xt.varKinds.let,e,t,n)}var(e,t,n){return this._def(Xt.varKinds.var,e,t,n)}assign(e,t,n){return this._leafNode(new La(e,t,n))}add(e,t){return this._leafNode(new Kd(e,Y.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==re.nil&&this._leafNode(new Yd(e)),this}object(...e){let t=["{"];for(let[n,i]of e)t.length>1&&t.push(","),t.push(n),(n!==i||this.opts.es5)&&(t.push(":"),(0,re.addCodeArg)(t,i));return t.push("}"),new re._Code(t)}if(e,t,n){if(this._blockNode(new Yn(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Yn(e))}else(){return this._elseNode(new Ci)}endIf(){return this._endBlockNode(Yn,Ci)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new Qd(e),t)}forRange(e,t,n,i,s=this.opts.es5?Xt.varKinds.var:Xt.varKinds.let){let o=this._scope.toName(e);return this._for(new Zd(s,o,t,n),()=>i(o))}forOf(e,t,n,i=Xt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let o=t instanceof re.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0,re._)`${o}.length`,a=>{this.var(s,(0,re._)`${o}[${a}]`),n(s)})}return this._for(new Fa("of",i,s,t),()=>n(s))}forIn(e,t,n,i=this.opts.es5?Xt.varKinds.var:Xt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,re._)`Object.keys(${t})`,n);let s=this._scope.toName(e);return this._for(new Fa("in",i,s,t),()=>n(s))}endFor(){return this._endBlockNode(Xn)}label(e){return this._leafNode(new Wd(e))}break(e){return this._leafNode(new Gd(e))}return(e){let t=new Vs;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Vs)}try(e,t,n){if(!t&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new eu;if(this._blockNode(i),this.code(e),t){let s=this.name("e");this._currNode=i.catch=new Hs(s),t(s)}return n&&(this._currNode=i.finally=new zs,this.code(n)),this._endBlockNode(Hs,zs)}throw(e){return this._leafNode(new Jd(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=re.nil,n,i){return this._blockNode(new Us(e,t,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(Us)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof Yn))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};Y.CodeGen=tu;function Qn(r,e){for(let t in e)r[t]=(r[t]||0)+(e[t]||0);return r}function ja(r,e){return e instanceof re._CodeOrName?Qn(r,e.names):r}function Mi(r,e,t){if(r instanceof re.Name)return n(r);if(!i(r))return r;return new re._Code(r._items.reduce((s,o)=>(o instanceof re.Name&&(o=n(o)),o instanceof re._Code?s.push(...o._items):s.push(o),s),[]));function n(s){let o=t[s.str];return o===void 0||e[s.str]!==1?s:(delete e[s.str],o)}function i(s){return s instanceof re._Code&&s._items.some(o=>o instanceof re.Name&&e[o.str]===1&&t[o.str]!==void 0)}}function _E(r,e){for(let t in e)r[t]=(r[t]||0)-(e[t]||0)}function my(r){return typeof r=="boolean"||typeof r=="number"||r===null?!r:(0,re._)`!${ru(r)}`}Y.not=my;var SE=yy(Y.operators.AND);function xE(...r){return r.reduce(SE)}Y.and=xE;var $E=yy(Y.operators.OR);function EE(...r){return r.reduce($E)}Y.or=EE;function yy(r){return(e,t)=>e===re.nil?t:t===re.nil?e:(0,re._)`${ru(e)} ${r} ${ru(t)}`}function ru(r){return r instanceof re.Name?r:(0,re._)`(${r})`}});var Q=k(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.checkStrictMode=X.getErrorPath=X.Type=X.useFunc=X.setEvaluated=X.evaluatedPropsToName=X.mergeEvaluated=X.eachItem=X.unescapeJsonPointer=X.escapeJsonPointer=X.escapeFragment=X.unescapeFragment=X.schemaRefOrVal=X.schemaHasRulesButRef=X.schemaHasRules=X.checkUnknownRules=X.alwaysValidSchema=X.toHash=void 0;var de=U(),kE=qs();function AE(r){let e={};for(let t of r)e[t]=!0;return e}X.toHash=AE;function PE(r,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(vy(r,e),!wy(e,r.self.RULES.all))}X.alwaysValidSchema=PE;function vy(r,e=r.schema){let{opts:t,self:n}=r;if(!t.strictSchema||typeof e=="boolean")return;let i=n.RULES.keywords;for(let s in e)i[s]||xy(r,`unknown keyword: "${s}"`)}X.checkUnknownRules=vy;function wy(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(e[t])return!0;return!1}X.schemaHasRules=wy;function CE(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(t!=="$ref"&&e.all[t])return!0;return!1}X.schemaHasRulesButRef=CE;function ME({topSchemaRef:r,schemaPath:e},t,n,i){if(!i){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return(0,de._)`${t}`}return(0,de._)`${r}${e}${(0,de.getProperty)(n)}`}X.schemaRefOrVal=ME;function RE(r){return _y(decodeURIComponent(r))}X.unescapeFragment=RE;function TE(r){return encodeURIComponent(iu(r))}X.escapeFragment=TE;function iu(r){return typeof r=="number"?`${r}`:r.replace(/~/g,"~0").replace(/\//g,"~1")}X.escapeJsonPointer=iu;function _y(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}X.unescapeJsonPointer=_y;function IE(r,e){if(Array.isArray(r))for(let t of r)e(t);else e(r)}X.eachItem=IE;function gy({mergeNames:r,mergeToName:e,mergeValues:t,resultToName:n}){return(i,s,o,a)=>{let c=o===void 0?s:o instanceof de.Name?(s instanceof de.Name?r(i,s,o):e(i,s,o),o):s instanceof de.Name?(e(i,o,s),s):t(s,o);return a===de.Name&&!(c instanceof de.Name)?n(i,c):c}}X.mergeEvaluated={props:gy({mergeNames:(r,e,t)=>r.if((0,de._)`${t} !== true && ${e} !== undefined`,()=>{r.if((0,de._)`${e} === true`,()=>r.assign(t,!0),()=>r.assign(t,(0,de._)`${t} || {}`).code((0,de._)`Object.assign(${t}, ${e})`))}),mergeToName:(r,e,t)=>r.if((0,de._)`${t} !== true`,()=>{e===!0?r.assign(t,!0):(r.assign(t,(0,de._)`${t} || {}`),su(r,t,e))}),mergeValues:(r,e)=>r===!0?!0:{...r,...e},resultToName:Sy}),items:gy({mergeNames:(r,e,t)=>r.if((0,de._)`${t} !== true && ${e} !== undefined`,()=>r.assign(t,(0,de._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(r,e,t)=>r.if((0,de._)`${t} !== true`,()=>r.assign(t,e===!0?!0:(0,de._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(r,e)=>r===!0?!0:Math.max(r,e),resultToName:(r,e)=>r.var("items",e)})};function Sy(r,e){if(e===!0)return r.var("props",!0);let t=r.var("props",(0,de._)`{}`);return e!==void 0&&su(r,t,e),t}X.evaluatedPropsToName=Sy;function su(r,e,t){Object.keys(t).forEach(n=>r.assign((0,de._)`${e}${(0,de.getProperty)(n)}`,!0))}X.setEvaluated=su;var by={};function OE(r,e){return r.scopeValue("func",{ref:e,code:by[e.code]||(by[e.code]=new kE._Code(e.code))})}X.useFunc=OE;var nu;(function(r){r[r.Num=0]="Num",r[r.Str=1]="Str"})(nu||(X.Type=nu={}));function DE(r,e,t){if(r instanceof de.Name){let n=e===nu.Num;return t?n?(0,de._)`"[" + ${r} + "]"`:(0,de._)`"['" + ${r} + "']"`:n?(0,de._)`"/" + ${r}`:(0,de._)`"/" + ${r}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0,de.getProperty)(r).toString():"/"+iu(r)}X.getErrorPath=DE;function xy(r,e,t=r.opts.strictSchema){if(t){if(e=`strict mode: ${e}`,t===!0)throw new Error(e);r.self.logger.warn(e)}}X.checkStrictMode=xy});var Ft=k(ou=>{"use strict";Object.defineProperty(ou,"__esModule",{value:!0});var He=U(),NE={data:new He.Name("data"),valCxt:new He.Name("valCxt"),instancePath:new He.Name("instancePath"),parentData:new He.Name("parentData"),parentDataProperty:new He.Name("parentDataProperty"),rootData:new He.Name("rootData"),dynamicAnchors:new He.Name("dynamicAnchors"),vErrors:new He.Name("vErrors"),errors:new He.Name("errors"),this:new He.Name("this"),self:new He.Name("self"),scope:new He.Name("scope"),json:new He.Name("json"),jsonPos:new He.Name("jsonPos"),jsonLen:new He.Name("jsonLen"),jsonPart:new He.Name("jsonPart")};ou.default=NE});var Ks=k(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.extendErrors=ze.resetErrorsCount=ze.reportExtraError=ze.reportError=ze.keyword$DataError=ze.keywordError=void 0;var ie=U(),Ba=Q(),rt=Ft();ze.keywordError={message:({keyword:r})=>(0,ie.str)`must pass "${r}" keyword validation`};ze.keyword$DataError={message:({keyword:r,schemaType:e})=>e?(0,ie.str)`"${r}" keyword must be ${e} ($data)`:(0,ie.str)`"${r}" keyword is invalid ($data)`};function LE(r,e=ze.keywordError,t,n){let{it:i}=r,{gen:s,compositeRule:o,allErrors:a}=i,c=ky(r,e,t);n??(o||a)?$y(s,c):Ey(i,(0,ie._)`[${c}]`)}ze.reportError=LE;function FE(r,e=ze.keywordError,t){let{it:n}=r,{gen:i,compositeRule:s,allErrors:o}=n,a=ky(r,e,t);$y(i,a),s||o||Ey(n,rt.default.vErrors)}ze.reportExtraError=FE;function jE(r,e){r.assign(rt.default.errors,e),r.if((0,ie._)`${rt.default.vErrors} !== null`,()=>r.if(e,()=>r.assign((0,ie._)`${rt.default.vErrors}.length`,e),()=>r.assign(rt.default.vErrors,null)))}ze.resetErrorsCount=jE;function qE({gen:r,keyword:e,schemaValue:t,data:n,errsCount:i,it:s}){if(i===void 0)throw new Error("ajv implementation error");let o=r.name("err");r.forRange("i",i,rt.default.errors,a=>{r.const(o,(0,ie._)`${rt.default.vErrors}[${a}]`),r.if((0,ie._)`${o}.instancePath === undefined`,()=>r.assign((0,ie._)`${o}.instancePath`,(0,ie.strConcat)(rt.default.instancePath,s.errorPath))),r.assign((0,ie._)`${o}.schemaPath`,(0,ie.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(r.assign((0,ie._)`${o}.schema`,t),r.assign((0,ie._)`${o}.data`,n))})}ze.extendErrors=qE;function $y(r,e){let t=r.const("err",e);r.if((0,ie._)`${rt.default.vErrors} === null`,()=>r.assign(rt.default.vErrors,(0,ie._)`[${t}]`),(0,ie._)`${rt.default.vErrors}.push(${t})`),r.code((0,ie._)`${rt.default.errors}++`)}function Ey(r,e){let{gen:t,validateName:n,schemaEnv:i}=r;i.$async?t.throw((0,ie._)`new ${r.ValidationError}(${e})`):(t.assign((0,ie._)`${n}.errors`,e),t.return(!1))}var Zn={keyword:new ie.Name("keyword"),schemaPath:new ie.Name("schemaPath"),params:new ie.Name("params"),propertyName:new ie.Name("propertyName"),message:new ie.Name("message"),schema:new ie.Name("schema"),parentSchema:new ie.Name("parentSchema")};function ky(r,e,t){let{createErrors:n}=r.it;return n===!1?(0,ie._)`{}`:BE(r,e,t)}function BE(r,e,t={}){let{gen:n,it:i}=r,s=[UE(i,t),VE(r,t)];return HE(r,e,s),n.object(...s)}function UE({errorPath:r},{instancePath:e}){let t=e?(0,ie.str)`${r}${(0,Ba.getErrorPath)(e,Ba.Type.Str)}`:r;return[rt.default.instancePath,(0,ie.strConcat)(rt.default.instancePath,t)]}function VE({keyword:r,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:n}){let i=n?e:(0,ie.str)`${e}/${r}`;return t&&(i=(0,ie.str)`${i}${(0,Ba.getErrorPath)(t,Ba.Type.Str)}`),[Zn.schemaPath,i]}function HE(r,{params:e,message:t},n){let{keyword:i,data:s,schemaValue:o,it:a}=r,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;n.push([Zn.keyword,i],[Zn.params,typeof e=="function"?e(r):e||(0,ie._)`{}`]),c.messages&&n.push([Zn.message,typeof t=="function"?t(r):t]),c.verbose&&n.push([Zn.schema,o],[Zn.parentSchema,(0,ie._)`${u}${d}`],[rt.default.data,s]),l&&n.push([Zn.propertyName,l])}});var Py=k(Ri=>{"use strict";Object.defineProperty(Ri,"__esModule",{value:!0});Ri.boolOrEmptySchema=Ri.topBoolOrEmptySchema=void 0;var zE=Ks(),KE=U(),WE=Ft(),GE={message:"boolean schema is false"};function JE(r){let{gen:e,schema:t,validateName:n}=r;t===!1?Ay(r,!1):typeof t=="object"&&t.$async===!0?e.return(WE.default.data):(e.assign((0,KE._)`${n}.errors`,null),e.return(!0))}Ri.topBoolOrEmptySchema=JE;function YE(r,e){let{gen:t,schema:n}=r;n===!1?(t.var(e,!1),Ay(r)):t.var(e,!0)}Ri.boolOrEmptySchema=YE;function Ay(r,e){let{gen:t,data:n}=r,i={gen:t,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:r};(0,zE.reportError)(i,GE,void 0,e)}});var au=k(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.getRules=Ti.isJSONType=void 0;var XE=["string","number","integer","boolean","null","object","array"],QE=new Set(XE);function ZE(r){return typeof r=="string"&&QE.has(r)}Ti.isJSONType=ZE;function ek(){let r={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...r,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},r.number,r.string,r.array,r.object],post:{rules:[]},all:{},keywords:{}}}Ti.getRules=ek});var cu=k(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.shouldUseRule=dn.shouldUseGroup=dn.schemaHasRulesForType=void 0;function tk({schema:r,self:e},t){let n=e.RULES.types[t];return n&&n!==!0&&Cy(r,n)}dn.schemaHasRulesForType=tk;function Cy(r,e){return e.rules.some(t=>My(r,t))}dn.shouldUseGroup=Cy;function My(r,e){var t;return r[e.keyword]!==void 0||((t=e.definition.implements)===null||t===void 0?void 0:t.some(n=>r[n]!==void 0))}dn.shouldUseRule=My});var Ws=k(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.reportTypeError=Ke.checkDataTypes=Ke.checkDataType=Ke.coerceAndCheckDataType=Ke.getJSONTypes=Ke.getSchemaTypes=Ke.DataType=void 0;var rk=au(),nk=cu(),ik=Ks(),z=U(),Ry=Q(),Ii;(function(r){r[r.Correct=0]="Correct",r[r.Wrong=1]="Wrong"})(Ii||(Ke.DataType=Ii={}));function sk(r){let e=Ty(r.type);if(e.includes("null")){if(r.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&r.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');r.nullable===!0&&e.push("null")}return e}Ke.getSchemaTypes=sk;function Ty(r){let e=Array.isArray(r)?r:r?[r]:[];if(e.every(rk.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ke.getJSONTypes=Ty;function ok(r,e){let{gen:t,data:n,opts:i}=r,s=ak(e,i.coerceTypes),o=e.length>0&&!(s.length===0&&e.length===1&&(0,nk.schemaHasRulesForType)(r,e[0]));if(o){let a=du(e,n,i.strictNumbers,Ii.Wrong);t.if(a,()=>{s.length?ck(r,e,s):uu(r)})}return o}Ke.coerceAndCheckDataType=ok;var Iy=new Set(["string","number","integer","boolean","null"]);function ak(r,e){return e?r.filter(t=>Iy.has(t)||e==="array"&&t==="array"):[]}function ck(r,e,t){let{gen:n,data:i,opts:s}=r,o=n.let("dataType",(0,z._)`typeof ${i}`),a=n.let("coerced",(0,z._)`undefined`);s.coerceTypes==="array"&&n.if((0,z._)`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,z._)`${i}[0]`).assign(o,(0,z._)`typeof ${i}`).if(du(e,i,s.strictNumbers),()=>n.assign(a,i))),n.if((0,z._)`${a} !== undefined`);for(let l of t)(Iy.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),uu(r),n.endIf(),n.if((0,z._)`${a} !== undefined`,()=>{n.assign(i,a),lk(r,a)});function c(l){switch(l){case"string":n.elseIf((0,z._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,z._)`"" + ${i}`).elseIf((0,z._)`${i} === null`).assign(a,(0,z._)`""`);return;case"number":n.elseIf((0,z._)`${o} == "boolean" || ${i} === null || (${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}, + || ${o} === "boolean" || ${i} === null`).assign(a,(0,z._)`[${i}]`)}}}function lk({gen:r,parentData:e,parentDataProperty:t},n){r.if((0,z._)`${e} !== undefined`,()=>r.assign((0,z._)`${e}[${t}]`,n))}function lu(r,e,t,n=Ii.Correct){let i=n===Ii.Correct?z.operators.EQ:z.operators.NEQ,s;switch(r){case"null":return(0,z._)`${e} ${i} null`;case"array":s=(0,z._)`Array.isArray(${e})`;break;case"object":s=(0,z._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=o((0,z._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=o();break;default:return(0,z._)`typeof ${e} ${i} ${r}`}return n===Ii.Correct?s:(0,z.not)(s);function o(a=z.nil){return(0,z.and)((0,z._)`typeof ${e} == "number"`,a,t?(0,z._)`isFinite(${e})`:z.nil)}}Ke.checkDataType=lu;function du(r,e,t,n){if(r.length===1)return lu(r[0],e,t,n);let i,s=(0,Ry.toHash)(r);if(s.array&&s.object){let o=(0,z._)`typeof ${e} != "object"`;i=s.null?o:(0,z._)`!${e} || ${o}`,delete s.null,delete s.array,delete s.object}else i=z.nil;s.number&&delete s.integer;for(let o in s)i=(0,z.and)(i,lu(o,e,t,n));return i}Ke.checkDataTypes=du;var dk={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,z._)`{type: ${r}}`:(0,z._)`{type: ${e}}`};function uu(r){let e=uk(r);(0,ik.reportError)(e,dk)}Ke.reportTypeError=uu;function uk(r){let{gen:e,data:t,schema:n}=r,i=(0,Ry.schemaRefOrVal)(r,n,"type");return{gen:e,keyword:"type",data:t,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:r}}});var Dy=k(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.assignDefaults=void 0;var Oi=U(),fk=Q();function pk(r,e){let{properties:t,items:n}=r.schema;if(e==="object"&&t)for(let i in t)Oy(r,i,t[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,s)=>Oy(r,s,i.default))}Ua.assignDefaults=pk;function Oy(r,e,t){let{gen:n,compositeRule:i,data:s,opts:o}=r;if(t===void 0)return;let a=(0,Oi._)`${s}${(0,Oi.getProperty)(e)}`;if(i){(0,fk.checkStrictMode)(r,`default is ignored for: ${a}`);return}let c=(0,Oi._)`${a} === undefined`;o.useDefaults==="empty"&&(c=(0,Oi._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Oi._)`${a} = ${(0,Oi.stringify)(t)}`)}});var jt=k(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.validateUnion=le.validateArray=le.usePattern=le.callValidateCode=le.schemaProperties=le.allSchemaProperties=le.noPropertyInData=le.propertyInData=le.isOwnProperty=le.hasPropFunc=le.reportMissingProp=le.checkMissingProp=le.checkReportMissingProp=void 0;var me=U(),fu=Q(),un=Ft(),hk=Q();function mk(r,e){let{gen:t,data:n,it:i}=r;t.if(hu(t,n,e,i.opts.ownProperties),()=>{r.setParams({missingProperty:(0,me._)`${e}`},!0),r.error()})}le.checkReportMissingProp=mk;function yk({gen:r,data:e,it:{opts:t}},n,i){return(0,me.or)(...n.map(s=>(0,me.and)(hu(r,e,s,t.ownProperties),(0,me._)`${i} = ${s}`)))}le.checkMissingProp=yk;function gk(r,e){r.setParams({missingProperty:e},!0),r.error()}le.reportMissingProp=gk;function Ny(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,me._)`Object.prototype.hasOwnProperty`})}le.hasPropFunc=Ny;function pu(r,e,t){return(0,me._)`${Ny(r)}.call(${e}, ${t})`}le.isOwnProperty=pu;function bk(r,e,t,n){let i=(0,me._)`${e}${(0,me.getProperty)(t)} !== undefined`;return n?(0,me._)`${i} && ${pu(r,e,t)}`:i}le.propertyInData=bk;function hu(r,e,t,n){let i=(0,me._)`${e}${(0,me.getProperty)(t)} === undefined`;return n?(0,me.or)(i,(0,me.not)(pu(r,e,t))):i}le.noPropertyInData=hu;function Ly(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}le.allSchemaProperties=Ly;function vk(r,e){return Ly(e).filter(t=>!(0,fu.alwaysValidSchema)(r,e[t]))}le.schemaProperties=vk;function wk({schemaCode:r,data:e,it:{gen:t,topSchemaRef:n,schemaPath:i,errorPath:s},it:o},a,c,l){let u=l?(0,me._)`${r}, ${e}, ${n}${i}`:e,d=[[un.default.instancePath,(0,me.strConcat)(un.default.instancePath,s)],[un.default.parentData,o.parentData],[un.default.parentDataProperty,o.parentDataProperty],[un.default.rootData,un.default.rootData]];o.opts.dynamicRef&&d.push([un.default.dynamicAnchors,un.default.dynamicAnchors]);let f=(0,me._)`${u}, ${t.object(...d)}`;return c!==me.nil?(0,me._)`${a}.call(${c}, ${f})`:(0,me._)`${a}(${f})`}le.callValidateCode=wk;var _k=(0,me._)`new RegExp`;function Sk({gen:r,it:{opts:e}},t){let n=e.unicodeRegExp?"u":"",{regExp:i}=e.code,s=i(t,n);return r.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,me._)`${i.code==="new RegExp"?_k:(0,hk.useFunc)(r,i)}(${t}, ${n})`})}le.usePattern=Sk;function xk(r){let{gen:e,data:t,keyword:n,it:i}=r,s=e.name("valid");if(i.allErrors){let a=e.let("valid",!0);return o(()=>e.assign(a,!1)),a}return e.var(s,!0),o(()=>e.break()),s;function o(a){let c=e.const("len",(0,me._)`${t}.length`);e.forRange("i",0,c,l=>{r.subschema({keyword:n,dataProp:l,dataPropType:fu.Type.Num},s),e.if((0,me.not)(s),a)})}}le.validateArray=xk;function $k(r){let{gen:e,schema:t,keyword:n,it:i}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(t.some(c=>(0,fu.alwaysValidSchema)(i,c))&&!i.opts.unevaluated)return;let o=e.let("valid",!1),a=e.name("_valid");e.block(()=>t.forEach((c,l)=>{let u=r.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);e.assign(o,(0,me._)`${o} || ${a}`),r.mergeValidEvaluated(u,a)||e.if((0,me.not)(o))})),r.result(o,()=>r.reset(),()=>r.error(!0))}le.validateUnion=$k});var qy=k(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.validateKeywordUsage=vr.validSchemaType=vr.funcKeywordCode=vr.macroKeywordCode=void 0;var nt=U(),ei=Ft(),Ek=jt(),kk=Ks();function Ak(r,e){let{gen:t,keyword:n,schema:i,parentSchema:s,it:o}=r,a=e.macro.call(o.self,i,s,o),c=jy(t,n,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);let l=t.name("valid");r.subschema({schema:a,schemaPath:nt.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),r.pass(l,()=>r.error(!0))}vr.macroKeywordCode=Ak;function Pk(r,e){var t;let{gen:n,keyword:i,schema:s,parentSchema:o,$data:a,it:c}=r;Mk(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,o,c):e.validate,u=jy(n,i,l),d=n.let("valid");r.block$data(d,f),r.ok((t=e.valid)!==null&&t!==void 0?t:d);function f(){if(e.errors===!1)m(),e.modifying&&Fy(r),y(()=>r.error());else{let g=e.async?p():h();e.modifying&&Fy(r),y(()=>Ck(r,g))}}function p(){let g=n.let("ruleErrs",null);return n.try(()=>m((0,nt._)`await `),b=>n.assign(d,!1).if((0,nt._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(g,(0,nt._)`${b}.errors`),()=>n.throw(b))),g}function h(){let g=(0,nt._)`${u}.errors`;return n.assign(g,null),m(nt.nil),g}function m(g=e.async?(0,nt._)`await `:nt.nil){let b=c.opts.passContext?ei.default.this:ei.default.self,v=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,nt._)`${g}${(0,Ek.callValidateCode)(r,u,b,v)}`,e.modifying)}function y(g){var b;n.if((0,nt.not)((b=e.valid)!==null&&b!==void 0?b:d),g)}}vr.funcKeywordCode=Pk;function Fy(r){let{gen:e,data:t,it:n}=r;e.if(n.parentData,()=>e.assign(t,(0,nt._)`${n.parentData}[${n.parentDataProperty}]`))}function Ck(r,e){let{gen:t}=r;t.if((0,nt._)`Array.isArray(${e})`,()=>{t.assign(ei.default.vErrors,(0,nt._)`${ei.default.vErrors} === null ? ${e} : ${ei.default.vErrors}.concat(${e})`).assign(ei.default.errors,(0,nt._)`${ei.default.vErrors}.length`),(0,kk.extendErrors)(r)},()=>r.error())}function Mk({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function jy(r,e,t){if(t===void 0)throw new Error(`keyword "${e}" failed to compile`);return r.scopeValue("keyword",typeof t=="function"?{ref:t}:{ref:t,code:(0,nt.stringify)(t)})}function Rk(r,e,t=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(r):n==="object"?r&&typeof r=="object"&&!Array.isArray(r):typeof r==n||t&&typeof r>"u")}vr.validSchemaType=Rk;function Tk({schema:r,opts:e,self:t,errSchemaPath:n},i,s){if(Array.isArray(i.keyword)?!i.keyword.includes(s):i.keyword!==s)throw new Error("ajv implementation error");let o=i.dependencies;if(o?.some(a=>!Object.prototype.hasOwnProperty.call(r,a)))throw new Error(`parent schema must have dependencies of ${s}: ${o.join(",")}`);if(i.validateSchema&&!i.validateSchema(r[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+t.errorsText(i.validateSchema.errors);if(e.validateSchema==="log")t.logger.error(c);else throw new Error(c)}}vr.validateKeywordUsage=Tk});var Uy=k(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.extendSubschemaMode=fn.extendSubschemaData=fn.getSubschema=void 0;var wr=U(),By=Q();function Ik(r,{keyword:e,schemaProp:t,schema:n,schemaPath:i,errSchemaPath:s,topSchemaRef:o}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=r.schema[e];return t===void 0?{schema:a,schemaPath:(0,wr._)`${r.schemaPath}${(0,wr.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:a[t],schemaPath:(0,wr._)`${r.schemaPath}${(0,wr.getProperty)(e)}${(0,wr.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,By.escapeFragment)(t)}`}}if(n!==void 0){if(i===void 0||s===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:o,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}fn.getSubschema=Ik;function Ok(r,e,{dataProp:t,dataPropType:n,data:i,dataTypes:s,propertyName:o}){if(i!==void 0&&t!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(t!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=e,f=a.let("data",(0,wr._)`${e.data}${(0,wr.getProperty)(t)}`,!0);c(f),r.errorPath=(0,wr.str)`${l}${(0,By.getErrorPath)(t,n,d.jsPropertySyntax)}`,r.parentDataProperty=(0,wr._)`${t}`,r.dataPathArr=[...u,r.parentDataProperty]}if(i!==void 0){let l=i instanceof wr.Name?i:a.let("data",i,!0);c(l),o!==void 0&&(r.propertyName=o)}s&&(r.dataTypes=s);function c(l){r.data=l,r.dataLevel=e.dataLevel+1,r.dataTypes=[],e.definedProperties=new Set,r.parentData=e.data,r.dataNames=[...e.dataNames,l]}}fn.extendSubschemaData=Ok;function Dk(r,{jtdDiscriminator:e,jtdMetadata:t,compositeRule:n,createErrors:i,allErrors:s}){n!==void 0&&(r.compositeRule=n),i!==void 0&&(r.createErrors=i),s!==void 0&&(r.allErrors=s),r.jtdDiscriminator=e,r.jtdMetadata=t}fn.extendSubschemaMode=Dk});var mu=k((Oj,Vy)=>{"use strict";Vy.exports=function r(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return!1;var n,i,s;if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(i=n;i--!==0;)if(!r(e[i],t[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(t).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(t,s[i]))return!1;for(i=n;i--!==0;){var o=s[i];if(!r(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}});var zy=k((Dj,Hy)=>{"use strict";var pn=Hy.exports=function(r,e,t){typeof e=="function"&&(t=e,e={}),t=e.cb||t;var n=typeof t=="function"?t:t.pre||function(){},i=t.post||function(){};Va(e,n,i,r,"",r)};pn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};pn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};pn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};pn.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Va(r,e,t,n,i,s,o,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,i,s,o,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in pn.arrayKeywords)for(var f=0;f{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.getSchemaRefs=pt.resolveUrl=pt.normalizeId=pt._getFullPath=pt.getFullPath=pt.inlineRef=void 0;var Lk=Q(),Fk=mu(),jk=zy(),qk=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Bk(r,e=!0){return typeof r=="boolean"?!0:e===!0?!yu(r):e?Ky(r)<=e:!1}pt.inlineRef=Bk;var Uk=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function yu(r){for(let e in r){if(Uk.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(yu)||typeof t=="object"&&yu(t))return!0}return!1}function Ky(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!qk.has(t)&&(typeof r[t]=="object"&&(0,Lk.eachItem)(r[t],n=>e+=Ky(n)),e===1/0))return 1/0}return e}function Wy(r,e="",t){t!==!1&&(e=Di(e));let n=r.parse(e);return Gy(r,n)}pt.getFullPath=Wy;function Gy(r,e){return r.serialize(e).split("#")[0]+"#"}pt._getFullPath=Gy;var Vk=/#\/?$/;function Di(r){return r?r.replace(Vk,""):""}pt.normalizeId=Di;function Hk(r,e,t){return t=Di(t),r.resolve(e,t)}pt.resolveUrl=Hk;var zk=/^[a-z_][-a-z0-9._]*$/i;function Kk(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:n}=this.opts,i=Di(r[t]||e),s={"":i},o=Wy(n,i,!1),a={},c=new Set;return jk(r,{allKeys:!0},(d,f,p,h)=>{if(h===void 0)return;let m=o+f,y=s[h];typeof d[t]=="string"&&(y=g.call(this,d[t])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),s[f]=y;function g(v){let S=this.opts.uriResolver.resolve;if(v=Di(y?S(y,v):v),c.has(v))throw u(v);c.add(v);let _=this.refs[v];return typeof _=="string"&&(_=this.refs[_]),typeof _=="object"?l(d,_.schema,v):v!==Di(m)&&(v[0]==="#"?(l(d,a[v],v),a[v]=d):this.refs[v]=m),v}function b(v){if(typeof v=="string"){if(!zk.test(v))throw new Error(`invalid anchor "${v}"`);g.call(this,`#${v}`)}}}),a;function l(d,f,p){if(f!==void 0&&!Fk(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}pt.getSchemaRefs=Kk});var Ni=k(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.getData=hn.KeywordCxt=hn.validateFunctionCode=void 0;var Zy=Py(),Jy=Ws(),bu=cu(),Ha=Ws(),Wk=Dy(),Ys=qy(),gu=Uy(),j=U(),B=Ft(),Gk=Gs(),Br=Q(),Js=Ks();function Jk(r){if(rg(r)&&(ng(r),tg(r))){Qk(r);return}eg(r,()=>(0,Zy.topBoolOrEmptySchema)(r))}hn.validateFunctionCode=Jk;function eg({gen:r,validateName:e,schema:t,schemaEnv:n,opts:i},s){i.code.es5?r.func(e,(0,j._)`${B.default.data}, ${B.default.valCxt}`,n.$async,()=>{r.code((0,j._)`"use strict"; ${Yy(t,i)}`),Xk(r,i),r.code(s)}):r.func(e,(0,j._)`${B.default.data}, ${Yk(i)}`,n.$async,()=>r.code(Yy(t,i)).code(s))}function Yk(r){return(0,j._)`{${B.default.instancePath}="", ${B.default.parentData}, ${B.default.parentDataProperty}, ${B.default.rootData}=${B.default.data}${r.dynamicRef?(0,j._)`, ${B.default.dynamicAnchors}={}`:j.nil}}={}`}function Xk(r,e){r.if(B.default.valCxt,()=>{r.var(B.default.instancePath,(0,j._)`${B.default.valCxt}.${B.default.instancePath}`),r.var(B.default.parentData,(0,j._)`${B.default.valCxt}.${B.default.parentData}`),r.var(B.default.parentDataProperty,(0,j._)`${B.default.valCxt}.${B.default.parentDataProperty}`),r.var(B.default.rootData,(0,j._)`${B.default.valCxt}.${B.default.rootData}`),e.dynamicRef&&r.var(B.default.dynamicAnchors,(0,j._)`${B.default.valCxt}.${B.default.dynamicAnchors}`)},()=>{r.var(B.default.instancePath,(0,j._)`""`),r.var(B.default.parentData,(0,j._)`undefined`),r.var(B.default.parentDataProperty,(0,j._)`undefined`),r.var(B.default.rootData,B.default.data),e.dynamicRef&&r.var(B.default.dynamicAnchors,(0,j._)`{}`)})}function Qk(r){let{schema:e,opts:t,gen:n}=r;eg(r,()=>{t.$comment&&e.$comment&&sg(r),nA(r),n.let(B.default.vErrors,null),n.let(B.default.errors,0),t.unevaluated&&Zk(r),ig(r),oA(r)})}function Zk(r){let{gen:e,validateName:t}=r;r.evaluated=e.const("evaluated",(0,j._)`${t}.evaluated`),e.if((0,j._)`${r.evaluated}.dynamicProps`,()=>e.assign((0,j._)`${r.evaluated}.props`,(0,j._)`undefined`)),e.if((0,j._)`${r.evaluated}.dynamicItems`,()=>e.assign((0,j._)`${r.evaluated}.items`,(0,j._)`undefined`))}function Yy(r,e){let t=typeof r=="object"&&r[e.schemaId];return t&&(e.code.source||e.code.process)?(0,j._)`/*# sourceURL=${t} */`:j.nil}function eA(r,e){if(rg(r)&&(ng(r),tg(r))){tA(r,e);return}(0,Zy.boolOrEmptySchema)(r,e)}function tg({schema:r,self:e}){if(typeof r=="boolean")return!r;for(let t in r)if(e.RULES.all[t])return!0;return!1}function rg(r){return typeof r.schema!="boolean"}function tA(r,e){let{schema:t,gen:n,opts:i}=r;i.$comment&&t.$comment&&sg(r),iA(r),sA(r);let s=n.const("_errs",B.default.errors);ig(r,s),n.var(e,(0,j._)`${s} === ${B.default.errors}`)}function ng(r){(0,Br.checkUnknownRules)(r),rA(r)}function ig(r,e){if(r.opts.jtd)return Xy(r,[],!1,e);let t=(0,Jy.getSchemaTypes)(r.schema),n=(0,Jy.coerceAndCheckDataType)(r,t);Xy(r,t,!n,e)}function rA(r){let{schema:e,errSchemaPath:t,opts:n,self:i}=r;e.$ref&&n.ignoreKeywordsWithRef&&(0,Br.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function nA(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,Br.checkStrictMode)(r,"default is ignored in the schema root")}function iA(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,Gk.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function sA(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function sg({gen:r,schemaEnv:e,schema:t,errSchemaPath:n,opts:i}){let s=t.$comment;if(i.$comment===!0)r.code((0,j._)`${B.default.self}.logger.log(${s})`);else if(typeof i.$comment=="function"){let o=(0,j.str)`${n}/$comment`,a=r.scopeValue("root",{ref:e.root});r.code((0,j._)`${B.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function oA(r){let{gen:e,schemaEnv:t,validateName:n,ValidationError:i,opts:s}=r;t.$async?e.if((0,j._)`${B.default.errors} === 0`,()=>e.return(B.default.data),()=>e.throw((0,j._)`new ${i}(${B.default.vErrors})`)):(e.assign((0,j._)`${n}.errors`,B.default.vErrors),s.unevaluated&&aA(r),e.return((0,j._)`${B.default.errors} === 0`))}function aA({gen:r,evaluated:e,props:t,items:n}){t instanceof j.Name&&r.assign((0,j._)`${e}.props`,t),n instanceof j.Name&&r.assign((0,j._)`${e}.items`,n)}function Xy(r,e,t,n){let{gen:i,schema:s,data:o,allErrors:a,opts:c,self:l}=r,{RULES:u}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Br.schemaHasRulesButRef)(s,u))){i.block(()=>ag(r,"$ref",u.all.$ref.definition));return}c.jtd||cA(r,e),i.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,bu.shouldUseGroup)(s,f)&&(f.type?(i.if((0,Ha.checkDataType)(f.type,o,c.strictNumbers)),Qy(r,f),e.length===1&&e[0]===f.type&&t&&(i.else(),(0,Ha.reportTypeError)(r)),i.endIf()):Qy(r,f),a||i.if((0,j._)`${B.default.errors} === ${n||0}`))}}function Qy(r,e){let{gen:t,schema:n,opts:{useDefaults:i}}=r;i&&(0,Wk.assignDefaults)(r,e.type),t.block(()=>{for(let s of e.rules)(0,bu.shouldUseRule)(n,s)&&ag(r,s.keyword,s.definition,e.type)})}function cA(r,e){r.schemaEnv.meta||!r.opts.strictTypes||(lA(r,e),r.opts.allowUnionTypes||dA(r,e),uA(r,r.dataTypes))}function lA(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{og(r.dataTypes,t)||vu(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),pA(r,e)}}function dA(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&vu(r,"use allowUnionTypes to allow union type keyword")}function uA(r,e){let t=r.self.RULES.all;for(let n in t){let i=t[n];if(typeof i=="object"&&(0,bu.shouldUseRule)(r.schema,i)){let{type:s}=i.definition;s.length&&!s.some(o=>fA(e,o))&&vu(r,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function fA(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function og(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function pA(r,e){let t=[];for(let n of r.dataTypes)og(e,n)?t.push(n):e.includes("integer")&&n==="number"&&t.push("integer");r.dataTypes=t}function vu(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,Br.checkStrictMode)(r,e,r.opts.strictTypes)}var za=class{constructor(e,t,n){if((0,Ys.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Br.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",cg(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ys.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const("_errs",B.default.errors))}result(e,t,n){this.failResult((0,j.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,j.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,j._)`${t} !== undefined && (${(0,j.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?Js.reportExtraError:Js.reportError)(this,this.def.error,t)}$dataError(){(0,Js.reportError)(this,this.def.$dataError||Js.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Js.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=j.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=j.nil,t=j.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:s,def:o}=this;n.if((0,j.or)((0,j._)`${i} === undefined`,t)),e!==j.nil&&n.assign(e,!0),(s.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==j.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:i,it:s}=this;return(0,j.or)(o(),a());function o(){if(n.length){if(!(t instanceof j.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,j._)`${(0,Ha.checkDataTypes)(c,t,s.opts.strictNumbers,Ha.DataType.Wrong)}`}return j.nil}function a(){if(i.validateSchema){let c=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,j._)`!${c}(${t})`}return j.nil}}subschema(e,t){let n=(0,gu.getSubschema)(this.it,e);(0,gu.extendSubschemaData)(n,this.it,e),(0,gu.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return eA(i,t),i}mergeEvaluated(e,t){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Br.mergeEvaluated.props(i,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=Br.mergeEvaluated.items(i,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(t,()=>this.mergeEvaluated(e,j.Name)),!0}};hn.KeywordCxt=za;function ag(r,e,t,n){let i=new za(r,t,e);"code"in t?t.code(i,n):i.$data&&t.validate?(0,Ys.funcKeywordCode)(i,t):"macro"in t?(0,Ys.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0,Ys.funcKeywordCode)(i,t)}var hA=/^\/(?:[^~]|~0|~1)*$/,mA=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function cg(r,{dataLevel:e,dataNames:t,dataPathArr:n}){let i,s;if(r==="")return B.default.rootData;if(r[0]==="/"){if(!hA.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);i=r,s=B.default.rootData}else{let l=mA.exec(r);if(!l)throw new Error(`Invalid JSON-pointer: ${r}`);let u=+l[1];if(i=l[2],i==="#"){if(u>=e)throw new Error(c("property/index",u));return n[e-u]}if(u>e)throw new Error(c("data",u));if(s=t[e-u],!i)return s}let o=s,a=i.split("/");for(let l of a)l&&(s=(0,j._)`${s}${(0,j.getProperty)((0,Br.unescapeJsonPointer)(l))}`,o=(0,j._)`${o} && ${s}`);return o;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}hn.getData=cg});var Xs=k(_u=>{"use strict";Object.defineProperty(_u,"__esModule",{value:!0});var wu=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};_u.default=wu});var Li=k($u=>{"use strict";Object.defineProperty($u,"__esModule",{value:!0});var Su=Gs(),xu=class extends Error{constructor(e,t,n,i){super(i||`can't resolve reference ${n} from id ${t}`),this.missingRef=(0,Su.resolveUrl)(e,t,n),this.missingSchema=(0,Su.normalizeId)((0,Su.getFullPath)(e,this.missingRef))}};$u.default=xu});var Qs=k(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.resolveSchema=qt.getCompilingSchema=qt.resolveRef=qt.compileSchema=qt.SchemaEnv=void 0;var Qt=U(),yA=Xs(),ti=Ft(),Zt=Gs(),lg=Q(),gA=Ni(),Fi=class{constructor(e){var t;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:(0,Zt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};qt.SchemaEnv=Fi;function ku(r){let e=dg.call(this,r);if(e)return e;let t=(0,Zt.getFullPath)(this.opts.uriResolver,r.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:s}=this.opts,o=new Qt.CodeGen(this.scope,{es5:n,lines:i,ownProperties:s}),a;r.$async&&(a=o.scopeValue("Error",{ref:yA.default,code:(0,Qt._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");r.validateName=c;let l={gen:o,allErrors:this.opts.allErrors,data:ti.default.data,parentData:ti.default.parentData,parentDataProperty:ti.default.parentDataProperty,dataNames:[ti.default.data],dataPathArr:[Qt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:r.schema,code:(0,Qt.stringify)(r.schema)}:{ref:r.schema}),validateName:c,ValidationError:a,schema:r.schema,schemaEnv:r,rootId:t,baseId:r.baseId||t,schemaPath:Qt.nil,errSchemaPath:r.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Qt._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(r),(0,gA.validateFunctionCode)(l),o.optimize(this.opts.code.optimize);let d=o.toString();u=`${o.scopeRefs(ti.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,r));let p=new Function(`${ti.default.self}`,`${ti.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=r.schema,p.schemaEnv=r,r.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:o._values}),this.opts.unevaluated){let{props:h,items:m}=l;p.evaluated={props:h instanceof Qt.Name?void 0:h,items:m instanceof Qt.Name?void 0:m,dynamicProps:h instanceof Qt.Name,dynamicItems:m instanceof Qt.Name},p.source&&(p.source.evaluated=(0,Qt.stringify)(p.evaluated))}return r.validate=p,r}catch(d){throw delete r.validate,delete r.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(r)}}qt.compileSchema=ku;function bA(r,e,t){var n;t=(0,Zt.resolveUrl)(this.opts.uriResolver,e,t);let i=r.refs[t];if(i)return i;let s=_A.call(this,r,t);if(s===void 0){let o=(n=r.localRefs)===null||n===void 0?void 0:n[t],{schemaId:a}=this.opts;o&&(s=new Fi({schema:o,schemaId:a,root:r,baseId:e}))}if(s!==void 0)return r.refs[t]=vA.call(this,s)}qt.resolveRef=bA;function vA(r){return(0,Zt.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:ku.call(this,r)}function dg(r){for(let e of this._compilations)if(wA(e,r))return e}qt.getCompilingSchema=dg;function wA(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function _A(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||Ka.call(this,r,e)}function Ka(r,e){let t=this.opts.uriResolver.parse(e),n=(0,Zt._getFullPath)(this.opts.uriResolver,t),i=(0,Zt.getFullPath)(this.opts.uriResolver,r.baseId,void 0);if(Object.keys(r.schema).length>0&&n===i)return Eu.call(this,t,r);let s=(0,Zt.normalizeId)(n),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=Ka.call(this,r,o);return typeof a?.schema!="object"?void 0:Eu.call(this,t,a)}if(typeof o?.schema=="object"){if(o.validate||ku.call(this,o),s===(0,Zt.normalizeId)(e)){let{schema:a}=o,{schemaId:c}=this.opts,l=a[c];return l&&(i=(0,Zt.resolveUrl)(this.opts.uriResolver,i,l)),new Fi({schema:a,schemaId:c,root:r,baseId:i})}return Eu.call(this,t,o)}}qt.resolveSchema=Ka;var SA=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Eu(r,{baseId:e,schema:t,root:n}){var i;if(((i=r.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let a of r.fragment.slice(1).split("/")){if(typeof t=="boolean")return;let c=t[(0,lg.unescapeFragment)(a)];if(c===void 0)return;t=c;let l=typeof t=="object"&&t[this.opts.schemaId];!SA.has(a)&&l&&(e=(0,Zt.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof t!="boolean"&&t.$ref&&!(0,lg.schemaHasRulesButRef)(t,this.RULES)){let a=(0,Zt.resolveUrl)(this.opts.uriResolver,e,t.$ref);s=Ka.call(this,n,a)}let{schemaId:o}=this.opts;if(s=s||new Fi({schema:t,schemaId:o,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var ug=k((Bj,xA)=>{xA.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Tu=k((Uj,bg)=>{"use strict";var $A=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Pu=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),EA=RegExp.prototype.test.bind(/^\d*$/u),ri=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Cu=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),pg=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Mu=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),kA=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),ht=new Array(256);{let r="0123456789ABCDEF";for(let e=0;e<256;e++)ht[e]="%"+r[e>>4]+r[e&15]}function We(r){return r<2048?ht[192|r>>6]+ht[128|r&63]:r<65536?ht[224|r>>12]+ht[128|r>>6&63]+ht[128|r&63]:ht[240|r>>18]+ht[128|r>>12&63]+ht[128|r>>6&63]+ht[128|r&63]}function AA(r){let e="",t=0,n=0;for(n=0;n=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return"";e+=r[n];break}for(n+=1;n=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return"";e+=r[n]}return e}var PA=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),CA=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),MA=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),RA=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function TA(r){if(r.length===0)return!1;for(let e=0;et&&(t=i,e=n)):(n=-1,i=0);if(t<2)return r.join(":");let s=r.slice(0,e).join(":"),o=r.slice(e+t).join(":");return s+"::"+o}function IA(r){let e=r.indexOf("::");if(e!==-1&&r.indexOf("::",e+1)!==-1)return;let t=e===-1?r.split(":"):r.slice(0,e).split(":"),n=e===-1?[]:r.slice(e+2).split(":");e!==-1&&(t.length===1&&t[0]===""&&(t.length=0),n.length===1&&n[0]===""&&(n.length=0));let i=t.concat(n),s=0;for(let a=0;a=8)return;let o=i.slice(0,t.length);for(let a=s;a<8;a++)o.push("0");for(let a=t.length;aNA[n])}function mg(r,e=!1){if(r.indexOf("%")===-1)return r;let t="";for(let n=0;n57343)e+=We(i);else if(i<=56319&&t+1=56320&&s<=57343?(e+=We(65536+(i-55296<<10)+(s-56320)),t++):e+=We(65533)}else e+=We(65533)}}return e}function qA(r,e=!1){let t="",n=e&&r[0]!=="/";for(let i=0;i57343)t+=We(o);else if(o<=56319&&i+1=56320&&a<=57343?(t+=We(65536+(o-55296<<10)+(a-56320)),i++):t+=We(65533)}else t+=We(65533)}}return t}function Ru(r,e){let t="";for(let n=0;n57343)t+=We(s);else if(s<=56319&&n+1=56320&&o<=57343?(t+=We(65536+(s-55296<<10)+(o-56320)),n++):t+=We(65533)}else t+=We(65533)}}return t}function yg(r){return Ru(r,kA)}function BA(r){return Ru(r,Mu)}function UA(r){return Ru(r,Mu)}function gg(r){return r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||r===42||r===43||r===45||r===46||r===47||r===64||r===95}function VA(r){let e="";for(let t=0;t57343)e+=We(i);else if(i<=56319&&t+1=56320&&s<=57343?(e+=We(65536+(i-55296<<10)+(s-56320)),t++):e+=We(65533)}else e+=We(65533)}}return e}function HA(r){let e="";for(let t=0;t{"use strict";var{isUUID:KA}=Tu(),WA=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,GA=["http","https","ws","wss","urn","urn:uuid"];function JA(r){return GA.indexOf(r)!==-1}function Iu(r){return r.secure===!0?!0:r.secure===!1?!1:r.scheme?r.scheme.length===3&&(r.scheme[0]==="w"||r.scheme[0]==="W")&&(r.scheme[1]==="s"||r.scheme[1]==="S")&&(r.scheme[2]==="s"||r.scheme[2]==="S"):!1}function vg(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function wg(r){let e=String(r.scheme).toLowerCase()==="https";return(r.port===(e?443:80)||r.port==="")&&(r.port=void 0),r.path||(r.path="/"),r}function YA(r){return r.secure=Iu(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function XA(r){if((r.port===(Iu(r)?443:80)||r.port==="")&&(r.port=void 0),typeof r.secure=="boolean"&&(r.scheme=r.secure?"wss":"ws",r.secure=void 0),r.resourceName){let e=r.resourceName.indexOf("?"),t=e===-1?r.resourceName:r.resourceName.slice(0,e);r.path=t&&t!=="/"?t:void 0,r.query=e===-1?void 0:r.resourceName.slice(e+1),r.resourceName=void 0}return r.fragment=void 0,r}function QA(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(WA);if(t&&t[0]===r.path){let n=e.scheme||r.scheme||"urn";r.nid=t[1].toLowerCase(),r.nss=t[2];let i=`${n}:${e.nid||r.nid}`,s=Ou(i);r.path=void 0,s&&(r=s.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function ZA(r,e){if(r.nid===void 0)throw new Error("URN without nid cannot be serialized");let t=e.scheme||r.scheme||"urn",n=r.nid.toLowerCase(),i=`${t}:${e.nid||n}`,s=Ou(i);s&&(r=s.serialize(r,e));let o=r,a=r.nss;return o.path=`${n||e.nid}:${a}`,e.skipEscape=!0,o}function eP(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!KA(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function tP(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var _g={scheme:"http",domainHost:!0,parse:vg,serialize:wg},rP={scheme:"https",domainHost:_g.domainHost,parse:vg,serialize:wg},Wa={scheme:"ws",domainHost:!0,parse:YA,serialize:XA},nP={scheme:"wss",domainHost:Wa.domainHost,parse:Wa.parse,serialize:Wa.serialize},iP={scheme:"urn",parse:QA,serialize:ZA,skipNormalize:!0},sP={scheme:"urn:uuid",parse:eP,serialize:tP,skipNormalize:!0},Ga={http:_g,https:rP,ws:Wa,wss:nP,urn:iP,"urn:uuid":sP};Object.setPrototypeOf(Ga,null);function Ou(r){return r&&(Ga[r]||Ga[r.toLowerCase()])||void 0}Sg.exports={wsIsSecure:Iu,SCHEMES:Ga,isValidSchemeName:JA,getSchemeHandler:Ou}});var Lg=k((Hj,Xa)=>{"use strict";var{normalizeIPv6:Pg,removeDotSegments:eo,recomposeAuthority:oP,normalizePercentEncoding:Cg,normalizePathEncoding:aP,serializePathEncoding:$g,normalizeQueryFragmentEncoding:Eg,encodeQuery:cP,encodeFragment:lP,reescapeHostDelimiters:dP,isIPv4:Mg,nonSimpleDomain:uP}=Tu(),{SCHEMES:Rg,getSchemeHandler:Du}=xg(),Tg=/^[A-Za-z][A-Za-z0-9+.-]*$/u,Ig="URI scheme is malformed.";function kg(r){let e=unescape(String(r));if(!Tg.test(e))throw new TypeError(Ig);return e}function fP(r,e){return typeof r=="string"?r=wP(r,e):typeof r=="object"&&(r=Ya(ni(r,e),e)),r}function pP(r,e,t){let n=t?Object.assign({scheme:"null"},t):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:s,malformedPercentEncoding:o,malformedSchemeSpecific:a,malformedHost:c,malformedScheme:l}=Ja(r,n),{parsed:u,malformedAuthorityOrPort:d,malformedPercentEncoding:f,malformedSchemeSpecific:p,malformedHost:h,malformedScheme:m}=Ja(e,n);if(s||d||o||f||a||p||c||h||l||m)throw new Error(i.error||u.error||"URI is malformed.");let y=Og(i,u,n,!0),g=Du(t&&t.scheme||y.scheme),b=y.host,v=b!==void 0&&b!==""&&(Mg(b)||Pg(b).isIPV6);Dg(y,t||{},g,v);let S=b&&b.indexOf("%")!==-1&&!/\P{ASCII}/u.test(b);if(y.error&&!S)throw new Error(y.error);return n.skipEscape=!0,ni(y,n)}function Og(r,e,t,n){let i={};return n||(r=Ya(ni(r,t),t),e=Ya(ni(e,t),t)),t=t||{},!t.tolerant&&e.scheme?(i.scheme=e.scheme,i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=eo(e.path||""),i.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=eo(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=eo(e.path):((r.userinfo!==void 0||r.host!==void 0||r.port!==void 0)&&!r.path?i.path="/"+e.path:r.path?i.path=r.path.slice(0,r.path.lastIndexOf("/")+1)+e.path:i.path=e.path,i.path=eo(i.path)),i.query=e.query):(i.path=r.path,e.query!==void 0?i.query=e.query:i.query=r.query),i.userinfo=r.userinfo,i.host=r.host,i.port=r.port),i.scheme=r.scheme),i.fragment=e.fragment,i}function hP(r,e,t){let n=Ag(r,t),i=Ag(e,t);return n!==void 0&&i!==void 0&&n===i}function ni(r,e){let t={host:r.host,scheme:r.scheme,userinfo:r.userinfo,port:r.port,path:r.path,query:r.query,nid:r.nid,nss:r.nss,uuid:r.uuid,fragment:r.fragment,reference:r.reference,resourceName:r.resourceName,secure:r.secure,error:""},n=Object.assign({},e),i=[];t.scheme&&(t.scheme=kg(t.scheme));let s=Du(n.scheme||t.scheme);s&&s.serialize&&s.serialize(t,n);let o=t.userinfo!==void 0||t.host!==void 0||t.port!==void 0,a=!n.skipEscape&&t.scheme===void 0&&!o;t.path!==void 0&&(n.skipEscape?t.path=Cg(t.path):t.path=$g(t.path,a)),n.reference!=="suffix"&&t.scheme&&(t.scheme=kg(t.scheme),i.push(t.scheme,":"));let c=oP(t);if(c!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(c),t.path&&t.path[0]!=="/"&&i.push("/")),t.path!==void 0){let l=t.path;!n.absolutePath&&(!s||!s.absolutePath)&&(l=eo(l)),a&&(l=$g(l,!0)),c===void 0&&l[0]==="/"&&l[1]==="/"&&(l="/%2F"+l.slice(2)),i.push(l)}return t.query!==void 0&&i.push("?",cP(t.query)),t.fragment!==void 0&&i.push("#",lP(t.fragment)),i.join("")}var mP=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,yP=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,gP=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function bP(r,e){if(e[2]!==void 0&&r.path&&r.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof r.port=="number"&&(r.port<0||r.port>65535))return"URI port is malformed."}function Zs(r){if(r===void 0)return!1;let e=r.indexOf("%");for(;e!==-1;){if(e+2>=r.length||!/^[\da-f]{2}$/iu.test(r.slice(e+1,e+3)))return!0;e=r.indexOf("%",e+3)}return!1}function Nu(r){return r[0]==="["&&r[r.length-1]==="]"}function vP(r){let e=r[4];return Zs(r[3])||e!==void 0&&!Nu(e)&&Zs(e)||Zs(r[6])||Zs(r[7])||Zs(r[8])}function Dg(r,e,t,n){if(!e.unicodeSupport&&(!t||!t.unicodeSupport)&&r.host&&!Nu(r.host)&&(e.domainHost||t&&t.domainHost)&&n===!1&&uP(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(i){return r.error=r.error||"Host's domain name can not be converted to ASCII: "+i,!0}return!1}function Ja(r,e){let t=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=!1,s=!1,o=!1,a=!1,c=!1,l=!1,u=!1;t.reference==="suffix"&&(t.scheme?r=t.scheme+":"+r:r="//"+r);let d=r.match(yP);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let f=r.match(gP);if(f!==null){let h=f[1],m=h.replace(/[\t\n\r]/g,"");m.length>=2&&(m.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",i=!0):h.length!==m.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",i=!0))}let p=r.match(mP);if(p){if(n.scheme=p[1],n.userinfo=p[3],n.host=p[4],n.port=parseInt(p[5],10),n.path=p[6]||"",n.query=p[7],n.fragment=p[8],n.scheme!==void 0){let y=unescape(n.scheme);Tg.test(y)?n.scheme=y.toLowerCase():(n.error=n.error||Ig,l=!0)}s=vP(p),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=p[5]);let h=bP(n,p);if(h!==void 0&&(n.error=n.error||h,i=!0),n.host)if(Mg(n.host)===!1){let g=Nu(n.host),b=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,v=Pg(n.host);u=v.isIPV6||v.isIPVFuture===!0,c=b&&(!g||v.error===!0),n.host=u?v.host:v.host.toLowerCase(),c&&(n.error=n.error||"URI host is malformed.",i=!0)}else u=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",t.reference&&t.reference!=="suffix"&&t.reference!==n.reference&&(n.error=n.error||"URI is not a "+t.reference+" reference.");let m=Du(t.scheme||n.scheme);if(c||(a=Dg(n,t,m,u)),!m||m&&!m.skipNormalize){if(r.indexOf("%")!==-1&&n.host!==void 0&&!c){let y=u?n.host:Cg(n.host,!0);n.host=dP(y,u)}n.path&&(n.path=aP(n.path)),n.query&&(n.query=Eg(n.query)),n.fragment&&(n.fragment=Eg(n.fragment))}m&&m.parse&&(m.parse(n,t),m===Rg.urn&&n.nid===void 0&&(o=!0))}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:i,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:a,malformedScheme:l}}function Ya(r,e){return Ja(r,e).parsed}function wP(r,e){return Ng(r,e).normalized}function Ng(r,e){let{parsed:t,malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:a}=Ja(r,e);return{normalized:n||i||s||o||a?r:ni(t,e),malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:a}}function Ag(r,e){if(typeof r!="string"&&typeof r!="object")return;let t;try{t=typeof r=="string"?r:ni(r,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:i,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:a,malformedScheme:c}=Ng(t,e);return i||s||o||a||c?void 0:n}var Lu={SCHEMES:Rg,normalize:fP,resolve:pP,resolveComponent:Og,equal:hP,serialize:ni,parse:Ya};Xa.exports=Lu;Xa.exports.default=Lu;Xa.exports.fastUri=Lu});var jg=k(Fu=>{"use strict";Object.defineProperty(Fu,"__esModule",{value:!0});var Fg=Lg();Fg.code='require("ajv/dist/runtime/uri").default';Fu.default=Fg});var Bu=k(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.CodeGen=Fe.Name=Fe.nil=Fe.stringify=Fe.str=Fe._=Fe.KeywordCxt=void 0;var _P=Ni();Object.defineProperty(Fe,"KeywordCxt",{enumerable:!0,get:function(){return _P.KeywordCxt}});var ji=U();Object.defineProperty(Fe,"_",{enumerable:!0,get:function(){return ji._}});Object.defineProperty(Fe,"str",{enumerable:!0,get:function(){return ji.str}});Object.defineProperty(Fe,"stringify",{enumerable:!0,get:function(){return ji.stringify}});Object.defineProperty(Fe,"nil",{enumerable:!0,get:function(){return ji.nil}});Object.defineProperty(Fe,"Name",{enumerable:!0,get:function(){return ji.Name}});Object.defineProperty(Fe,"CodeGen",{enumerable:!0,get:function(){return ji.CodeGen}});var SP=Xs(),Hg=Li(),xP=au(),to=Qs(),$P=U(),ro=Gs(),Qa=Ws(),qu=Q(),qg=ug(),EP=jg(),zg=(r,e)=>new RegExp(r,e);zg.code="new RegExp";var kP=["removeAdditional","useDefaults","coerceTypes"],AP=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),PP={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},CP={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Bg=200;function MP(r){var e,t,n,i,s,o,a,c,l,u,d,f,p,h,m,y,g,b,v,S,_,E,A,x,R;let $=r.strict,q=(e=r.code)===null||e===void 0?void 0:e.optimize,M=q===!0||q===void 0?1:q||0,V=(n=(t=r.code)===null||t===void 0?void 0:t.regExp)!==null&&n!==void 0?n:zg,P=(i=r.uriResolver)!==null&&i!==void 0?i:EP.default;return{strictSchema:(o=(s=r.strictSchema)!==null&&s!==void 0?s:$)!==null&&o!==void 0?o:!0,strictNumbers:(c=(a=r.strictNumbers)!==null&&a!==void 0?a:$)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=r.strictTypes)!==null&&l!==void 0?l:$)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=r.strictTuples)!==null&&d!==void 0?d:$)!==null&&f!==void 0?f:"log",strictRequired:(h=(p=r.strictRequired)!==null&&p!==void 0?p:$)!==null&&h!==void 0?h:!1,code:r.code?{...r.code,optimize:M,regExp:V}:{optimize:M,regExp:V},loopRequired:(m=r.loopRequired)!==null&&m!==void 0?m:Bg,loopEnum:(y=r.loopEnum)!==null&&y!==void 0?y:Bg,meta:(g=r.meta)!==null&&g!==void 0?g:!0,messages:(b=r.messages)!==null&&b!==void 0?b:!0,inlineRefs:(v=r.inlineRefs)!==null&&v!==void 0?v:!0,schemaId:(S=r.schemaId)!==null&&S!==void 0?S:"$id",addUsedSchema:(_=r.addUsedSchema)!==null&&_!==void 0?_:!0,validateSchema:(E=r.validateSchema)!==null&&E!==void 0?E:!0,validateFormats:(A=r.validateFormats)!==null&&A!==void 0?A:!0,unicodeRegExp:(x=r.unicodeRegExp)!==null&&x!==void 0?x:!0,int32range:(R=r.int32range)!==null&&R!==void 0?R:!0,uriResolver:P}}var no=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...MP(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new $P.ValueScope({scope:{},prefixes:AP,es5:t,lines:n}),this.logger=NP(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,xP.getRules)(),Ug.call(this,PP,e,"NOT SUPPORTED"),Ug.call(this,CP,e,"DEPRECATED","warn"),this._metaOpts=OP.call(this),e.formats&&TP.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&IP.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),RP.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,i=qg;n==="id"&&(i={...qg},i.id=i.$id,delete i.$id),t&&e&&this.addMetaSchema(i,i[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[t]||e:void 0}validate(e,t){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let i=n(t);return"$async"in n||(this.errors=n.errors),i}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return i.call(this,e,t);async function i(u,d){await s.call(this,u.$schema);let f=this._addSchema(u,d);return f.validate||o.call(this,f)}async function s(u){u&&!this.getSchema(u)&&await i.call(this,{$ref:u},!0)}async function o(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof Hg.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),o.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function c(u){let d=await l.call(this,u);this.refs[u]||await s.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,t)}async function l(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(e,t,n,i=this.opts.validateSchema){if(Array.isArray(e)){for(let o of e)this.addSchema(o,void 0,n,i);return this}let s;if(typeof e=="object"){let{schemaId:o}=this.opts;if(s=e[o],s!==void 0&&typeof s!="string")throw new Error(`schema ${o} must be string`)}return t=(0,ro.normalizeId)(t||s),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,i,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let i=this.validate(n,e);if(!i&&t){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return i}getSchema(e){let t;for(;typeof(t=Vg.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:n}=this.opts,i=new to.SchemaEnv({schema:{},schemaId:n});if(t=to.resolveSchema.call(this,i,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let t=Vg.call(this,e);return typeof t=="object"&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,ro.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e=="string")n=e,typeof t=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=n);else if(typeof e=="object"&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(FP.call(this,n,t),!t)return(0,qu.eachItem)(n,s=>ju.call(this,s)),this;qP.call(this,t);let i={...t,type:(0,Qa.getJSONTypes)(t.type),schemaType:(0,Qa.getJSONTypes)(t.schemaType)};return(0,qu.eachItem)(n,i.type.length===0?s=>ju.call(this,s,i):s=>i.type.forEach(o=>ju.call(this,s,i,o))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t=="object"?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let i=n.rules.findIndex(s=>s.keyword===e);i>=0&&n.rules.splice(i,1)}return this}addFormat(e,t){return typeof t=="string"&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,s)=>i+t+s)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of t){let s=i.split("/").slice(1),o=e;for(let a of s)o=o[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=o[a];l&&u&&(o[a]=Kg(u))}}return e}_removeAllSchemas(e,t){for(let n in e){let i=e[n];(!t||t.test(n))&&(typeof i=="string"?delete e[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete e[n]))}}_addSchema(e,t,n,i=this.opts.validateSchema,s=this.opts.addUsedSchema){let o,{schemaId:a}=this.opts;if(typeof e=="object")o=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,ro.normalizeId)(o||n);let l=ro.getSchemaRefs.call(this,e,n);return c=new to.SchemaEnv({schema:e,schemaId:a,meta:t,baseId:n,localRefs:l}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),i&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):to.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{to.compileSchema.call(this,e)}finally{this.opts=t}}};no.ValidationError=SP.default;no.MissingRefError=Hg.default;Fe.default=no;function Ug(r,e,t,n="error"){for(let i in r){let s=i;s in e&&this.logger[n](`${t}: option ${i}. ${r[s]}`)}}function Vg(r){return r=(0,ro.normalizeId)(r),this.schemas[r]||this.refs[r]}function RP(){let r=this.opts.schemas;if(r)if(Array.isArray(r))this.addSchema(r);else for(let e in r)this.addSchema(r[e],e)}function TP(){for(let r in this.opts.formats){let e=this.opts.formats[r];e&&this.addFormat(r,e)}}function IP(r){if(Array.isArray(r)){this.addVocabulary(r);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in r){let t=r[e];t.keyword||(t.keyword=e),this.addKeyword(t)}}function OP(){let r={...this.opts};for(let e of kP)delete r[e];return r}var DP={log(){},warn(){},error(){}};function NP(r){if(r===!1)return DP;if(r===void 0)return console;if(r.log&&r.warn&&r.error)return r;throw new Error("logger must implement log, warn and error methods")}var LP=/^[a-z_$][a-z0-9_$:-]*$/i;function FP(r,e){let{RULES:t}=this;if((0,qu.eachItem)(r,n=>{if(t.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!LP.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function ju(r,e,t){var n;let i=e?.post;if(t&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,o=i?s.post:s.rules.find(({type:c})=>c===t);if(o||(o={type:t,rules:[]},s.rules.push(o)),s.keywords[r]=!0,!e)return;let a={keyword:r,definition:{...e,type:(0,Qa.getJSONTypes)(e.type),schemaType:(0,Qa.getJSONTypes)(e.schemaType)}};e.before?jP.call(this,o,a,e.before):o.rules.push(a),s.all[r]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function jP(r,e,t){let n=r.rules.findIndex(i=>i.keyword===t);n>=0?r.rules.splice(n,0,e):(r.rules.push(e),this.logger.warn(`rule ${t} is not defined`))}function qP(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=Kg(e)),r.validateSchema=this.compile(e,!0))}var BP={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Kg(r){return{anyOf:[r,BP]}}});var Wg=k(Uu=>{"use strict";Object.defineProperty(Uu,"__esModule",{value:!0});var UP={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Uu.default=UP});var tc=k(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.callRef=ii.getValidate=void 0;var VP=Li(),Gg=jt(),mt=U(),qi=Ft(),Jg=Qs(),Za=Q(),HP={keyword:"$ref",schemaType:"string",code(r){let{gen:e,schema:t,it:n}=r,{baseId:i,schemaEnv:s,validateName:o,opts:a,self:c}=n,{root:l}=s;if((t==="#"||t==="#/")&&i===l.baseId)return d();let u=Jg.resolveRef.call(c,l,i,t);if(u===void 0)throw new VP.default(n.opts.uriResolver,i,t);if(u instanceof Jg.SchemaEnv)return f(u);return p(u);function d(){if(s===l)return ec(r,o,s,s.$async);let h=e.scopeValue("root",{ref:l});return ec(r,(0,mt._)`${h}.validate`,l,l.$async)}function f(h){let m=Yg(r,h);ec(r,m,h,h.$async)}function p(h){let m=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,mt.stringify)(h)}:{ref:h}),y=e.name("valid"),g=r.subschema({schema:h,dataTypes:[],schemaPath:mt.nil,topSchemaRef:m,errSchemaPath:t},y);r.mergeEvaluated(g),r.ok(y)}}};function Yg(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,mt._)`${t.scopeValue("wrapper",{ref:e})}.validate`}ii.getValidate=Yg;function ec(r,e,t,n){let{gen:i,it:s}=r,{allErrors:o,schemaEnv:a,opts:c}=s,l=c.passContext?qi.default.this:mt.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=i.let("valid");i.try(()=>{i.code((0,mt._)`await ${(0,Gg.callValidateCode)(r,e,l)}`),p(e),o||i.assign(h,!0)},m=>{i.if((0,mt._)`!(${m} instanceof ${s.ValidationError})`,()=>i.throw(m)),f(m),o||i.assign(h,!1)}),r.ok(h)}function d(){r.result((0,Gg.callValidateCode)(r,e,l),()=>p(e),()=>f(e))}function f(h){let m=(0,mt._)`${h}.errors`;i.assign(qi.default.vErrors,(0,mt._)`${qi.default.vErrors} === null ? ${m} : ${qi.default.vErrors}.concat(${m})`),i.assign(qi.default.errors,(0,mt._)`${qi.default.vErrors}.length`)}function p(h){var m;if(!s.opts.unevaluated)return;let y=(m=t?.validate)===null||m===void 0?void 0:m.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=Za.mergeEvaluated.props(i,y.props,s.props));else{let g=i.var("props",(0,mt._)`${h}.evaluated.props`);s.props=Za.mergeEvaluated.props(i,g,s.props,mt.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Za.mergeEvaluated.items(i,y.items,s.items));else{let g=i.var("items",(0,mt._)`${h}.evaluated.items`);s.items=Za.mergeEvaluated.items(i,g,s.items,mt.Name)}}}ii.callRef=ec;ii.default=HP});var Hu=k(Vu=>{"use strict";Object.defineProperty(Vu,"__esModule",{value:!0});var zP=Wg(),KP=tc(),WP=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",zP.default,KP.default];Vu.default=WP});var Xg=k(zu=>{"use strict";Object.defineProperty(zu,"__esModule",{value:!0});var rc=U(),mn=rc.operators,nc={maximum:{okStr:"<=",ok:mn.LTE,fail:mn.GT},minimum:{okStr:">=",ok:mn.GTE,fail:mn.LT},exclusiveMaximum:{okStr:"<",ok:mn.LT,fail:mn.GTE},exclusiveMinimum:{okStr:">",ok:mn.GT,fail:mn.LTE}},GP={message:({keyword:r,schemaCode:e})=>(0,rc.str)`must be ${nc[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,rc._)`{comparison: ${nc[r].okStr}, limit: ${e}}`},JP={keyword:Object.keys(nc),type:"number",schemaType:"number",$data:!0,error:GP,code(r){let{keyword:e,data:t,schemaCode:n}=r;r.fail$data((0,rc._)`${t} ${nc[e].fail} ${n} || isNaN(${t})`)}};zu.default=JP});var Qg=k(Ku=>{"use strict";Object.defineProperty(Ku,"__esModule",{value:!0});var io=U(),YP={message:({schemaCode:r})=>(0,io.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,io._)`{multipleOf: ${r}}`},XP={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:YP,code(r){let{gen:e,data:t,schemaCode:n,it:i}=r,s=i.opts.multipleOfPrecision,o=e.let("res"),a=s?(0,io._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,io._)`${o} !== parseInt(${o})`;r.fail$data((0,io._)`(${n} === 0 || (${o} = ${t}/${n}, ${a}))`)}};Ku.default=XP});var eb=k(Wu=>{"use strict";Object.defineProperty(Wu,"__esModule",{value:!0});function Zg(r){let e=r.length,t=0,n=0,i;for(;n=55296&&i<=56319&&n{"use strict";Object.defineProperty(Gu,"__esModule",{value:!0});var si=U(),QP=Q(),ZP=eb(),eC={message({keyword:r,schemaCode:e}){let t=r==="maxLength"?"more":"fewer";return(0,si.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:r})=>(0,si._)`{limit: ${r}}`},tC={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:eC,code(r){let{keyword:e,data:t,schemaCode:n,it:i}=r,s=e==="maxLength"?si.operators.GT:si.operators.LT,o=i.opts.unicode===!1?(0,si._)`${t}.length`:(0,si._)`${(0,QP.useFunc)(r.gen,ZP.default)}(${t})`;r.fail$data((0,si._)`${o} ${s} ${n}`)}};Gu.default=tC});var rb=k(Ju=>{"use strict";Object.defineProperty(Ju,"__esModule",{value:!0});var rC=jt(),nC=Q(),Bi=U(),iC={message:({schemaCode:r})=>(0,Bi.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,Bi._)`{pattern: ${r}}`},sC={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:iC,code(r){let{gen:e,data:t,$data:n,schema:i,schemaCode:s,it:o}=r,a=o.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=o.opts.code,l=c.code==="new RegExp"?(0,Bi._)`new RegExp`:(0,nC.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Bi._)`${l}(${s}, ${a}).test(${t})`),()=>e.assign(u,!1)),r.fail$data((0,Bi._)`!${u}`)}else{let c=(0,rC.usePattern)(r,i);r.fail$data((0,Bi._)`!${c}.test(${t})`)}}};Ju.default=sC});var nb=k(Yu=>{"use strict";Object.defineProperty(Yu,"__esModule",{value:!0});var so=U(),oC={message({keyword:r,schemaCode:e}){let t=r==="maxProperties"?"more":"fewer";return(0,so.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:r})=>(0,so._)`{limit: ${r}}`},aC={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:oC,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxProperties"?so.operators.GT:so.operators.LT;r.fail$data((0,so._)`Object.keys(${t}).length ${i} ${n}`)}};Yu.default=aC});var ib=k(Xu=>{"use strict";Object.defineProperty(Xu,"__esModule",{value:!0});var oo=jt(),ao=U(),cC=Q(),lC={message:({params:{missingProperty:r}})=>(0,ao.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,ao._)`{missingProperty: ${r}}`},dC={keyword:"required",type:"object",schemaType:"array",$data:!0,error:lC,code(r){let{gen:e,schema:t,schemaCode:n,data:i,$data:s,it:o}=r,{opts:a}=o;if(!s&&t.length===0)return;let c=t.length>=a.loopRequired;if(o.allErrors?l():u(),a.strictRequired){let p=r.parentSchema.properties,{definedProperties:h}=r.it;for(let m of t)if(p?.[m]===void 0&&!h.has(m)){let y=o.schemaEnv.baseId+o.errSchemaPath,g=`required property "${m}" is not defined at "${y}" (strictRequired)`;(0,cC.checkStrictMode)(o,g,o.opts.strictRequired)}}function l(){if(c||s)r.block$data(ao.nil,d);else for(let p of t)(0,oo.checkReportMissingProp)(r,p)}function u(){let p=e.let("missing");if(c||s){let h=e.let("valid",!0);r.block$data(h,()=>f(p,h)),r.ok(h)}else e.if((0,oo.checkMissingProp)(r,t,p)),(0,oo.reportMissingProp)(r,p),e.else()}function d(){e.forOf("prop",n,p=>{r.setParams({missingProperty:p}),e.if((0,oo.noPropertyInData)(e,i,p,a.ownProperties),()=>r.error())})}function f(p,h){r.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(h,(0,oo.propertyInData)(e,i,p,a.ownProperties)),e.if((0,ao.not)(h),()=>{r.error(),e.break()})},ao.nil)}}};Xu.default=dC});var sb=k(Qu=>{"use strict";Object.defineProperty(Qu,"__esModule",{value:!0});var co=U(),uC={message({keyword:r,schemaCode:e}){let t=r==="maxItems"?"more":"fewer";return(0,co.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:r})=>(0,co._)`{limit: ${r}}`},fC={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:uC,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxItems"?co.operators.GT:co.operators.LT;r.fail$data((0,co._)`${t}.length ${i} ${n}`)}};Qu.default=fC});var ic=k(Zu=>{"use strict";Object.defineProperty(Zu,"__esModule",{value:!0});var ob=mu();ob.code='require("ajv/dist/runtime/equal").default';Zu.default=ob});var ab=k(tf=>{"use strict";Object.defineProperty(tf,"__esModule",{value:!0});var ef=Ws(),je=U(),pC=Q(),hC=ic(),mC={message:({params:{i:r,j:e}})=>(0,je.str)`must NOT have duplicate items (items ## ${e} and ${r} are identical)`,params:({params:{i:r,j:e}})=>(0,je._)`{i: ${r}, j: ${e}}`},yC={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:mC,code(r){let{gen:e,data:t,$data:n,schema:i,parentSchema:s,schemaCode:o,it:a}=r;if(!n&&!i)return;let c=e.let("valid"),l=s.items?(0,ef.getSchemaTypes)(s.items):[];r.block$data(c,u,(0,je._)`${o} === false`),r.ok(c);function u(){let h=e.let("i",(0,je._)`${t}.length`),m=e.let("j");r.setParams({i:h,j:m}),e.assign(c,!0),e.if((0,je._)`${h} > 1`,()=>(d()?f:p)(h,m))}function d(){return l.length>0&&!l.some(h=>h==="object"||h==="array")}function f(h,m){let y=e.name("item"),g=(0,ef.checkDataTypes)(l,y,a.opts.strictNumbers,ef.DataType.Wrong),b=e.const("indices",(0,je._)`{}`);e.for((0,je._)`;${h}--;`,()=>{e.let(y,(0,je._)`${t}[${h}]`),e.if(g,(0,je._)`continue`),l.length>1&&e.if((0,je._)`typeof ${y} == "string"`,(0,je._)`${y} += "_"`),e.if((0,je._)`typeof ${b}[${y}] == "number"`,()=>{e.assign(m,(0,je._)`${b}[${y}]`),r.error(),e.assign(c,!1).break()}).code((0,je._)`${b}[${y}] = ${h}`)})}function p(h,m){let y=(0,pC.useFunc)(e,hC.default),g=e.name("outer");e.label(g).for((0,je._)`;${h}--;`,()=>e.for((0,je._)`${m} = ${h}; ${m}--;`,()=>e.if((0,je._)`${y}(${t}[${h}], ${t}[${m}])`,()=>{r.error(),e.assign(c,!1).break(g)})))}}};tf.default=yC});var cb=k(nf=>{"use strict";Object.defineProperty(nf,"__esModule",{value:!0});var rf=U(),gC=Q(),bC=ic(),vC={message:"must be equal to constant",params:({schemaCode:r})=>(0,rf._)`{allowedValue: ${r}}`},wC={keyword:"const",$data:!0,error:vC,code(r){let{gen:e,data:t,$data:n,schemaCode:i,schema:s}=r;n||s&&typeof s=="object"?r.fail$data((0,rf._)`!${(0,gC.useFunc)(e,bC.default)}(${t}, ${i})`):r.fail((0,rf._)`${s} !== ${t}`)}};nf.default=wC});var lb=k(sf=>{"use strict";Object.defineProperty(sf,"__esModule",{value:!0});var lo=U(),_C=Q(),SC=ic(),xC={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,lo._)`{allowedValues: ${r}}`},$C={keyword:"enum",schemaType:"array",$data:!0,error:xC,code(r){let{gen:e,data:t,$data:n,schema:i,schemaCode:s,it:o}=r;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let a=i.length>=o.opts.loopEnum,c,l=()=>c??(c=(0,_C.useFunc)(e,SC.default)),u;if(a||n)u=e.let("valid"),r.block$data(u,d);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let p=e.const("vSchema",s);u=(0,lo.or)(...i.map((h,m)=>f(p,m)))}r.pass(u);function d(){e.assign(u,!1),e.forOf("v",s,p=>e.if((0,lo._)`${l()}(${t}, ${p})`,()=>e.assign(u,!0).break()))}function f(p,h){let m=i[h];return typeof m=="object"&&m!==null?(0,lo._)`${l()}(${t}, ${p}[${h}])`:(0,lo._)`${t} === ${m}`}}};sf.default=$C});var af=k(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});var EC=Xg(),kC=Qg(),AC=tb(),PC=rb(),CC=nb(),MC=ib(),RC=sb(),TC=ab(),IC=cb(),OC=lb(),DC=[EC.default,kC.default,AC.default,PC.default,CC.default,MC.default,RC.default,TC.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},IC.default,OC.default];of.default=DC});var lf=k(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.validateAdditionalItems=void 0;var oi=U(),cf=Q(),NC={message:({params:{len:r}})=>(0,oi.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,oi._)`{limit: ${r}}`},LC={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:NC,code(r){let{parentSchema:e,it:t}=r,{items:n}=e;if(!Array.isArray(n)){(0,cf.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}db(r,n)}};function db(r,e){let{gen:t,schema:n,data:i,keyword:s,it:o}=r;o.items=!0;let a=t.const("len",(0,oi._)`${i}.length`);if(n===!1)r.setParams({len:e.length}),r.pass((0,oi._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,cf.alwaysValidSchema)(o,n)){let l=t.var("valid",(0,oi._)`${a} <= ${e.length}`);t.if((0,oi.not)(l),()=>c(l)),r.ok(l)}function c(l){t.forRange("i",e.length,a,u=>{r.subschema({keyword:s,dataProp:u,dataPropType:cf.Type.Num},l),o.allErrors||t.if((0,oi.not)(l),()=>t.break())})}}uo.validateAdditionalItems=db;uo.default=LC});var df=k(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.validateTuple=void 0;var ub=U(),sc=Q(),FC=jt(),jC={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return fb(r,"additionalItems",e);t.items=!0,!(0,sc.alwaysValidSchema)(t,e)&&r.ok((0,FC.validateArray)(r))}};function fb(r,e,t=r.schema){let{gen:n,parentSchema:i,data:s,keyword:o,it:a}=r;u(i),a.opts.unevaluated&&t.length&&a.items!==!0&&(a.items=sc.mergeEvaluated.items(n,t.length,a.items));let c=n.name("valid"),l=n.const("len",(0,ub._)`${s}.length`);t.forEach((d,f)=>{(0,sc.alwaysValidSchema)(a,d)||(n.if((0,ub._)`${l} > ${f}`,()=>r.subschema({keyword:o,schemaProp:f,dataProp:f},c)),r.ok(c))});function u(d){let{opts:f,errSchemaPath:p}=a,h=t.length,m=h===d.minItems&&(h===d.maxItems||d[e]===!1);if(f.strictTuples&&!m){let y=`"${o}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,sc.checkStrictMode)(a,y,f.strictTuples)}}}fo.validateTuple=fb;fo.default=jC});var pb=k(uf=>{"use strict";Object.defineProperty(uf,"__esModule",{value:!0});var qC=df(),BC={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,qC.validateTuple)(r,"items")};uf.default=BC});var mb=k(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var hb=U(),UC=Q(),VC=jt(),HC=lf(),zC={message:({params:{len:r}})=>(0,hb.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,hb._)`{limit: ${r}}`},KC={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:zC,code(r){let{schema:e,parentSchema:t,it:n}=r,{prefixItems:i}=t;n.items=!0,!(0,UC.alwaysValidSchema)(n,e)&&(i?(0,HC.validateAdditionalItems)(r,i):r.ok((0,VC.validateArray)(r)))}};ff.default=KC});var yb=k(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});var Bt=U(),oc=Q(),WC={message:({params:{min:r,max:e}})=>e===void 0?(0,Bt.str)`must contain at least ${r} valid item(s)`:(0,Bt.str)`must contain at least ${r} and no more than ${e} valid item(s)`,params:({params:{min:r,max:e}})=>e===void 0?(0,Bt._)`{minContains: ${r}}`:(0,Bt._)`{minContains: ${r}, maxContains: ${e}}`},GC={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:WC,code(r){let{gen:e,schema:t,parentSchema:n,data:i,it:s}=r,o,a,{minContains:c,maxContains:l}=n;s.opts.next?(o=c===void 0?1:c,a=l):o=1;let u=e.const("len",(0,Bt._)`${i}.length`);if(r.setParams({min:o,max:a}),a===void 0&&o===0){(0,oc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,oc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,oc.alwaysValidSchema)(s,t)){let m=(0,Bt._)`${u} >= ${o}`;a!==void 0&&(m=(0,Bt._)`${m} && ${u} <= ${a}`),r.pass(m);return}s.items=!0;let d=e.name("valid");a===void 0&&o===1?p(d,()=>e.if(d,()=>e.break())):o===0?(e.let(d,!0),a!==void 0&&e.if((0,Bt._)`${i}.length > 0`,f)):(e.let(d,!1),f()),r.result(d,()=>r.reset());function f(){let m=e.name("_valid"),y=e.let("count",0);p(m,()=>e.if(m,()=>h(y)))}function p(m,y){e.forRange("i",0,u,g=>{r.subschema({keyword:"contains",dataProp:g,dataPropType:oc.Type.Num,compositeRule:!0},m),y()})}function h(m){e.code((0,Bt._)`${m}++`),a===void 0?e.if((0,Bt._)`${m} >= ${o}`,()=>e.assign(d,!0).break()):(e.if((0,Bt._)`${m} > ${a}`,()=>e.assign(d,!1).break()),o===1?e.assign(d,!0):e.if((0,Bt._)`${m} >= ${o}`,()=>e.assign(d,!0)))}}};pf.default=GC});var ac=k(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.validateSchemaDeps=_r.validatePropertyDeps=_r.error=void 0;var hf=U(),JC=Q(),po=jt();_r.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let n=e===1?"property":"properties";return(0,hf.str)`must have ${n} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:n}})=>(0,hf._)`{property: ${r}, missingProperty: ${n}, depsCount: ${e}, - 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`--- + deps: ${t}}`};var YC={keyword:"dependencies",type:"object",schemaType:"object",error:_r.error,code(r){let[e,t]=XC(r);gb(r,e),bb(r,t)}};function XC({schema:r}){let e={},t={};for(let n in r){if(n==="__proto__")continue;let i=Array.isArray(r[n])?e:t;i[n]=r[n]}return[e,t]}function gb(r,e=r.schema){let{gen:t,data:n,it:i}=r;if(Object.keys(e).length===0)return;let s=t.let("missing");for(let o in e){let a=e[o];if(a.length===0)continue;let c=(0,po.propertyInData)(t,n,o,i.opts.ownProperties);r.setParams({property:o,depsCount:a.length,deps:a.join(", ")}),i.allErrors?t.if(c,()=>{for(let l of a)(0,po.checkReportMissingProp)(r,l)}):(t.if((0,hf._)`${c} && (${(0,po.checkMissingProp)(r,a,s)})`),(0,po.reportMissingProp)(r,s),t.else())}}_r.validatePropertyDeps=gb;function bb(r,e=r.schema){let{gen:t,data:n,keyword:i,it:s}=r,o=t.name("valid");for(let a in e)(0,JC.alwaysValidSchema)(s,e[a])||(t.if((0,po.propertyInData)(t,n,a,s.opts.ownProperties),()=>{let c=r.subschema({keyword:i,schemaProp:a},o);r.mergeValidEvaluated(c,o)},()=>t.var(o,!0)),r.ok(o))}_r.validateSchemaDeps=bb;_r.default=YC});var wb=k(mf=>{"use strict";Object.defineProperty(mf,"__esModule",{value:!0});var vb=U(),QC=Q(),ZC={message:"property name must be valid",params:({params:r})=>(0,vb._)`{propertyName: ${r.propertyName}}`},eM={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:ZC,code(r){let{gen:e,schema:t,data:n,it:i}=r;if((0,QC.alwaysValidSchema)(i,t))return;let s=e.name("valid");e.forIn("key",n,o=>{r.setParams({propertyName:o}),r.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},s),e.if((0,vb.not)(s),()=>{r.error(!0),i.allErrors||e.break()})}),r.ok(s)}};mf.default=eM});var gf=k(yf=>{"use strict";Object.defineProperty(yf,"__esModule",{value:!0});var cc=jt(),er=U(),tM=Ft(),lc=Q(),rM={message:"must NOT have additional properties",params:({params:r})=>(0,er._)`{additionalProperty: ${r.additionalProperty}}`},nM={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:rM,code(r){let{gen:e,schema:t,parentSchema:n,data:i,errsCount:s,it:o}=r;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,lc.alwaysValidSchema)(o,t))return;let l=(0,cc.allSchemaProperties)(n.properties),u=(0,cc.allSchemaProperties)(n.patternProperties);d(),r.ok((0,er._)`${s} === ${tM.default.errors}`);function d(){e.forIn("key",i,y=>{!l.length&&!u.length?h(y):e.if(f(y),()=>h(y))})}function f(y){let g;if(l.length>8){let b=(0,lc.schemaRefOrVal)(o,n.properties,"properties");g=(0,cc.isOwnProperty)(e,b,y)}else l.length?g=(0,er.or)(...l.map(b=>(0,er._)`${y} === ${b}`)):g=er.nil;return u.length&&(g=(0,er.or)(g,...u.map(b=>(0,er._)`${(0,cc.usePattern)(r,b)}.test(${y})`))),(0,er.not)(g)}function p(y){e.code((0,er._)`delete ${i}[${y}]`)}function h(y){if(c.removeAdditional==="all"||c.removeAdditional&&t===!1){p(y);return}if(t===!1){r.setParams({additionalProperty:y}),r.error(),a||e.break();return}if(typeof t=="object"&&!(0,lc.alwaysValidSchema)(o,t)){let g=e.name("valid");c.removeAdditional==="failing"?(m(y,g,!1),e.if((0,er.not)(g),()=>{r.reset(),p(y)})):(m(y,g),a||e.if((0,er.not)(g),()=>e.break()))}}function m(y,g,b){let v={keyword:"additionalProperties",dataProp:y,dataPropType:lc.Type.Str};b===!1&&Object.assign(v,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(v,g)}}};yf.default=nM});var xb=k(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0});var iM=Ni(),_b=jt(),bf=Q(),Sb=gf(),sM={keyword:"properties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,parentSchema:n,data:i,it:s}=r;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Sb.default.code(new iM.KeywordCxt(s,Sb.default,"additionalProperties"));let o=(0,_b.allSchemaProperties)(t);for(let d of o)s.definedProperties.add(d);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=bf.mergeEvaluated.props(e,(0,bf.toHash)(o),s.props));let a=o.filter(d=>!(0,bf.alwaysValidSchema)(s,t[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)l(d)?u(d):(e.if((0,_b.propertyInData)(e,i,d,s.opts.ownProperties)),u(d),s.allErrors||e.else().var(c,!0),e.endIf()),r.it.definedProperties.add(d),r.ok(c);function l(d){return s.opts.useDefaults&&!s.compositeRule&&t[d].default!==void 0}function u(d){r.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};vf.default=sM});var Ab=k(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0});var $b=jt(),dc=U(),Eb=Q(),kb=Q(),oM={keyword:"patternProperties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,data:n,parentSchema:i,it:s}=r,{opts:o}=s,a=(0,$b.allSchemaProperties)(t),c=a.filter(m=>(0,Eb.alwaysValidSchema)(s,t[m]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=o.strictSchema&&!o.allowMatchingProperties&&i.properties,u=e.name("valid");s.props!==!0&&!(s.props instanceof dc.Name)&&(s.props=(0,kb.evaluatedPropsToName)(e,s.props));let{props:d}=s;f();function f(){for(let m of a)l&&p(m),s.allErrors?h(m):(e.var(u,!0),h(m),e.if(u))}function p(m){for(let y in l)new RegExp(m).test(y)&&(0,Eb.checkStrictMode)(s,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function h(m){e.forIn("key",n,y=>{e.if((0,dc._)`${(0,$b.usePattern)(r,m)}.test(${y})`,()=>{let g=c.includes(m);g||r.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:kb.Type.Str},u),s.opts.unevaluated&&d!==!0?e.assign((0,dc._)`${d}[${y}]`,!0):!g&&!s.allErrors&&e.if((0,dc.not)(u),()=>e.break())})})}}};wf.default=oM});var Pb=k(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var aM=Q(),cM={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,aM.alwaysValidSchema)(n,t)){r.fail();return}let i=e.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),r.failResult(i,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};_f.default=cM});var Cb=k(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0});var lM=jt(),dM={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:lM.validateUnion,error:{message:"must match a schema in anyOf"}};Sf.default=dM});var Mb=k(xf=>{"use strict";Object.defineProperty(xf,"__esModule",{value:!0});var uc=U(),uM=Q(),fM={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,uc._)`{passingSchemas: ${r.passing}}`},pM={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:fM,code(r){let{gen:e,schema:t,parentSchema:n,it:i}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let s=t,o=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");r.setParams({passing:a}),e.block(l),r.result(o,()=>r.reset(),()=>r.error(!0));function l(){s.forEach((u,d)=>{let f;(0,uM.alwaysValidSchema)(i,u)?e.var(c,!0):f=r.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,uc._)`${c} && ${o}`).assign(o,!1).assign(a,(0,uc._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(a,d),f&&r.mergeEvaluated(f,uc.Name)})})}}};xf.default=pM});var Rb=k($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0});var hM=Q(),mM={keyword:"allOf",schemaType:"array",code(r){let{gen:e,schema:t,it:n}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");let i=e.name("valid");t.forEach((s,o)=>{if((0,hM.alwaysValidSchema)(n,s))return;let a=r.subschema({keyword:"allOf",schemaProp:o},i);r.ok(i),r.mergeEvaluated(a)})}};$f.default=mM});var Ob=k(Ef=>{"use strict";Object.defineProperty(Ef,"__esModule",{value:!0});var fc=U(),Ib=Q(),yM={message:({params:r})=>(0,fc.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,fc._)`{failingKeyword: ${r.ifClause}}`},gM={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:yM,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,Ib.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=Tb(n,"then"),s=Tb(n,"else");if(!i&&!s)return;let o=e.let("valid",!0),a=e.name("_valid");if(c(),r.reset(),i&&s){let u=e.let("ifClause");r.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else i?e.if(a,l("then")):e.if((0,fc.not)(a),l("else"));r.pass(o,()=>r.error(!0));function c(){let u=r.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);r.mergeEvaluated(u)}function l(u,d){return()=>{let f=r.subschema({keyword:u},a);e.assign(o,a),r.mergeValidEvaluated(f,o),d?e.assign(d,(0,fc._)`${u}`):r.setParams({ifClause:u})}}}};function Tb(r,e){let t=r.schema[e];return t!==void 0&&!(0,Ib.alwaysValidSchema)(r,t)}Ef.default=gM});var Db=k(kf=>{"use strict";Object.defineProperty(kf,"__esModule",{value:!0});var bM=Q(),vM={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,bM.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};kf.default=vM});var Pf=k(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});var wM=lf(),_M=pb(),SM=df(),xM=mb(),$M=yb(),EM=ac(),kM=wb(),AM=gf(),PM=xb(),CM=Ab(),MM=Pb(),RM=Cb(),TM=Mb(),IM=Rb(),OM=Ob(),DM=Db();function NM(r=!1){let e=[MM.default,RM.default,TM.default,IM.default,OM.default,DM.default,kM.default,AM.default,EM.default,PM.default,CM.default];return r?e.push(_M.default,xM.default):e.push(wM.default,SM.default),e.push($M.default),e}Af.default=NM});var Mf=k(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});ho.dynamicAnchor=void 0;var Cf=U(),LM=Ft(),Nb=Qs(),FM=tc(),jM={keyword:"$dynamicAnchor",schemaType:"string",code:r=>Lb(r,r.schema)};function Lb(r,e){let{gen:t,it:n}=r;n.schemaEnv.root.dynamicAnchors[e]=!0;let i=(0,Cf._)`${LM.default.dynamicAnchors}${(0,Cf.getProperty)(e)}`,s=n.errSchemaPath==="#"?n.validateName:qM(r);t.if((0,Cf._)`!${i}`,()=>t.assign(i,s))}ho.dynamicAnchor=Lb;function qM(r){let{schemaEnv:e,schema:t,self:n}=r.it,{root:i,baseId:s,localRefs:o,meta:a}=e.root,{schemaId:c}=n.opts,l=new Nb.SchemaEnv({schema:t,schemaId:c,root:i,baseId:s,localRefs:o,meta:a});return Nb.compileSchema.call(n,l),(0,FM.getValidate)(r,l)}ho.default=jM});var Rf=k(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.dynamicRef=void 0;var Fb=U(),BM=Ft(),jb=tc(),UM={keyword:"$dynamicRef",schemaType:"string",code:r=>qb(r,r.schema)};function qb(r,e){let{gen:t,keyword:n,it:i}=r;if(e[0]!=="#")throw new Error(`"${n}" only supports hash fragment reference`);let s=e.slice(1);if(i.allErrors)o();else{let c=t.let("valid",!1);o(c),r.ok(c)}function o(c){if(i.schemaEnv.root.dynamicAnchors[s]){let l=t.let("_v",(0,Fb._)`${BM.default.dynamicAnchors}${(0,Fb.getProperty)(s)}`);t.if(l,a(l,c),a(i.validateName,c))}else a(i.validateName,c)()}function a(c,l){return l?()=>t.block(()=>{(0,jb.callRef)(r,c),t.let(l,!0)}):()=>(0,jb.callRef)(r,c)}}mo.dynamicRef=qb;mo.default=UM});var Bb=k(Tf=>{"use strict";Object.defineProperty(Tf,"__esModule",{value:!0});var VM=Mf(),HM=Q(),zM={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,VM.dynamicAnchor)(r,""):(0,HM.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};Tf.default=zM});var Ub=k(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var KM=Rf(),WM={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,KM.dynamicRef)(r,r.schema)};If.default=WM});var Vb=k(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var GM=Mf(),JM=Rf(),YM=Bb(),XM=Ub(),QM=[GM.default,JM.default,YM.default,XM.default];Of.default=QM});var zb=k(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var Hb=ac(),ZM={keyword:"dependentRequired",type:"object",schemaType:"object",error:Hb.error,code:r=>(0,Hb.validatePropertyDeps)(r)};Df.default=ZM});var Kb=k(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var e1=ac(),t1={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,e1.validateSchemaDeps)(r)};Nf.default=t1});var Wb=k(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var r1=Q(),n1={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,r1.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};Lf.default=n1});var Gb=k(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var i1=zb(),s1=Kb(),o1=Wb(),a1=[i1.default,s1.default,o1.default];Ff.default=a1});var Yb=k(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var yn=U(),Jb=Q(),c1=Ft(),l1={message:"must NOT have unevaluated properties",params:({params:r})=>(0,yn._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},d1={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:l1,code(r){let{gen:e,schema:t,data:n,errsCount:i,it:s}=r;if(!i)throw new Error("ajv implementation error");let{allErrors:o,props:a}=s;a instanceof yn.Name?e.if((0,yn._)`${a} !== true`,()=>e.forIn("key",n,d=>e.if(l(a,d),()=>c(d)))):a!==!0&&e.forIn("key",n,d=>a===void 0?c(d):e.if(u(a,d),()=>c(d))),s.props=!0,r.ok((0,yn._)`${i} === ${c1.default.errors}`);function c(d){if(t===!1){r.setParams({unevaluatedProperty:d}),r.error(),o||e.break();return}if(!(0,Jb.alwaysValidSchema)(s,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:d,dataPropType:Jb.Type.Str},f),o||e.if((0,yn.not)(f),()=>e.break())}}function l(d,f){return(0,yn._)`!${d} || !${d}[${f}]`}function u(d,f){let p=[];for(let h in d)d[h]===!0&&p.push((0,yn._)`${f} !== ${h}`);return(0,yn.and)(...p)}}};jf.default=d1});var Qb=k(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var ai=U(),Xb=Q(),u1={message:({params:{len:r}})=>(0,ai.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,ai._)`{limit: ${r}}`},f1={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:u1,code(r){let{gen:e,schema:t,data:n,it:i}=r,s=i.items||0;if(s===!0)return;let o=e.const("len",(0,ai._)`${n}.length`);if(t===!1)r.setParams({len:s}),r.fail((0,ai._)`${o} > ${s}`);else if(typeof t=="object"&&!(0,Xb.alwaysValidSchema)(i,t)){let c=e.var("valid",(0,ai._)`${o} <= ${s}`);e.if((0,ai.not)(c),()=>a(c,s)),r.ok(c)}i.items=!0;function a(c,l){e.forRange("i",l,o,u=>{r.subschema({keyword:"unevaluatedItems",dataProp:u,dataPropType:Xb.Type.Num},c),i.allErrors||e.if((0,ai.not)(c),()=>e.break())})}}};qf.default=f1});var Zb=k(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var p1=Yb(),h1=Qb(),m1=[p1.default,h1.default];Bf.default=m1});var ev=k(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var xe=U(),y1={message:({schemaCode:r})=>(0,xe.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,xe._)`{format: ${r}}`},g1={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:y1,code(r,e){let{gen:t,data:n,$data:i,schema:s,schemaCode:o,it:a}=r,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;i?f():p();function f(){let h=t.scopeValue("formats",{ref:d.formats,code:c.code.formats}),m=t.const("fDef",(0,xe._)`${h}[${o}]`),y=t.let("fType"),g=t.let("format");t.if((0,xe._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>t.assign(y,(0,xe._)`${m}.type || "string"`).assign(g,(0,xe._)`${m}.validate`),()=>t.assign(y,(0,xe._)`"string"`).assign(g,m)),r.fail$data((0,xe.or)(b(),v()));function b(){return c.strictSchema===!1?xe.nil:(0,xe._)`${o} && !${g}`}function v(){let S=u.$async?(0,xe._)`(${m}.async ? await ${g}(${n}) : ${g}(${n}))`:(0,xe._)`${g}(${n})`,_=(0,xe._)`(typeof ${g} == "function" ? ${S} : ${g}.test(${n}))`;return(0,xe._)`${g} && ${g} !== true && ${y} === ${e} && !${_}`}}function p(){let h=d.formats[s];if(!h){b();return}if(h===!0)return;let[m,y,g]=v(h);m===e&&r.pass(S());function b(){if(c.strictSchema===!1){d.logger.warn(_());return}throw new Error(_());function _(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function v(_){let E=_ instanceof RegExp?(0,xe.regexpCode)(_):c.code.formats?(0,xe._)`${c.code.formats}${(0,xe.getProperty)(s)}`:void 0,A=t.scopeValue("formats",{key:s,ref:_,code:E});return typeof _=="object"&&!(_ instanceof RegExp)?[_.type||"string",_.validate,(0,xe._)`${A}.validate`]:["string",_,A]}function S(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!u.$async)throw new Error("async format in sync schema");return(0,xe._)`await ${g}(${n})`}return typeof y=="function"?(0,xe._)`${g}(${n})`:(0,xe._)`${g}.test(${n})`}}}};Uf.default=g1});var Hf=k(Vf=>{"use strict";Object.defineProperty(Vf,"__esModule",{value:!0});var b1=ev(),v1=[b1.default];Vf.default=v1});var zf=k(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.contentVocabulary=Ui.metadataVocabulary=void 0;Ui.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Ui.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var rv=k(Kf=>{"use strict";Object.defineProperty(Kf,"__esModule",{value:!0});var w1=Hu(),_1=af(),S1=Pf(),x1=Vb(),$1=Gb(),E1=Zb(),k1=Hf(),tv=zf(),A1=[x1.default,w1.default,_1.default,(0,S1.default)(!0),k1.default,tv.metadataVocabulary,tv.contentVocabulary,$1.default,E1.default];Kf.default=A1});var iv=k(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});pc.DiscrError=void 0;var nv;(function(r){r.Tag="tag",r.Mapping="mapping"})(nv||(pc.DiscrError=nv={}))});var Jf=k(Gf=>{"use strict";Object.defineProperty(Gf,"__esModule",{value:!0});var Vi=U(),Wf=iv(),sv=Qs(),P1=Li(),C1=Q(),M1={message:({params:{discrError:r,tagName:e}})=>r===Wf.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,Vi._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},R1={keyword:"discriminator",type:"object",schemaType:"object",error:M1,code(r){let{gen:e,data:t,schema:n,parentSchema:i,it:s}=r,{oneOf:o}=i;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,Vi._)`${t}${(0,Vi.getProperty)(a)}`);e.if((0,Vi._)`typeof ${l} == "string"`,()=>u(),()=>r.error(!1,{discrError:Wf.DiscrError.Tag,tag:l,tagName:a})),r.ok(c);function u(){let p=f();e.if(!1);for(let h in p)e.elseIf((0,Vi._)`${l} === ${h}`),e.assign(c,d(p[h]));e.else(),r.error(!1,{discrError:Wf.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function d(p){let h=e.name("valid"),m=r.subschema({keyword:"oneOf",schemaProp:p},h);return r.mergeEvaluated(m,Vi.Name),h}function f(){var p;let h={},m=g(i),y=!0;for(let S=0;S{T1.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var av=k((zq,I1)=>{I1.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var cv=k((Kq,O1)=>{O1.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var lv=k((Wq,D1)=>{D1.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var dv=k((Gq,N1)=>{N1.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var uv=k((Jq,L1)=>{L1.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var fv=k((Yq,F1)=>{F1.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var pv=k((Xq,j1)=>{j1.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var hv=k(Yf=>{"use strict";Object.defineProperty(Yf,"__esModule",{value:!0});var q1=ov(),B1=av(),U1=cv(),V1=lv(),H1=dv(),z1=uv(),K1=fv(),W1=pv(),G1=["/properties"];function J1(r){return[q1,B1,U1,V1,H1,e(this,z1),K1,e(this,W1)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,n){return r?t.$dataMetaSchema(n,G1):n}}Yf.default=J1});var Zf=k((ye,Qf)=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.MissingRefError=ye.ValidationError=ye.CodeGen=ye.Name=ye.nil=ye.stringify=ye.str=ye._=ye.KeywordCxt=ye.Ajv2020=void 0;var Y1=Bu(),X1=rv(),Q1=Jf(),Z1=hv(),Xf="https://json-schema.org/draft/2020-12/schema",Hi=class extends Y1.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),X1.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Q1.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(Z1.default.call(this,e),this.refs["http://json-schema.org/schema"]=Xf)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Xf)?Xf:void 0)}};ye.Ajv2020=Hi;Qf.exports=ye=Hi;Qf.exports.Ajv2020=Hi;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=Hi;var eR=Ni();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return eR.KeywordCxt}});var zi=U();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return zi._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return zi.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return zi.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return zi.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return zi.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return zi.CodeGen}});var tR=Xs();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return tR.default}});var rR=Li();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return rR.default}})});var Sv=k(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.formatNames=xr.fastFormats=xr.fullFormats=void 0;function Sr(r,e){return{validate:r,compare:e}}xr.fullFormats={date:Sr(bv,np),time:Sr(tp(!0),ip),"date-time":Sr(mv(!0),wv),"iso-time":Sr(tp(),vv),"iso-date-time":Sr(mv(),_v),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:cR,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:mR,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:lR,int32:{type:"number",validate:fR},int64:{type:"number",validate:pR},float:{type:"number",validate:gv},double:{type:"number",validate:gv},password:!0,binary:!0};xr.fastFormats={...xr.fullFormats,date:Sr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,np),time:Sr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ip),"date-time":Sr(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,wv),"iso-time":Sr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,vv),"iso-date-time":Sr(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,_v),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};xr.formatNames=Object.keys(xr.fullFormats);function nR(r){return r%4===0&&(r%100!==0||r%400===0)}var iR=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,sR=[0,31,28,31,30,31,30,31,31,30,31,30,31];function bv(r){let e=iR.exec(r);if(!e)return!1;let t=+e[1],n=+e[2],i=+e[3];return n>=1&&n<=12&&i>=1&&i<=(n===2&&nR(t)?29:sR[n])}function np(r,e){if(r&&e)return r>e?1:r23||u>59||r&&!a)return!1;if(i<=23&&s<=59&&o<60)return!0;let d=s-u*c,f=i-l*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&o<61}}function ip(r,e){if(!(r&&e))return;let t=new Date("2020-01-01T"+r).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(t&&n)return t-n}function vv(r,e){if(!(r&&e))return;let t=ep.exec(r),n=ep.exec(e);if(t&&n)return r=t[1]+t[2]+t[3],e=n[1]+n[2]+n[3],r>e?1:r=dR}function pR(r){return Number.isInteger(r)}function gv(){return!0}var hR=/[^\\]\\Z/;function mR(r){if(hR.test(r))return!1;try{return new RegExp(r),!0}catch{return!1}}});var $v=k(sp=>{"use strict";Object.defineProperty(sp,"__esModule",{value:!0});var yR=Hu(),gR=af(),bR=Pf(),vR=Hf(),xv=zf(),wR=[yR.default,gR.default,(0,bR.default)(),vR.default,xv.metadataVocabulary,xv.contentVocabulary];sp.default=wR});var Ev=k((tB,_R)=>{_R.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var Av=k((ge,op)=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.MissingRefError=ge.ValidationError=ge.CodeGen=ge.Name=ge.nil=ge.stringify=ge.str=ge._=ge.KeywordCxt=ge.Ajv=void 0;var SR=Bu(),xR=$v(),$R=Jf(),kv=Ev(),ER=["/properties"],hc="http://json-schema.org/draft-07/schema",Ki=class extends SR.default{_addVocabularies(){super._addVocabularies(),xR.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword($R.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(kv,ER):kv;this.addMetaSchema(e,hc,!1),this.refs["http://json-schema.org/schema"]=hc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(hc)?hc:void 0)}};ge.Ajv=Ki;op.exports=ge=Ki;op.exports.Ajv=Ki;Object.defineProperty(ge,"__esModule",{value:!0});ge.default=Ki;var kR=Ni();Object.defineProperty(ge,"KeywordCxt",{enumerable:!0,get:function(){return kR.KeywordCxt}});var Wi=U();Object.defineProperty(ge,"_",{enumerable:!0,get:function(){return Wi._}});Object.defineProperty(ge,"str",{enumerable:!0,get:function(){return Wi.str}});Object.defineProperty(ge,"stringify",{enumerable:!0,get:function(){return Wi.stringify}});Object.defineProperty(ge,"nil",{enumerable:!0,get:function(){return Wi.nil}});Object.defineProperty(ge,"Name",{enumerable:!0,get:function(){return Wi.Name}});Object.defineProperty(ge,"CodeGen",{enumerable:!0,get:function(){return Wi.CodeGen}});var AR=Xs();Object.defineProperty(ge,"ValidationError",{enumerable:!0,get:function(){return AR.default}});var PR=Li();Object.defineProperty(ge,"MissingRefError",{enumerable:!0,get:function(){return PR.default}})});var Pv=k(Gi=>{"use strict";Object.defineProperty(Gi,"__esModule",{value:!0});Gi.formatLimitDefinition=void 0;var CR=Av(),tr=U(),gn=tr.operators,mc={formatMaximum:{okStr:"<=",ok:gn.LTE,fail:gn.GT},formatMinimum:{okStr:">=",ok:gn.GTE,fail:gn.LT},formatExclusiveMaximum:{okStr:"<",ok:gn.LT,fail:gn.GTE},formatExclusiveMinimum:{okStr:">",ok:gn.GT,fail:gn.LTE}},MR={message:({keyword:r,schemaCode:e})=>(0,tr.str)`should be ${mc[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,tr._)`{comparison: ${mc[r].okStr}, limit: ${e}}`};Gi.formatLimitDefinition={keyword:Object.keys(mc),type:"string",schemaType:"string",$data:!0,error:MR,code(r){let{gen:e,data:t,schemaCode:n,keyword:i,it:s}=r,{opts:o,self:a}=s;if(!o.validateFormats)return;let c=new CR.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let f=e.scopeValue("formats",{ref:a.formats,code:o.code.formats}),p=e.const("fmt",(0,tr._)`${f}[${c.schemaCode}]`);r.fail$data((0,tr.or)((0,tr._)`typeof ${p} != "object"`,(0,tr._)`${p} instanceof RegExp`,(0,tr._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let f=c.schema,p=a.formats[f];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${i}": format "${f}" does not define "compare" function`);let h=e.scopeValue("formats",{key:f,ref:p,code:o.code.formats?(0,tr._)`${o.code.formats}${(0,tr.getProperty)(f)}`:void 0});r.fail$data(d(h))}function d(f){return(0,tr._)`${f}.compare(${t}, ${n}) ${mc[i].fail} 0`}},dependencies:["format"]};var RR=r=>(r.addKeyword(Gi.formatLimitDefinition),r);Gi.default=RR});var lp=k((yo,Rv)=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});var Ji=Sv(),TR=Pv(),ap=U(),Cv=new ap.Name("fullFormats"),IR=new ap.Name("fastFormats"),cp=(r,e={keywords:!0})=>{if(Array.isArray(e))return Mv(r,e,Ji.fullFormats,Cv),r;let[t,n]=e.mode==="fast"?[Ji.fastFormats,IR]:[Ji.fullFormats,Cv],i=e.formats||Ji.formatNames;return Mv(r,i,t,n),e.keywords&&(0,TR.default)(r),r};cp.get=(r,e="full")=>{let n=(e==="fast"?Ji.fastFormats:Ji.fullFormats)[r];if(!n)throw new Error(`Unknown format "${r}"`);return n};function Mv(r,e,t,n){var i,s;(i=(s=r.opts.code).formats)!==null&&i!==void 0||(s.formats=(0,ap._)`require("ajv-formats/dist/formats").${n}`);for(let o of e)r.addFormat(o,t[o])}Rv.exports=yo=cp;Object.defineProperty(yo,"__esModule",{value:!0});yo.default=cp});var go=k((nB,Nv)=>{"use strict";var Tv="[^\\\\/]",OR="(?=.)",Iv="[^/]",dp="(?:\\/|$)",Ov="(?:^|\\/)",up=`\\.{1,2}${dp}`,DR="(?!\\.)",NR=`(?!${Ov}${up})`,LR=`(?!\\.{0,1}${dp})`,FR=`(?!${up})`,jR="[^.\\/]",qR=`${Iv}*?`,BR="/",Dv={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:OR,QMARK:Iv,END_ANCHOR:dp,DOTS_SLASH:up,NO_DOT:DR,NO_DOTS:NR,NO_DOT_SLASH:LR,NO_DOTS_SLASH:FR,QMARK_NO_DOT:jR,STAR:qR,START_ANCHOR:Ov,SEP:BR},UR={...Dv,SLASH_LITERAL:"[\\\\/]",QMARK:Tv,STAR:`${Tv}*?`,DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},VR={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};Nv.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:VR,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(r){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${r.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(r){return r===!0?UR:Dv}}});var bo=k(yt=>{"use strict";var{REGEX_BACKSLASH:HR,REGEX_REMOVE_BACKSLASH:zR,REGEX_SPECIAL_CHARS:KR,REGEX_SPECIAL_CHARS_GLOBAL:WR}=go();yt.isObject=r=>r!==null&&typeof r=="object"&&!Array.isArray(r);yt.hasRegexChars=r=>KR.test(r);yt.isRegexChar=r=>r.length===1&&yt.hasRegexChars(r);yt.escapeRegex=r=>r.replace(WR,"\\$1");yt.toPosixSlashes=r=>r.replace(HR,"/");yt.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let r=navigator.platform.toLowerCase();return r==="win32"||r==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":!1};yt.removeBackslashes=r=>r.replace(zR,e=>e==="\\"?"":e);yt.escapeLast=(r,e,t)=>{let n=r.lastIndexOf(e,t);return n===-1?r:r[n-1]==="\\"?yt.escapeLast(r,e,n-1):`${r.slice(0,n)}\\${r.slice(n)}`};yt.removePrefix=(r,e={})=>{let t=r;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};yt.wrapOutput=(r,e={},t={})=>{let n=t.contains?"":"^",i=t.contains?"":"$",s=`${n}(?:${r})${i}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s};yt.basename=(r,{windows:e}={})=>{let t=r.split(e?/[\\/]/:"/"),n=t[t.length-1];return n===""?t[t.length-2]:n}});var Hv=k((sB,Vv)=>{"use strict";var Lv=bo(),{CHAR_ASTERISK:fp,CHAR_AT:GR,CHAR_BACKWARD_SLASH:Yi,CHAR_COMMA:JR,CHAR_DOT:pp,CHAR_EXCLAMATION_MARK:hp,CHAR_FORWARD_SLASH:Uv,CHAR_LEFT_CURLY_BRACE:mp,CHAR_LEFT_PARENTHESES:yc,CHAR_LEFT_SQUARE_BRACKET:YR,CHAR_PLUS:XR,CHAR_QUESTION_MARK:Fv,CHAR_RIGHT_CURLY_BRACE:QR,CHAR_RIGHT_PARENTHESES:jv,CHAR_RIGHT_SQUARE_BRACKET:ZR}=go(),qv=r=>r===Uv||r===Yi,Bv=r=>{r.isPrefix!==!0&&(r.depth=r.isGlobstar?1/0:1)},eT=(r,e)=>{let t=e||{},n=r.length-1,i=t.parts===!0||t.tokens===!0||t.scanToEnd===!0,s=[],o=[],a=[],c=r,l=-1,u=0,d=0,f=!1,p=!1,h=!1,m=!1,y=!1,g=!1,b=!1,v=!1,S=!1,_=!1,E=0,A,x,R={value:"",depth:0,isGlob:!1},$=()=>l>=n,q=()=>c.charCodeAt(l+1),M=()=>(A=x,c.charCodeAt(++l));for(;l0&&(P=c.slice(0,u),c=c.slice(u),d-=u),V&&h===!0&&d>0?(V=c.slice(0,d),C=c.slice(d)):h===!0?(V="",C=c):V=c,V&&V!==""&&V!=="/"&&V!==c&&qv(V.charCodeAt(V.length-1))&&(V=V.slice(0,-1)),t.unescape===!0&&(C&&(C=Lv.removeBackslashes(C)),V&&b===!0&&(V=Lv.removeBackslashes(V)));let Ve={prefix:P,input:r,start:u,base:V,glob:C,isBrace:f,isBracket:p,isGlob:h,isExtglob:m,isGlobstar:y,negated:v,negatedExtglob:S};if(t.tokens===!0&&(Ve.maxDepth=0,qv(x)||o.push(R),Ve.tokens=o),t.parts===!0||t.tokens===!0){let ce;for(let Ae=0;Ae=u&&(a.push(zn),ce=Ns)}let dt=ce!==void 0?ce+1:u,kt=r.slice(dt);a.push(kt),t.tokens&&ce&&ce+1{"use strict";var vo=go(),At=bo(),{MAX_LENGTH:gc,POSIX_REGEX_SOURCE:tT,REGEX_NON_SPECIAL_CHARS:rT,REGEX_SPECIAL_CHARS_BACKREF:nT,REPLACEMENTS:zv}=vo,iT=(r,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...r,e);r.sort();let t=`[${r.join("-")}]`;try{new RegExp(t)}catch{return r.map(i=>At.escapeRegex(i)).join("..")}return t},Xi=(r,e)=>`Missing ${r}: "${e}" - use "\\\\${e}" to match literal characters`,Kv=r=>{let e=[],t=0,n=0,i=0,s="",o=!1;for(let a of r){if(o===!0){s+=a,o=!1;continue}if(a==="\\"){s+=a,o=!0;continue}if(a==='"'){i=i===1?0:1,s+=a;continue}if(i===0){if(a==="[")t++;else if(a==="]"&&t>0)t--;else if(t===0){if(a==="(")n++;else if(a===")"&&n>0)n--;else if(a==="|"&&n===0){e.push(s),s="";continue}}}s+=a}return e.push(s),e},sT=r=>{let e=!1;for(let t of r){if(e===!0){e=!1;continue}if(t==="\\"){e=!0;continue}if(/[?*+@!()[\]{}]/.test(t))return!1}return!0},gp=r=>{let e=r.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(sT(e))return e.replace(/\\(.)/g,"$1")},oT=r=>{let e=r.map(gp).filter(Boolean);for(let t=0;t{if(r[0]!=="+"&&r[0]!=="*"||r[1]!=="(")return;let t=0,n=0,i=0,s=!1;for(let o=1;o0){t--;continue}if(!(t>0)){if(a==="("){n++;continue}if(a===")"&&(n--,n===0))return e===!0&&o!==r.length-1?void 0:{type:r[0],body:r.slice(2,o),end:o}}}}},aT=r=>`${r.length===1?At.escapeRegex(r[0]):`[${r.map(t=>At.escapeRegex(t)).join("")}]`}*`,cT=r=>{let e=0,t=[];for(;eo.trim());if(i.length!==1)return;let s=gp(i[0]);if(!s||s.length!==1)return;t.push(s),e+=n.end+1}if(!(t.length<1))return t},lT=r=>{let e=0,t=r.trim(),n=yp(t);for(;n;)e++,t=n.body.trim(),n=yp(t);return e},dT=(r,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:vo.DEFAULT_MAX_EXTGLOB_RECURSION,n=Kv(r).map(a=>a.trim());if(n.length>1&&(n.some(a=>a==="")||n.some(a=>/^[*?]+$/.test(a))||oT(n)))return{risky:!0};let i=[],s=!1,o=!0;for(let a of n){let c=cT(a);if(c){s=!0,i.push(...c);continue}let l=gp(a);if(l&&l.length===1){i.push(l);continue}if(o=!1,lT(a)>t)return{risky:!0}}return s?o?{risky:!0,safeOutput:aT([...new Set(i)])}:{risky:!0}:{risky:!1}},bp=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a string");r=zv[r]||r;let t={...e},n=typeof t.maxLength=="number"?Math.min(gc,t.maxLength):gc,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);let s={type:"bos",value:"",output:t.prepend||""},o=[s],a=t.capture?"":"?:",c=vo.globChars(t.windows),l=vo.extglobChars(c),{DOT_LITERAL:u,PLUS_LITERAL:d,SLASH_LITERAL:f,ONE_CHAR:p,DOTS_SLASH:h,NO_DOT:m,NO_DOT_SLASH:y,NO_DOTS_SLASH:g,QMARK:b,QMARK_NO_DOT:v,STAR:S,START_ANCHOR:_}=c,E=I=>`(${a}(?:(?!${_}${I.dot?h:u}).)*?)`,A=t.dot?"":m,x=t.dot?b:v,R=t.bash===!0?E(t):S;t.capture&&(R=`(${R})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let $={input:r,index:-1,start:0,dot:t.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:o};r=At.removePrefix(r,$),i=r.length;let q=[],M=[],V=[],P=s,C,Ve=()=>$.index===i-1,ce=$.peek=(I=1)=>r[$.index+I],dt=$.advance=()=>r[++$.index]||"",kt=()=>r.slice($.index+1),Ae=(I="",ve=0)=>{$.consumed+=I,$.index+=ve},ki=I=>{$.output+=I.output!=null?I.output:I.value,Ae(I.value)},Ns=()=>{let I=1;for(;ce()==="!"&&(ce(2)!=="("||ce(3)==="?");)dt(),$.start++,I++;return I%2===0?!1:($.negated=!0,$.start++,!0)},zn=I=>{$[I]++,V.push(I)},cn=I=>{$[I]--,V.pop()},Z=I=>{if(P.type==="globstar"){let ve=$.braces>0&&(I.type==="comma"||I.type==="brace"),T=I.extglob===!0||q.length&&(I.type==="pipe"||I.type==="paren");I.type!=="slash"&&I.type!=="paren"&&!ve&&!T&&($.output=$.output.slice(0,-P.output.length),P.type="star",P.value="*",P.output=R,$.output+=P.output)}if(q.length&&I.type!=="paren"&&(q[q.length-1].inner+=I.value),(I.value||I.output)&&ki(I),P&&P.type==="text"&&I.type==="text"){P.output=(P.output||P.value)+I.value,P.value+=I.value;return}I.prev=P,o.push(I),P=I},Ca=(I,ve)=>{let T={...l[ve],conditions:1,inner:""};T.prev=P,T.parens=$.parens,T.output=$.output,T.startIndex=$.index,T.tokensIndex=o.length;let ee=(t.capture?"(":"")+T.open;zn("parens"),Z({type:I,value:ve,output:$.output?"":p}),Z({type:"paren",extglob:!0,value:dt(),output:ee}),q.push(T)},Z$=I=>{let ve=r.slice(I.startIndex,$.index+1),T=r.slice(I.startIndex+2,$.index),ee=dT(T,t);if((I.type==="plus"||I.type==="star")&&ee.risky){let ue=ee.safeOutput?(I.output?"":p)+(t.capture?`(${ee.safeOutput})`:ee.safeOutput):void 0,gr=o[I.tokensIndex];gr.type="text",gr.value=ve,gr.output=ue||At.escapeRegex(ve);for(let Kn=I.tokensIndex+1;Kn1&&I.inner.includes("/")&&(ue=E(t)),(ue!==R||Ve()||/^\)+$/.test(kt()))&&(he=I.close=`)$))${ue}`),I.inner.includes("*")&&(Pe=kt())&&/^\.[^\\/.]+$/.test(Pe)){let gr=bp(Pe,{...e,fastpaths:!1}).output;he=I.close=`)${gr})${ue})`}I.prev.type==="bos"&&($.negatedExtglob=!0)}Z({type:"paren",extglob:!0,value:C,output:he}),cn("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(r)){let I=!1,ve=r.replace(nT,(T,ee,he,Pe,ue,gr)=>Pe==="\\"?(I=!0,T):Pe==="?"?ee?ee+Pe+(ue?b.repeat(ue.length):""):gr===0?x+(ue?b.repeat(ue.length):""):b.repeat(he.length):Pe==="."?u.repeat(he.length):Pe==="*"?ee?ee+Pe+(ue?R:""):R:ee?T:`\\${T}`);return I===!0&&(t.unescape===!0?ve=ve.replace(/\\/g,""):ve=ve.replace(/\\+/g,T=>T.length%2===0?"\\\\":T?"\\":"")),ve===r&&t.contains===!0?($.output=r,$):($.output=At.wrapOutput(ve,$,e),$)}for(;!Ve();){if(C=dt(),C==="\0")continue;if(C==="\\"){let T=ce();if(T==="/"&&t.bash!==!0||T==="."||T===";")continue;if(!T){C+="\\",Z({type:"text",value:C});continue}let ee=/^\\+/.exec(kt()),he=0;if(ee&&ee[0].length>2&&(he=ee[0].length,$.index+=he,he%2!==0&&(C+="\\")),t.unescape===!0?C=dt():C+=dt(),$.brackets===0){Z({type:"text",value:C});continue}}if($.brackets>0&&(C!=="]"||P.value==="["||P.value==="[^")){if(t.posix!==!1&&C===":"){let T=P.value.slice(1);if(T.includes("[")&&(P.posix=!0,T.includes(":"))){let ee=P.value.lastIndexOf("["),he=P.value.slice(0,ee),Pe=P.value.slice(ee+2),ue=tT[Pe];if(ue){P.value=he+ue,$.backtrack=!0,dt(),!s.output&&o.indexOf(P)===1&&(s.output=p);continue}}}(C==="["&&ce()!==":"||C==="-"&&ce()==="]")&&(C=`\\${C}`),C==="]"&&(P.value==="["||P.value==="[^")&&(C=`\\${C}`),t.posix===!0&&C==="!"&&P.value==="["&&(C="^"),P.value+=C,ki({value:C});continue}if($.quotes===1&&C!=='"'){C=At.escapeRegex(C),P.value+=C,ki({value:C});continue}if(C==='"'){$.quotes=$.quotes===1?0:1,t.keepQuotes===!0&&Z({type:"text",value:C});continue}if(C==="("){zn("parens"),Z({type:"paren",value:C});continue}if(C===")"){if($.parens===0&&t.strictBrackets===!0)throw new SyntaxError(Xi("opening","("));let T=q[q.length-1];if(T&&$.parens===T.parens+1){Z$(q.pop());continue}Z({type:"paren",value:C,output:$.parens?")":"\\)"}),cn("parens");continue}if(C==="["){if(t.nobracket===!0||!kt().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(Xi("closing","]"));C=`\\${C}`}else zn("brackets");Z({type:"bracket",value:C});continue}if(C==="]"){if(t.nobracket===!0||P&&P.type==="bracket"&&P.value.length===1){Z({type:"text",value:C,output:`\\${C}`});continue}if($.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(Xi("opening","["));Z({type:"text",value:C,output:`\\${C}`});continue}cn("brackets");let T=P.value.slice(1);if(P.posix!==!0&&T[0]==="^"&&!T.includes("/")&&(C=`/${C}`),P.value+=C,ki({value:C}),t.literalBrackets===!1||At.hasRegexChars(T))continue;let ee=At.escapeRegex(P.value);if($.output=$.output.slice(0,-P.value.length),t.literalBrackets===!0){$.output+=ee,P.value=ee;continue}P.value=`(${a}${ee}|${P.value})`,$.output+=P.value;continue}if(C==="{"&&t.nobrace!==!0){zn("braces");let T={type:"brace",value:C,output:"(",outputIndex:$.output.length,tokensIndex:$.tokens.length};M.push(T),Z(T);continue}if(C==="}"){let T=M[M.length-1];if(t.nobrace===!0||!T){Z({type:"text",value:C,output:C});continue}let ee=")";if(T.dots===!0){let he=o.slice(),Pe=[];for(let ue=he.length-1;ue>=0&&(o.pop(),he[ue].type!=="brace");ue--)he[ue].type!=="dots"&&Pe.unshift(he[ue].value);ee=iT(Pe,t),$.backtrack=!0}if(T.comma!==!0&&T.dots!==!0){let he=$.output.slice(0,T.outputIndex),Pe=$.tokens.slice(T.tokensIndex);T.value=T.output="\\{",C=ee="\\}",$.output=he;for(let ue of Pe)$.output+=ue.output||ue.value}Z({type:"brace",value:C,output:ee}),cn("braces"),M.pop();continue}if(C==="|"){q.length>0&&q[q.length-1].conditions++,Z({type:"text",value:C});continue}if(C===","){let T=C,ee=M[M.length-1];ee&&V[V.length-1]==="braces"&&(ee.comma=!0,T="|"),Z({type:"comma",value:C,output:T});continue}if(C==="/"){if(P.type==="dot"&&$.index===$.start+1){$.start=$.index+1,$.consumed="",$.output="",o.pop(),P=s;continue}Z({type:"slash",value:C,output:f});continue}if(C==="."){if($.braces>0&&P.type==="dot"){P.value==="."&&(P.output=u);let T=M[M.length-1];P.type="dots",P.output+=C,P.value+=C,T.dots=!0;continue}if($.braces+$.parens===0&&P.type!=="bos"&&P.type!=="slash"){Z({type:"text",value:C,output:u});continue}Z({type:"dot",value:C,output:u});continue}if(C==="?"){if(!(P&&P.value==="(")&&t.noextglob!==!0&&ce()==="("&&ce(2)!=="?"){Ca("qmark",C);continue}if(P&&P.type==="paren"){let ee=ce(),he=C;(P.value==="("&&!/[!=<:]/.test(ee)||ee==="<"&&!/<([!=]|\w+>)/.test(kt()))&&(he=`\\${C}`),Z({type:"text",value:C,output:he});continue}if(t.dot!==!0&&(P.type==="slash"||P.type==="bos")){Z({type:"qmark",value:C,output:v});continue}Z({type:"qmark",value:C,output:b});continue}if(C==="!"){if(t.noextglob!==!0&&ce()==="("&&(ce(2)!=="?"||!/[!=<:]/.test(ce(3)))){Ca("negate",C);continue}if(t.nonegate!==!0&&$.index===0){Ns();continue}}if(C==="+"){if(t.noextglob!==!0&&ce()==="("&&ce(2)!=="?"){Ca("plus",C);continue}if(P&&P.value==="("||t.regex===!1){Z({type:"plus",value:C,output:d});continue}if(P&&(P.type==="bracket"||P.type==="paren"||P.type==="brace")||$.parens>0){Z({type:"plus",value:C});continue}Z({type:"plus",value:d});continue}if(C==="@"){if(t.noextglob!==!0&&ce()==="("&&ce(2)!=="?"){Z({type:"at",extglob:!0,value:C,output:""});continue}Z({type:"text",value:C});continue}if(C!=="*"){(C==="$"||C==="^")&&(C=`\\${C}`);let T=rT.exec(kt());T&&(C+=T[0],$.index+=T[0].length),Z({type:"text",value:C});continue}if(P&&(P.type==="globstar"||P.star===!0)){P.type="star",P.star=!0,P.value+=C,P.output=R,$.backtrack=!0,$.globstar=!0,Ae(C);continue}let I=kt();if(t.noextglob!==!0&&/^\([^?]/.test(I)){Ca("star",C);continue}if(P.type==="star"){if(t.noglobstar===!0){Ae(C);continue}let T=P.prev,ee=T.prev,he=T.type==="slash"||T.type==="bos",Pe=ee&&(ee.type==="star"||ee.type==="globstar");if(t.bash===!0&&(!he||I[0]&&I[0]!=="/")){Z({type:"star",value:C,output:""});continue}let ue=$.braces>0&&(T.type==="comma"||T.type==="brace"),gr=q.length&&(T.type==="pipe"||T.type==="paren");if(!he&&T.type!=="paren"&&!ue&&!gr){Z({type:"star",value:C,output:""});continue}for(;I.slice(0,3)==="/**";){let Ai=r[$.index+4];if(Ai&&Ai!=="/")break;I=I.slice(3),Ae("/**",3)}let Kn=Ve()||$.parens>0&&I===")".repeat($.parens)&&!q.some(Ai=>Ai.type==="negate");if(T.type==="bos"&&Ve()){P.type="globstar",P.value+=C,P.output=E(t),$.output=P.output,$.globstar=!0,Ae(C);continue}if(T.type==="slash"&&T.prev.type!=="bos"&&!Pe&&Kn){$.output=$.output.slice(0,-(T.output+P.output).length),T.output=`(?:${T.output}`,P.type="globstar",P.output=E(t)+(t.strictSlashes?")":"|$)"),P.value+=C,$.globstar=!0,$.output+=T.output+P.output,Ae(C);continue}if(T.type==="slash"&&T.prev.type!=="bos"&&I[0]==="/"){let Ai=I[1]!==void 0?"|$":"";$.output=$.output.slice(0,-(T.output+P.output).length),T.output=`(?:${T.output}`,P.type="globstar",P.output=`${E(t)}${f}|${f}${Ai})`,P.value+=C,$.output+=T.output+P.output,$.globstar=!0,Ae(C+dt()),Z({type:"slash",value:"/",output:""});continue}if(T.type==="bos"&&I[0]==="/"){P.type="globstar",P.value+=C,P.output=`(?:^|${f}|${E(t)}${f})`,$.output=P.output,$.globstar=!0,Ae(C+dt()),Z({type:"slash",value:"/",output:""});continue}$.output=$.output.slice(0,-P.output.length),P.type="globstar",P.output=E(t),P.value+=C,$.output+=P.output,$.globstar=!0,Ae(C);continue}let ve={type:"star",value:C,output:R};if(t.bash===!0){ve.output=".*?",(P.type==="bos"||P.type==="slash")&&(ve.output=A+ve.output),Z(ve);continue}if(P&&(P.type==="bracket"||P.type==="paren")&&t.regex===!0){ve.output=C,Z(ve);continue}($.index===$.start||P.type==="slash"||P.type==="dot")&&(P.type==="dot"?($.output+=y,P.output+=y):t.dot===!0?($.output+=g,P.output+=g):($.output+=A,P.output+=A),ce()!=="*"&&($.output+=p,P.output+=p)),Z(ve)}for(;$.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(Xi("closing","]"));$.output=At.escapeLast($.output,"["),cn("brackets")}for(;$.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(Xi("closing",")"));$.output=At.escapeLast($.output,"("),cn("parens")}for(;$.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(Xi("closing","}"));$.output=At.escapeLast($.output,"{"),cn("braces")}if(t.strictSlashes!==!0&&(P.type==="star"||P.type==="bracket")&&Z({type:"maybe_slash",value:"",output:`${f}?`}),$.backtrack===!0){$.output="";for(let I of $.tokens)$.output+=I.output!=null?I.output:I.value,I.suffix&&($.output+=I.suffix)}return $};bp.fastpaths=(r,e)=>{let t={...e},n=typeof t.maxLength=="number"?Math.min(gc,t.maxLength):gc,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);r=zv[r]||r;let{DOT_LITERAL:s,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:c,NO_DOT:l,NO_DOTS:u,NO_DOTS_SLASH:d,STAR:f,START_ANCHOR:p}=vo.globChars(t.windows),h=t.dot?u:l,m=t.dot?d:l,y=t.capture?"":"?:",g={negated:!1,prefix:""},b=t.bash===!0?".*?":f;t.capture&&(b=`(${b})`);let v=A=>A.noglobstar===!0?b:`(${y}(?:(?!${p}${A.dot?c:s}).)*?)`,S=A=>{switch(A){case"*":return`${h}${a}${b}`;case".*":return`${s}${a}${b}`;case"*.*":return`${h}${b}${s}${a}${b}`;case"*/*":return`${h}${b}${o}${a}${m}${b}`;case"**":return h+v(t);case"**/*":return`(?:${h}${v(t)}${o})?${m}${a}${b}`;case"**/*.*":return`(?:${h}${v(t)}${o})?${m}${b}${s}${a}${b}`;case"**/.*":return`(?:${h}${v(t)}${o})?${s}${a}${b}`;default:{let x=/^(.*?)\.(\w+)$/.exec(A);if(!x)return;let R=S(x[1]);return R?R+s+x[2]:void 0}}},_=At.removePrefix(r,g),E=S(_);return E&&t.strictSlashes!==!0&&(E+=`${o}?`),E};Wv.exports=bp});var Xv=k((aB,Yv)=>{"use strict";var uT=Hv(),vp=Gv(),Jv=bo(),fT=go(),pT=r=>r&&typeof r=="object"&&!Array.isArray(r),$e=(r,e,t=!1)=>{if(Array.isArray(r)){let u=r.map(f=>$e(f,e,t));return f=>{for(let p of u){let h=p(f);if(h)return h}return!1}}let n=pT(r)&&r.tokens&&r.input;if(r===""||typeof r!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let i=e||{},s=i.windows,o=n?$e.compileRe(r,e):$e.makeRe(r,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(i.ignore){let u={...e,ignore:null,onMatch:null,onResult:null};c=$e(i.ignore,u,t)}let l=(u,d=!1)=>{let{isMatch:f,match:p,output:h}=$e.test(u,o,e,{glob:r,posix:s}),m={glob:r,state:a,regex:o,posix:s,input:u,output:h,match:p,isMatch:f};return typeof i.onResult=="function"&&i.onResult(m),f===!1?(m.isMatch=!1,d?m:!1):c(u)?(typeof i.onIgnore=="function"&&i.onIgnore(m),m.isMatch=!1,d?m:!1):(typeof i.onMatch=="function"&&i.onMatch(m),d?m:!0)};return t&&(l.state=a),l};$e.test=(r,e,t,{glob:n,posix:i}={})=>{if(typeof r!="string")throw new TypeError("Expected input to be a string");if(r==="")return{isMatch:!1,output:""};let s=t||{},o=s.format||(i?Jv.toPosixSlashes:null),a=r===n,c=a&&o?o(r):r;return a===!1&&(c=o?o(r):r,a=c===n),(a===!1||s.capture===!0)&&(s.matchBase===!0||s.basename===!0?a=$e.matchBase(r,e,t,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};$e.matchBase=(r,e,t,n=t&&t.windows)=>(e instanceof RegExp?e:$e.makeRe(e,t)).test(Jv.basename(r,{windows:n}));$e.isMatch=(r,e,t)=>$e(e,t)(r);$e.parse=(r,e)=>Array.isArray(r)?r.map(t=>$e.parse(t,e)):vp(r,{...e,fastpaths:!1});$e.scan=(r,e)=>uT(r,e);$e.compileRe=(r,e,t=!1,n=!1)=>{if(t===!0)return r.output;let i=e||{},s=i.contains?"":"^",o=i.contains?"":"$",a=`${s}(?:${r.output})${o}`;r&&r.negated===!0&&(a=`^(?!${a}).*$`);let c=$e.toRegex(a,e);return n===!0&&(c.state=r),c};$e.makeRe=(r,e={},t=!1,n=!1)=>{if(!r||typeof r!="string")throw new TypeError("Expected a non-empty string");let i={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(r[0]==="."||r[0]==="*")&&(i.output=vp.fastpaths(r,e)),i.output||(i=vp(r,e)),$e.compileRe(i,e,t,n)};$e.toRegex=(r,e)=>{try{let t=e||{};return new RegExp(r,t.flags||(t.nocase?"i":""))}catch(t){if(e&&e.debug===!0)throw t;return/$^/}};$e.constants=fT;Yv.exports=$e});var wp=k((cB,ew)=>{"use strict";var Qv=Xv(),hT=bo();function Zv(r,e,t=!1){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:hT.isWindows()}),Qv(r,e,t)}Object.assign(Zv,Qv);ew.exports=Zv});function _p(r,e){return mT(e.split("/"),r.split("/"))}function mT(r,e){let t=0,n=0,i=-1,s=0;for(;t=0)n=i+1,t=++s;else return!1;for(;e[n]==="**";)n++;return n===e.length}function yT(r,e){let t=[...r],n=bT([...e]),i=0,s=0,o=-1,a=0;for(;i=0)s=o+1,i=++a;else return!1;for(;n[s]==="*";)s++;return s===n.length}function gT(r,e){if(r===void 0)return!1;if(typeof r=="string")return r==="?"||r===e;let t=wo(e);return r.ranges.some(([n,i])=>n<=t&&t<=i)!==r.negated}function bT(r){let e=[];for(let t=0;t{});var gw={};ly(gw,{MdbasePathError:()=>So,applyReadDefaults:()=>zT,buildInitialFrontmatter:()=>Dp,buildTypeTemplate:()=>Op,buildUniqueNotePath:()=>Lp,coerceFieldInput:()=>xc,createNoteFromType:()=>JT,createTypeDefinition:()=>KT,ensureCollectionInitialized:()=>xo,fieldsFromV03Schema:()=>vn,formatMarkdown:()=>gt,getPromptFields:()=>Np,getTopLevelFieldFromIssuePath:()=>Fp,getTypesForFile:()=>Ge,isExcluded:()=>bt,loadContractDefinitions:()=>Mp,loadMdbaseConfig:()=>ci,loadTypeDefinitions:()=>Cp,normalizeSafeRelativePath:()=>bn,parseFrontmatter:()=>Me,readCollectionRecords:()=>Pp,resolveFilenameForType:()=>hw,resolveFolderForType:()=>pw,schemaFromV03Fields:()=>Zi,slugify:()=>kp,v03TypeDefFromFrontmatter:()=>_c,validateCollection:()=>Ip,validateFile:()=>Sc,validateRecordAgainstType:()=>es});function _T(){return _o||(_o=new nw.Ajv2020({allErrors:!0,strict:!1,allowUnionTypes:!0}),(0,iw.default)(_o),_o)}function K(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Ne(r){return JSON.parse(JSON.stringify(r))}function ST(r){if(r===!0)return!0;if(r===!1)return!1;if(r==="warn")return"warn"}function Sp(r){return Array.isArray(r)?`[${r.map(e=>Sp(e)).join(",")}]`:K(r)?`{${Object.keys(r).sort().map(t=>`${JSON.stringify(t)}:${Sp(r[t])}`).join(",")}}`:JSON.stringify(r)}function xT(r){let e=r.indexOf("."),t=r.indexOf("[");return e===-1&&t===-1?r:e===-1?r.slice(0,t):t===-1?r.slice(0,e):r.slice(0,Math.min(e,t))}function $T(r){let e=new Map,t=new Set,n=i=>{let s=e.get(i);if(s)return s;let o=r.get(i);if(!o)return null;if(t.has(i)){let l={...o,fields:Ne(o.fields)};return e.set(i,l),l}t.add(i);let a=o.extends?n(o.extends):null;t.delete(i);let c={...o,fields:a?{...Ne(a.fields),...Ne(o.fields)}:Ne(o.fields),display_name_key:o.display_name_key??a?.display_name_key,path_pattern:o.path_pattern??a?.path_pattern,filename_pattern:o.filename_pattern??a?.filename_pattern,strict:o.strict!==void 0?o.strict:a?.strict,match:o.match??a?.match};return e.set(i,c),c};for(let i of r.keys())n(i);return e}function sw(r){let e=(0,oe.normalizePath)(r),t=e.lastIndexOf("/");return t>=0?e.slice(0,t):""}function ow(r){let e=r.trim();e.startsWith("[[")&&e.endsWith("]]")&&(e=e.slice(2,-2));let t=e.indexOf("|");t>=0&&(e=e.slice(0,t));let n=e.indexOf("#");return n>=0&&(e=e.slice(0,n)),e.trim()}function aw(r){return/^[a-z][a-z0-9+.-]*:\/\//i.test(r)}function cw(r,e,t){let n=ow(t);if(!n||aw(n))return null;let i=new Set,s=(0,oe.normalizePath)(n);i.add(s),s.endsWith(".md")||i.add(`${s}.md`);let o=sw(e);if(o){let c=(0,oe.normalizePath)(`${o}/${n}`);i.add(c),c.endsWith(".md")||i.add(`${c}.md`)}for(let c of i){let l=r.getAbstractFileByPath(c);if(l instanceof oe.TFile)return l}let a=n.replace(/\.md$/i,"");return r.getMarkdownFiles().find(c=>c.basename===a)??null}function ET(r,e,t){return aw(ow(t))||cw(r,e,t)!==null}function Me(r){let e=(0,oe.getFrontMatterInfo)(r);if(!e.exists)return{hasFrontmatter:!1,frontmatter:{},body:r};try{let t=e.frontmatter,n=(0,oe.parseYaml)(t);return n==null&&t.trim()!==""?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e.contentStart),error:"Frontmatter must be a YAML object"}:n!=null&&!K(n)?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e.contentStart),error:"Frontmatter must be a YAML object"}:{hasFrontmatter:!0,frontmatter:n??{},body:r.slice(e.contentStart)}}catch(t){return{hasFrontmatter:!0,frontmatter:{},body:r.slice(e.contentStart),error:t instanceof Error?t.message:String(t)}}}function gt(r,e=""){if(Object.keys(r).length===0)return e;let t=(0,oe.stringifyYaml)(r).trimEnd(),n=e.replace(/^\n+/,"");return`--- ${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(!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} +${n}`}async function ci(r){let e=r.getAbstractFileByPath("mdbase.yaml");if(!(e instanceof oe.TFile))return null;try{let t=await r.cachedRead(e),n=(0,oe.parseYaml)(t);if(!K(n))return null;let i=K(n.settings)?n.settings:{},s=K(n.runtime)?n.runtime:void 0;return{spec_version:typeof n.spec_version=="string"?n.spec_version:Ur.spec_version,name:typeof n.name=="string"?n.name:Ur.name,description:typeof n.description=="string"?n.description:Ur.description,runtime:s?{profile_version:typeof s.profile_version=="string"?s.profile_version:void 0,enabled:typeof s.enabled=="boolean"?s.enabled:void 0,policy:typeof s.policy=="string"?s.policy:void 0}:void 0,settings:{types_folder:typeof i.types_folder=="string"?i.types_folder:Ur.settings.types_folder,contracts_folder:typeof i.contracts_folder=="string"?i.contracts_folder:Ur.settings.contracts_folder,explicit_type_keys:Array.isArray(i.explicit_type_keys)?i.explicit_type_keys.filter(o=>typeof o=="string"):[...Ur.settings.explicit_type_keys],...typeof i.default_strict=="boolean"?{default_strict:i.default_strict}:{},...typeof i.include_subfolders=="boolean"?{include_subfolders:i.include_subfolders}:{},exclude:Array.isArray(i.exclude)?i.exclude.filter(o=>typeof o=="string"):Tp(n.spec_version)?[]:[...wT]}}}catch{return null}}async function xo(r,e={}){let t=[];if(!(r.getAbstractFileByPath("mdbase.yaml")instanceof oe.TFile)){let l=(0,oe.stringifyYaml)(Ur).trimEnd()+` +`;await r.create("mdbase.yaml",l),t.push("mdbase.yaml")}let i=await ci(r)??Ur,s=i.settings.types_folder;await r.adapter.exists(s)||(await r.createFolder(s),t.push(s));let a=(0,oe.normalizePath)(`${s}/note.md`);if(!await r.adapter.exists(a)&&e.seedNoteType!==!1){let l=Op("note",void 0,i.spec_version);await r.create(a,l),t.push(a)}return{created:t}}function lw(r,e){let t=K(r)?r:{},n=Array.isArray(t.type)?t.type.find(s=>s!=="null"):t.type,i={required:e};return Array.isArray(t.enum)?(i.type="enum",i.values=Ne(t.enum)):n==="array"?(i.type="list",i.items=lw(t.items,!1)):n==="object"?(i.type="object",i.fields=vn(t)):n==="string"&&t.format==="date"?i.type="date":n==="string"&&t.format==="date-time"?i.type="datetime":n==="string"&&t.format==="time"?i.type="time":typeof n=="string"?i.type=n:i.type="any",t.default!==void 0&&(i.default=Ne(t.default)),typeof t.description=="string"&&(i.description=t.description),typeof t.minimum=="number"&&(i.min=t.minimum),typeof t.maximum=="number"&&(i.max=t.maximum),typeof t.minLength=="number"&&(i.min_length=t.minLength),typeof t.maxLength=="number"&&(i.max_length=t.maxLength),typeof t.pattern=="string"&&(i.pattern=t.pattern),typeof t.minItems=="number"&&(i.min_length=t.minItems),typeof t.maxItems=="number"&&(i.max_length=t.maxItems),i}function vn(r){let e=K(r.properties)?r.properties:{},t=new Set(Array.isArray(r.required)?r.required.filter(n=>typeof n=="string"):[]);return Object.fromEntries(Object.entries(e).map(([n,i])=>[n,lw(i,t.has(n))]))}function dw(r,e){let t={...Ne(e)},n=r.type??"string",i=()=>{delete t.properties,delete t.required,delete t.additionalProperties},s=()=>{delete t.items};if(n==="enum")delete t.type,t.enum=Ne(r.values??[]),delete t.format,i(),s();else if(n==="list")t.type="array",delete t.enum,delete t.format,i(),t.items=dw(r.items??{type:"any"},K(t.items)?t.items:{});else if(n==="object"){t.type="object",delete t.enum,delete t.format,s();let c=Zi(r.fields??{},K(t)?t:{},!1);t.properties=c.properties,c.required?t.required=c.required:delete t.required}else n==="link"?(t.type="string",delete t.enum,delete t.format,i(),s()):["date","datetime","time"].includes(n)?(t.type="string",t.format=n==="datetime"?"date-time":n,delete t.enum,i(),s()):["string","integer","number","boolean"].includes(n)?(t.type=n,delete t.format,delete t.enum,i(),s()):(delete t.type,delete t.enum,delete t.format,i(),s());r.default!==void 0?t.default=Ne(r.default):delete t.default,typeof r.description=="string"&&r.description.trim()?t.description=r.description:delete t.description;let o=n==="integer"||n==="number";o&&typeof r.min=="number"?t.minimum=r.min:delete t.minimum,o&&typeof r.max=="number"?t.maximum=r.max:delete t.maximum;let a=["string","link","date","datetime","time"].includes(n);return n==="list"&&typeof r.min_length=="number"?t.minItems=r.min_length:delete t.minItems,n==="list"&&typeof r.max_length=="number"?t.maxItems=r.max_length:delete t.maxItems,a&&typeof r.min_length=="number"?t.minLength=r.min_length:delete t.minLength,a&&typeof r.max_length=="number"?t.maxLength=r.max_length:delete t.maxLength,a&&typeof r.pattern=="string"?t.pattern=r.pattern:delete t.pattern,t}function Zi(r,e={},t=!1){let n=K(e.properties)?e.properties:{},i=Object.create(null),s=[];for(let[a,c]of Object.entries(r))i[a]=dw(c,K(n[a])?n[a]:{}),c.required===!0&&s.push(a);let o={...Ne(e),type:"object",properties:i,additionalProperties:!t};return s.length>0?o.required=s:delete o.required,o}function uw(r,e){if(!e)return r;if(!e.startsWith("/"))return;let t=r;for(let n of e.slice(1).split("/")){let i=n.replace(/~1/g,"/").replace(/~0/g,"~");if(Array.isArray(t)){let s=Number(i);if(!Number.isInteger(s)||s<0||s>=t.length)return;t=t[s]}else if(K(t)&&i in t)t=t[i];else return}return t}async function fw(r,e,t){let[n,i=""]=t.split("#",2);if(!n||/^[a-z][a-z0-9+.-]*:/i.test(n)||n.startsWith("/"))return null;let s=sw(e),o=[];for(let l of`${s}/${n}`.replace(/\\/g,"/").split("/"))if(!(!l||l==="."))if(l===".."){if(o.length===0)return null;o.pop()}else o.push(l);let a=(0,oe.normalizePath)(o.join("/")),c=r.getAbstractFileByPath(a);if(!(c instanceof oe.TFile))return null;try{let l=JSON.parse(await r.cachedRead(c)),u=uw(l,i);return K(u)?u:null}catch{return null}}function _c(r,e,t){let n=K(r.collection)?Ne(r.collection):void 0,i=vn(t);for(let s of n?.unique??[])typeof s.field=="string"&&i[s.field]&&(i[s.field].unique=!0,i[s.field].unique_scope=s.scope);for(let[s,o]of Object.entries(n?.links??{}))i[s]&&(i[s].target=o.target_type,i[s].validate_exists=o.validate_exists);return{name:String(r.name),version:typeof r.version=="number"?r.version:void 0,description:typeof r.description=="string"?r.description:void 0,display_name_key:n?.display?.name_field,path_pattern:n?.path?.pattern,strict:t.additionalProperties===!1,match:K(r.match)?r.match:void 0,fields:i,filePath:e,specProfile:"v0.3",schema:Ne(t),collection:n,originalFrontmatter:Ne(r)}}async function Pp(r,e){let t=[],n=performance.now();for(let i of r.getMarkdownFiles()){if(performance.now()-n>=8&&(await new Promise(o=>setTimeout(o,0)),n=performance.now()),bt(i.path,e))continue;let s=Me(await r.cachedRead(i));s.error||t.push({path:i.path,frontmatter:s.frontmatter})}return t}function es(r,e,t){let n=[];return yw(r,e,t,n),n}async function Cp(r,e){let t=new Map,n=`${(0,oe.normalizePath)(e.settings.types_folder)}/`;for(let i of r.getMarkdownFiles()){if(!i.path.startsWith(n))continue;let s=await r.cachedRead(i),o=Me(s);if(!o.hasFrontmatter||o.error)continue;let a=o.frontmatter;if(e.spec_version.startsWith("0.3.")){if(a.kind!=="mdbase.type"||typeof a.name!="string"||!K(a.schema))continue;let u=a.schema,d=K(u.value)?u.value:null;if(!d&&typeof u.ref=="string"&&(d=await fw(r,i.path,u.ref)),!d)continue;t.set(a.name,_c(a,i.path,d));continue}if(!K(a.fields))continue;let c=typeof a.name=="string"&&a.name.trim().length>0?a.name.trim():i.basename,l={};for(let[u,d]of Object.entries(a.fields))K(d)&&(l[u]=d);t.set(c,{name:c,extends:typeof a.extends=="string"?a.extends:void 0,display_name_key:typeof a.display_name_key=="string"?a.display_name_key:void 0,path_pattern:typeof a.path_pattern=="string"?a.path_pattern:void 0,filename_pattern:typeof a.filename_pattern=="string"?a.filename_pattern:void 0,strict:ST(a.strict),match:K(a.match)?a.match:void 0,fields:l,filePath:i.path,specProfile:"v0.2",originalFrontmatter:Ne(a)})}return $T(t)}async function Mp(r,e){let t=new Map,n=`${(0,oe.normalizePath)(e.settings.contracts_folder||"_contracts")}/`;for(let i of r.getMarkdownFiles()){if(!i.path.startsWith(n))continue;let s=Me(await r.cachedRead(i));if(!s.hasFrontmatter||s.error)continue;let o=s.frontmatter;if(o.kind!=="mdbase.contract"||o.contract_type!=="record"||typeof o.id!="string"||typeof o.version!="string")continue;let a=K(o.record_schema)?o.record_schema:{},c=K(o.binding_schema)?o.binding_schema:void 0,l=await rw(r,i.path,a);if(!l)continue;let u=c?await rw(r,i.path,c):null,d=`${o.id}@${o.version}`;t.set(d,{contract_type:"record",id:o.id,version:o.version,digest:typeof o.digest=="string"?o.digest:"",schema:l,...u?{binding_schema:u}:{},implementations:[]})}return t}async function rw(r,e,t){return K(t.value)?Ne(t.value):typeof t.ref!="string"?null:fw(r,e,t.ref)}function kT(r,e){for(let t of e){let n=r[t];if(Array.isArray(n))return n.filter(s=>typeof s=="string")}for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim().length>0)return[n.trim()]}return null}function Rp(r,e){return r.replace(/\{([^}]+)\}/g,(t,n)=>{let i=e[n];return i==null?"":Array.isArray(i)?i.filter(s=>["string","number","boolean"].includes(typeof s)).map(String).join("-"):typeof i=="string"?i:typeof i=="number"||typeof i=="boolean"?String(i):""})}function bn(r){let e=r.replace(/\\/g,"/");if(!e||e.startsWith("/")||/^[A-Za-z]:\//.test(e)||e.includes("\0"))throw new So("invalid_path",`Invalid collection-relative path: ${r}`);let t=e.split("/");if(t.includes(".."))throw new So("path_traversal",`Path escapes the collection root: ${r}`);return(0,oe.normalizePath)(t.filter(n=>n&&n!==".").join("/"))}function AT(r){let e=r.search(/[*?]|\[/),n=(e===-1?r:r.slice(0,e)).replace(/\/+$/,"");if(n.endsWith(".md")){let i=n.lastIndexOf("/");return i>=0?n.slice(0,i):""}return n}function pw(r,e){if(r.path_pattern){let t=(0,oe.normalizePath)(Rp(r.path_pattern,e));if(t.endsWith(".md")){let n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}return t.replace(/\/+$/,"")}return r.match?.path_glob?AT(r.match.path_glob):""}function hw(r,e){let t=r.display_name_key??"title",n=e[t],i=`${r.name}-${new Date().toISOString().slice(0,10)}`,s=typeof n=="string"&&n.trim().length>0?n:i;if(r.filename_pattern&&r.filename_pattern.trim().length>0){let o=(0,oe.normalizePath)(Rp(r.filename_pattern,e)),c=(o.split("/").pop()??o).replace(/\.md$/i,"").trim();if(c.length>0)return`${kp(c)}.md`}return`${kp(s)}.md`}function Qi(r){return Array.isArray(r)?`[${r.map(Qi).join(",")}]`:K(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${Qi(r[e])}`).join(",")}}`:JSON.stringify(r)}function PT(r,e){let t=[r];for(let n of e.split(".").filter(Boolean)){let i=n.endsWith("[]"),s=i?n.slice(0,-2):n,o=[];for(let a of t){if(!K(a)||!Object.prototype.hasOwnProperty.call(a,s))continue;let c=a[s];i&&Array.isArray(c)?o.push(...c):i||o.push(c)}if(!o.length)return{present:!1,value:void 0};t=o}return{present:!0,value:t[0]}}function bc(r,e,t){return(typeof r=="number"&&typeof e=="number"&&Number.isFinite(r)&&Number.isFinite(e)||typeof r=="string"&&typeof e=="string")&&t(r,e)}function CT(r,e,t,n){let i=(s,o)=>Qi(s)===Qi(o);switch(e){case"eq":case"const":return r.present&&r.value!=null&&i(r.value,t);case"neq":return r.present&&r.value!=null&&!i(r.value,t);case"gt":return bc(r.value,t,(s,o)=>s>o);case"gte":return bc(r.value,t,(s,o)=>s>=o);case"lt":return bc(r.value,t,(s,o)=>ss<=o);case"exists":return n.startsWith("0.3.")?t===!0?r.present:!r.present:t===!0?r.present&&r.value!=null:!r.present||r.value==null;case"contains":return Array.isArray(r.value)?r.value.some(s=>i(s,t)):typeof r.value=="string"&&r.value.includes(String(t));case"containsAll":return!Array.isArray(r.value)||!Array.isArray(t)?!1:t.every(s=>r.value.some(o=>i(o,s)));case"containsAny":return!Array.isArray(r.value)||!Array.isArray(t)?!1:t.some(s=>r.value.some(o=>i(o,s)));case"in":return r.value!=null&&Array.isArray(t)&&t.some(s=>i(s,r.value));case"startsWith":case"starts_with":return typeof r.value=="string"&&typeof t=="string"&&r.value.startsWith(t);case"endsWith":case"ends_with":return typeof r.value=="string"&&typeof t=="string"&&r.value.endsWith(t);case"matches":try{return typeof r.value=="string"&&typeof t=="string"&&new RegExp(t.replace(/\\\\/g,"\\")).test(r.value)}catch{return!1}default:return!1}}function wc(r,e,t){if("and"in r)return Array.isArray(r.and)&&r.and.every(n=>K(n)&&wc(n,e,t));if("or"in r)return Array.isArray(r.or)&&r.or.some(n=>K(n)&&wc(n,e,t));if("not"in r)return K(r.not)&&!wc(r.not,e,t);for(let[n,i]of Object.entries(r)){let s=PT(e,n);if(!K(i)){if(!s.present||Qi(s.value)!==Qi(i))return!1;continue}for(let[o,a]of Object.entries(i))if(!CT(s,o,a,t))return!1}return!0}function Ge(r,e,t,n){let i=kT(e,t.settings.explicit_type_keys);if(i)return i;let s=[];for(let[o,a]of n.entries()){let c=a.match;if(!c)continue;let l=!0;if(typeof c.path_glob=="string"&&!VT(c.path_glob,r,t)&&(l=!1),l&&Array.isArray(c.fields_present)){for(let u of c.fields_present)if(!(u in e)){l=!1;break}}l&&K(c.where)&&(l=wc(c.where,e,t.spec_version)),l&&typeof c.where=="string"&&(l=!1),l&&s.push(o)}return s}function mw(r){return r==null||typeof r=="string"&&r.trim().length===0}function MT(r){return/^\d{4}-\d{2}-\d{2}$/.test(r)}function RT(r){return/^\d{2}:\d{2}(:\d{2})?$/.test(r)}function TT(r){return typeof r=="string"||Array.isArray(r)?r.length:null}function Ce(r,e,t,n,i,s){r.push({path:e,code:n,message:i,severity:t,field:s})}function Ut(r,e,t,n,i){typeof r=="number"&&(typeof e.min=="number"&&re.max&&Ce(i,n,"error","above_max",`'${t}' is ${r}; must be at most ${e.max}`,t));let s=TT(r);if(s!=null&&(typeof e.min_length=="number"&&se.max_length&&Ce(i,n,"error","above_max_length",`'${t}' has length ${s}; limit is ${e.max_length}`,t)),typeof e.pattern=="string"&&typeof r=="string")try{new RegExp(e.pattern).test(r)||Ce(i,n,"error","pattern_mismatch",`'${t}' is ${$p(r)}; does not match /${e.pattern}/`,t)}catch(o){Ce(i,n,"warn","invalid_pattern",`Field '${t}' has invalid regex pattern: ${o instanceof Error?o.message:String(o)}`,t)}}function xp(r,e,t,n,i,s){let o=e.type??"any";if(r==null)return;e.deprecated===!0&&Ce(i,n,"warn","deprecated_field",`Field '${t}' is marked deprecated`,t);let a=c=>{Ce(i,n,"error","invalid_type",`Field '${t}' expected ${c}`,t)};switch(o){case"any":Ut(r,e,t,n,i);return;case"string":if(typeof r!="string"){a("a string");return}Ut(r,e,t,n,i);return;case"integer":if(typeof r!="number"||!Number.isInteger(r)){a("an integer");return}Ut(r,e,t,n,i);return;case"number":if(typeof r!="number"||Number.isNaN(r)){a("a number");return}Ut(r,e,t,n,i);return;case"boolean":typeof r!="boolean"&&a("a boolean");return;case"date":if(typeof r!="string"||!MT(r)){a("a date (YYYY-MM-DD)");return}Ut(r,e,t,n,i);return;case"datetime":if(typeof r!="string"||Number.isNaN(Date.parse(r))){a("a datetime string");return}Ut(r,e,t,n,i);return;case"time":if(typeof r!="string"||!RT(r)){a("a time string (HH:MM)");return}Ut(r,e,t,n,i);return;case"enum":{let c=Array.isArray(e.values)?e.values:[];if(!c.includes(r)){Ce(i,n,"error","invalid_enum",`Field '${t}' must be one of: ${c.map(l=>String(l)).join(", ")}`,t);return}Ut(r,e,t,n,i);return}case"list":{if(!Array.isArray(r)){a("a list");return}Ut(r,e,t,n,i),e.items&&r.forEach((c,l)=>{xp(c,e.items,`${t}[${l}]`,n,i,s)});return}case"object":{if(!K(r)){a("an object");return}if(e.fields&&K(e.fields))for(let[c,l]of Object.entries(e.fields)){if(!K(l))continue;let u=l,d=`${t}.${c}`,f=r[c];if(u.required&&mw(f)){Ce(i,n,"error","missing_required",`Missing required field '${d}'`,d);continue}xp(f,u,d,n,i,s)}return}case"link":{if(typeof r!="string"&&!K(r)){a("a link string");return}if(e.validate_exists===!0&&s){let c=typeof r=="string"?r:typeof r.path=="string"?r.path:typeof r.file=="string"?r.file:"";(!c||!ET(s,n,c))&&Ce(i,n,"error","missing_link_target",`Field '${t}' references a missing note`,t)}return}case"tags":if(typeof r=="string"){Ut(r,e,t,n,i);return}if(Array.isArray(r)&&r.every(c=>typeof c=="string")){Ut(r,e,t,n,i);return}a("a tag string or list of strings");return;default:Ut(r,e,t,n,i);return}}function IT(r){return r.replace(/^\//,"").split("/").filter(Boolean).map(t=>t.replace(/~1/g,"/").replace(/~0/g,"~")).join(".")||void 0}function OT(r){return r.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function $p(r){return r===null?"empty":typeof r=="string"?r.trim()?`'${r.length>40?`${r.slice(0,39)}\u2026`:r}'`:"empty":typeof r=="number"||typeof r=="boolean"?String(r):Array.isArray(r)?`a list of ${r.length}`:K(r)?"an object":r===void 0?"missing":JSON.stringify(r)??"unknown"}function vc(r,e){return`${r} ${e}${r===1?"":"s"}`}function LT(r,e,t,n){let i=r.params,s=e?`'${e}'`:"This note",o=$p(t);switch(r.keyword){case"required":return`Missing required field '${e??String(i.missingProperty)}'`;case"additionalProperties":return`Field '${e??String(i.additionalProperty)}' is not declared by type '${n}'`;case"type":{let c=(Array.isArray(i.type)?i.type.join(","):typeof i.type=="string"?i.type:"").split(",").map(l=>DT[l]??l).join(" or ");return`${s} is ${o}; expected ${c}`}case"enum":{let a=Array.isArray(i.allowedValues)?i.allowedValues.map(l=>String(l)):[],c=a.length>6?`${a.slice(0,6).join(", ")}, \u2026`:a.join(", ");return`${s} is ${o}; expected one of ${c}`}case"const":return`${s} is ${o}; expected ${$p(i.allowedValue)}`;case"maximum":return`${s} is ${o}; must be at most ${String(i.limit)}`;case"minimum":return`${s} is ${o}; must be at least ${String(i.limit)}`;case"exclusiveMaximum":return`${s} is ${o}; must be less than ${String(i.limit)}`;case"exclusiveMinimum":return`${s} is ${o}; must be more than ${String(i.limit)}`;case"maxLength":return`${s} is ${vc(typeof t=="string"?t.length:0,"character")}; limit is ${String(i.limit)}`;case"minLength":return`${s} is ${vc(typeof t=="string"?t.length:0,"character")}; needs at least ${String(i.limit)}`;case"maxItems":return`${s} has ${vc(Array.isArray(t)?t.length:0,"item")}; limit is ${String(i.limit)}`;case"minItems":return`${s} has ${vc(Array.isArray(t)?t.length:0,"item")}; needs at least ${String(i.limit)}`;case"uniqueItems":return`${s} contains duplicate items`;case"pattern":return`${s} is ${o}; does not match ${String(i.pattern)}`;case"format":return`${s} is ${o}; expected ${NT[String(i.format)]??String(i.format)}`;default:return`${s}: ${r.message??"invalid value"}`}}function FT(r,e,t,n={}){let i=r.params,s=IT(r.instancePath),o=typeof i.missingProperty=="string"?i.missingProperty:typeof i.additionalProperty=="string"?i.additionalProperty:void 0,a=s&&o?`${s}.${o}`:o??s,c=r.keyword==="format"?"format_invalid":`schema_${OT(r.keyword)}`,l=uw(n,r.instancePath);return{path:e,code:c,message:LT(r,a,l,t),severity:"error",field:a,type:t,schema_location:`embedded://type/schema#${r.schemaPath}`,details:{instance_path:r.instancePath,schema_path:r.schemaPath,technical_message:`JSON Schema ${r.keyword} failed for type '${t}': ${r.message??"invalid value"}`,...o===void 0?{}:{property:o}}}}function Ep(r){if(Array.isArray(r)){for(let e of r){let t=Ep(e);if(t)return t}return null}if(!K(r))return null;if(typeof r.$ref=="string"&&!r.$ref.startsWith("#"))return r.$ref;for(let e of Object.values(r)){let t=Ep(e);if(t)return t}return null}function jT(r,e,t,n){if(!t.schema)return;let i=Ep(t.schema);if(i){n.push({path:r,code:/^[a-z][a-z0-9+.-]*:/i.test(i)?"schema_ref_forbidden":"unsupported_profile",message:`Unsupported JSON Schema reference '${i}' for type '${t.name}'`,severity:"error",type:t.name});return}try{let s=_T().compile(t.schema);if(s(e))return;for(let o of s.errors??[])n.push(FT(o,r,t.name,e))}catch(s){n.push({path:r,code:"invalid_embedded_schema",message:s instanceof Error?s.message:String(s),severity:"error",type:t.name})}}async function qT(r,e,t,n,i,s,o){for(let[a,c]of Object.entries(n.collection?.links??{})){let l=t[a],u=Array.isArray(l)?l:[l];for(let d of u){if(d==null||typeof d!="string")continue;let f=cw(r,e,d);if(!f&&c.validate_exists===!0){Ce(o,e,"error","link_not_found",`Field '${a}' references a missing note`,a);continue}if(f&&c.target_type&&c.target_type!=="any"){let p=Me(await r.cachedRead(f));Ge(f.path,p.frontmatter,i,s).includes(c.target_type)||Ce(o,e,"error","link_wrong_type",`Field '${a}' must reference type '${c.target_type}'`,a)}}}}function yw(r,e,t,n,i){if(t.specProfile==="v0.3"){jT(r,e,t,n);return}for(let[s,o]of Object.entries(t.fields)){if(!K(o))continue;let a=o,c=e[s];if(a.required&&mw(c)){Ce(n,r,"error","missing_required",`Missing required field '${s}' for type '${t.name}'`,s);continue}xp(c,a,s,r,n,i)}}function BT(r){let e=new Set;for(let t of r)for(let n of Object.keys(t.fields))e.add(n);return e}function UT(r,e){let t=!1,n=!1;for(let i of r){if(i.strict===!0)return!0;i.strict==="warn"&&(t=!0),i.strict===void 0&&(n=!0)}return t||n&&e.settings.default_strict?"warn":!1}function bt(r,e){let t=(0,oe.normalizePath)(r),n=(0,oe.normalizePath)(e.settings.types_folder);if(t.startsWith(`${n}/`)||t===n)return!0;if(Tp(e.spec_version)){let i=(0,oe.normalizePath)(e.settings.contracts_folder??"_contracts");return t===i||t.startsWith(`${i}/`)||t.split("/").some(s=>s.startsWith(".")||s==="node_modules")?!0:e.settings.exclude.some(s=>_p(s,t))}if(e.settings.include_subfolders===!1&&t.includes("/"))return!0;for(let i of e.settings.exclude)if((0,Ap.default)(i,{dot:!0,matchBase:!i.includes("/")})(t)||!i.includes("*")&&!i.includes("?")&&!i.includes("/")&&t.startsWith(`${i}/`))return!0;return!1}function Tp(r){return typeof r=="string"&&r.startsWith("0.3.")}function VT(r,e,t){return Tp(t.spec_version)?_p(r,e):(0,Ap.default)(r,{dot:!0})(e)}async function Sc(r,e,t,n){if(bt(e.path,t))return[];let i=[],s=await r.cachedRead(e),o=Me(s);if(o.error)return Ce(i,e.path,"error","invalid_frontmatter",o.error),i;let a=o.frontmatter,c=Ge(e.path,a,t,n);if(c.length===0)return Ce(i,e.path,"warn","no_matching_type","No type could be resolved for this file"),i;let l=c.map(f=>n.get(f)).filter(f=>!!f),u=c.filter(f=>!n.has(f));if(u.length>0&&Ce(i,e.path,"error","unknown_type",`Resolved types are not defined: ${u.join(", ")}`),l.length===0)return i;for(let f of l)yw(e.path,a,f,i,r),f.specProfile==="v0.3"&&await qT(r,e.path,a,f,t,n,i);let d=t.spec_version.startsWith("0.3.")?!1:UT(l,t);if(d!==!1){let f=BT(l),p=new Set(t.settings.explicit_type_keys),h=d===!0?"error":"warn";for(let m of Object.keys(a))f.has(m)||p.has(m)||Ce(i,e.path,h,"unknown_field",`Unknown field '${m}' in strict mode`,m)}return i}async function HT(r,e,t,n={}){let i=new Map;for(let o of r.getMarkdownFiles()){if(bt(o.path,e))continue;n.signal?.throwIfAborted();let a=await r.cachedRead(o),c=Me(a);if(c.error)continue;let u=Ge(o.path,c.frontmatter,e,t).map(d=>t.get(d)).filter(d=>!!d);for(let d of u)for(let[f,p]of Object.entries(d.fields)){if(!K(p))continue;let h=p;if(h.unique!==!0)continue;let m=c.frontmatter[f];if(m==null)continue;let y=Sp(m),g=h.unique_scope==="collection"?"collection":"type",b=`${g==="collection"?"*":d.name}::${f}::${y}`,v=i.get(b)??[];v.some(S=>S.path===o.path)||(v.push({path:o.path,typeName:d.name,fieldName:f,scope:g,specProfile:d.specProfile,value:m,fingerprint:y}),i.set(b,v))}}let s=[];for(let o of i.values())if(!(o.length<=1))for(let a of o){let c=o.filter(l=>l.path!==a.path).map(l=>l.path).join(", ");Ce(s,a.path,"error",a.specProfile==="v0.3"?"duplicate_value":"duplicate_unique",a.scope==="collection"?`Field '${a.fieldName}' must be unique across the collection. Duplicate found in: ${c}`:`Field '${a.fieldName}' must be unique for type '${a.typeName}'. Duplicate found in: ${c}`,a.fieldName)}return s}function zT(r,e){let t=Ne(r);for(let n of e)for(let[i,s]of Object.entries(n.collection?.read_defaults??{}))i in t||(t[i]=Ne(s));return t}async function Ip(r,e,t,n={}){let i=[],s=r.getMarkdownFiles().filter(a=>!bt(a.path,e));n.onProgress?.({completed:0,total:s.length,phase:"notes"});for(let[a,c]of s.entries()){n.signal?.throwIfAborted();let l=await Sc(r,c,e,t);n.signal?.throwIfAborted(),n.onFile?.(c,l),i.push(...l),n.onProgress?.({completed:a+1,total:s.length,phase:"notes"}),a%25===0&&await new Promise(u=>setTimeout(u,0))}n.signal?.throwIfAborted(),n.onProgress?.({completed:s.length,total:s.length,phase:"uniqueness"});let o=await HT(r,e,t,n);return n.signal?.throwIfAborted(),i.push(...o),i}function Op(r,e,t=Ur.spec_version){if(t.startsWith("0.3.")){let i={kind:"mdbase.type",name:r,version:1,description:`${r} type`,schema:{dialect:"json-schema-2020-12",value:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",required:["title"],additionalProperties:!0,properties:{title:{type:"string",minLength:1},tags:{type:"array",items:{type:"string"}}}}}};return e&&e.trim()&&(i.match={path_glob:e.trim()}),`${gt(i,`# ${r} 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} +`}let n={name:r,description:`${r} type`,strict:!1,fields:{title:{type:"string",required:!0}}};return e&&e.trim().length>0&&(n.match={path_glob:e.trim()}),`${gt(n,`# ${r} Type definition for ${r}.`)} -`}async function 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()} +`}async function KT(r,e,t,n){let i=t.trim(),s=(0,oe.normalizePath)(`${e.settings.types_folder}/${i}.md`);if(await r.adapter.exists(s))throw new Error(`Type already exists: ${s}`);let o=Op(i,n,e.spec_version);return await r.create(s,o),s}function Dp(r,e){let t={},n=e.settings.explicit_type_keys[0]??"type";t[n]=n==="types"?[r.name]:r.name;for(let[i,s]of Object.entries(r.fields)){if(!K(s))continue;let o=s;o.default!==void 0&&(t[i]=Ne(o.default))}return t}function Np(r,e){let t=[];for(let[n,i]of Object.entries(r.fields)){if(!K(i))continue;let s=i;s.computed||s.required&&e[n]===void 0&&t.push([n,s])}return t}function xc(r,e){let t=r.trim();switch(e.type??"string"){case"string":case"date":case"datetime":case"time":case"link":case"enum":case"any":return t;case"integer":{let i=Number(t);if(!/^[+-]?\d+$/.test(t)||!Number.isSafeInteger(i))throw new Error("Expected a whole integer");return i}case"number":{let i=Number(t);if(!/^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(t)||!Number.isFinite(i))throw new Error("Expected a finite number");return i}case"boolean":{let i=t.toLowerCase();if(["true","1","yes","y"].includes(i))return!0;if(["false","0","no","n"].includes(i))return!1;throw new Error("Expected boolean input: true/false")}case"list":{if(t.startsWith("[")||/^-\s/.test(t)){let s=(0,oe.parseYaml)(t);if(!Array.isArray(s))throw new Error("Expected a YAML or JSON list");return s}let i=t.split(",").map(s=>s.trim()).filter(s=>s.length>0);return e.items?i.map(s=>xc(s,e.items)):i}case"object":{let i=(0,oe.parseYaml)(t);if(!K(i))throw new Error("Expected YAML object value");return i}case"tags":return t.split(",").map(i=>i.trim()).filter(i=>i.length>0);default:return t}}function kp(r){let e=r.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-+/,"").replace(/-+$/,"");return e.length>0?e:"note"}async function WT(r,e){let t=(0,oe.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let n=t.split("/"),i="";for(let s of n)i=i?`${i}/${s}`:s,await r.adapter.exists(i)||await r.createFolder(i)}function GT(r,e){if(!r.path_pattern||r.path_pattern.trim().length===0)return null;let t=(0,oe.normalizePath)(Rp(r.path_pattern,e));return t.endsWith(".md")?t:null}async function Lp(r,e,t){let n=GT(e,t),i=pw(e,t),s=n?n.split("/").pop()??n:hw(e,t),o=bn(n||`${i?`${i}/`:""}${s.endsWith(".md")?s:`${s}.md`}`),a=o,c=2;for(;r.getAbstractFileByPath(a);)a=o.replace(/\.md$/,`-${c}.md`),c+=1;return a}async function JT(r,e,t,n=""){let i=bn(e),s=i.lastIndexOf("/");if(s>0&&await WT(r,i.slice(0,s)),await r.adapter.exists(i))throw new Error(`File already exists: ${i}`);let o=`${gt(t,n)} +`;return r.create(i,o)}function Fp(r){return xT(r)}var oe,nw,iw,Ap,So,Ur,wT,_o,DT,NT,Vt=cy(()=>{oe=require("obsidian"),nw=Wn(Zf(),1),iw=Wn(lp(),1),Ap=Wn(wp(),1);tw();So=class extends Error{constructor(t,n){super(n);this.code=t;this.name="MdbasePathError"}},Ur={spec_version:"0.3.0",name:"My mdbase collection",description:"Typed markdown collection",settings:{types_folder:"_types",contracts_folder:"_contracts",explicit_type_keys:["type","types"],exclude:[]}},wT=["_types",".obsidian",".git","node_modules",".trash",".mdbase"],_o=null;DT={string:"text",integer:"a whole number",number:"a number",boolean:"true or false",array:"a list",object:"an object",null:"empty"},NT={date:"a date (YYYY-MM-DD)","date-time":"a date and time",time:"a time (HH:MM)",email:"an email address",uri:"a URI"}});var is=k((CB,Cw)=>{"use strict";var iI="2.0.0",sI=Number.MAX_SAFE_INTEGER||9007199254740991,oI=16,aI=250,cI=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Cw.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:oI,MAX_SAFE_BUILD_LENGTH:aI,MAX_SAFE_INTEGER:sI,RELEASE_TYPES:cI,SEMVER_SPEC_VERSION:iI,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Eo=k((MB,Mw)=>{"use strict";var lI=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};Mw.exports=lI});var ss=k((Er,Rw)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Kp,MAX_SAFE_BUILD_LENGTH:dI,MAX_LENGTH:uI}=is(),fI=Eo();Er=Rw.exports={};var pI=Er.re=[],hI=Er.safeRe=[],D=Er.src=[],mI=Er.safeSrc=[],N=Er.t={},yI=0,Wp="[a-zA-Z0-9-]",gI=[["\\s",1],["\\d",uI],[Wp,dI]],bI=r=>{for(let[e,t]of gI)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},H=(r,e,t)=>{let n=bI(e),i=yI++;fI(r,i,e),N[r]=i,D[i]=e,mI[i]=n,pI[i]=new RegExp(e,t?"g":void 0),hI[i]=new RegExp(n,t?"g":void 0)};H("NUMERICIDENTIFIER","0|[1-9]\\d*");H("NUMERICIDENTIFIERLOOSE","\\d+");H("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Wp}*`);H("MAINVERSION",`(${D[N.NUMERICIDENTIFIER]})\\.(${D[N.NUMERICIDENTIFIER]})\\.(${D[N.NUMERICIDENTIFIER]})`);H("MAINVERSIONLOOSE",`(${D[N.NUMERICIDENTIFIERLOOSE]})\\.(${D[N.NUMERICIDENTIFIERLOOSE]})\\.(${D[N.NUMERICIDENTIFIERLOOSE]})`);H("PRERELEASEIDENTIFIER",`(?:${D[N.NONNUMERICIDENTIFIER]}|${D[N.NUMERICIDENTIFIER]})`);H("PRERELEASEIDENTIFIERLOOSE",`(?:${D[N.NONNUMERICIDENTIFIER]}|${D[N.NUMERICIDENTIFIERLOOSE]})`);H("PRERELEASE",`(?:-(${D[N.PRERELEASEIDENTIFIER]}(?:\\.${D[N.PRERELEASEIDENTIFIER]})*))`);H("PRERELEASELOOSE",`(?:-?(${D[N.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${D[N.PRERELEASEIDENTIFIERLOOSE]})*))`);H("BUILDIDENTIFIER",`${Wp}+`);H("BUILD",`(?:\\+(${D[N.BUILDIDENTIFIER]}(?:\\.${D[N.BUILDIDENTIFIER]})*))`);H("FULLPLAIN",`v?${D[N.MAINVERSION]}${D[N.PRERELEASE]}?${D[N.BUILD]}?`);H("FULL",`^${D[N.FULLPLAIN]}$`);H("LOOSEPLAIN",`[v=\\s]*${D[N.MAINVERSIONLOOSE]}${D[N.PRERELEASELOOSE]}?${D[N.BUILD]}?`);H("LOOSE",`^${D[N.LOOSEPLAIN]}$`);H("GTLT","((?:<|>)?=?)");H("XRANGEIDENTIFIERLOOSE",`${D[N.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);H("XRANGEIDENTIFIER",`${D[N.NUMERICIDENTIFIER]}|x|X|\\*`);H("XRANGEPLAIN",`[v=\\s]*(${D[N.XRANGEIDENTIFIER]})(?:\\.(${D[N.XRANGEIDENTIFIER]})(?:\\.(${D[N.XRANGEIDENTIFIER]})(?:${D[N.PRERELEASE]})?${D[N.BUILD]}?)?)?`);H("XRANGEPLAINLOOSE",`[v=\\s]*(${D[N.XRANGEIDENTIFIERLOOSE]})(?:\\.(${D[N.XRANGEIDENTIFIERLOOSE]})(?:\\.(${D[N.XRANGEIDENTIFIERLOOSE]})(?:${D[N.PRERELEASELOOSE]})?${D[N.BUILD]}?)?)?`);H("XRANGE",`^${D[N.GTLT]}\\s*${D[N.XRANGEPLAIN]}$`);H("XRANGELOOSE",`^${D[N.GTLT]}\\s*${D[N.XRANGEPLAINLOOSE]}$`);H("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Kp}})(?:\\.(\\d{1,${Kp}}))?(?:\\.(\\d{1,${Kp}}))?`);H("COERCE",`${D[N.COERCEPLAIN]}(?:$|[^\\d])`);H("COERCEFULL",D[N.COERCEPLAIN]+`(?:${D[N.PRERELEASE]})?(?:${D[N.BUILD]})?(?:$|[^\\d])`);H("COERCERTL",D[N.COERCE],!0);H("COERCERTLFULL",D[N.COERCEFULL],!0);H("LONETILDE","(?:~>?)");H("TILDETRIM",`(\\s*)${D[N.LONETILDE]}\\s+`,!0);Er.tildeTrimReplace="$1~";H("TILDE",`^${D[N.LONETILDE]}${D[N.XRANGEPLAIN]}$`);H("TILDELOOSE",`^${D[N.LONETILDE]}${D[N.XRANGEPLAINLOOSE]}$`);H("LONECARET","(?:\\^)");H("CARETTRIM",`(\\s*)${D[N.LONECARET]}\\s+`,!0);Er.caretTrimReplace="$1^";H("CARET",`^${D[N.LONECARET]}${D[N.XRANGEPLAIN]}$`);H("CARETLOOSE",`^${D[N.LONECARET]}${D[N.XRANGEPLAINLOOSE]}$`);H("COMPARATORLOOSE",`^${D[N.GTLT]}\\s*(${D[N.LOOSEPLAIN]})$|^$`);H("COMPARATOR",`^${D[N.GTLT]}\\s*(${D[N.FULLPLAIN]})$|^$`);H("COMPARATORTRIM",`(\\s*)${D[N.GTLT]}\\s*(${D[N.LOOSEPLAIN]}|${D[N.XRANGEPLAIN]})`,!0);Er.comparatorTrimReplace="$1$2$3";H("HYPHENRANGE",`^\\s*(${D[N.XRANGEPLAIN]})\\s+-\\s+(${D[N.XRANGEPLAIN]})\\s*$`);H("HYPHENRANGELOOSE",`^\\s*(${D[N.XRANGEPLAINLOOSE]})\\s+-\\s+(${D[N.XRANGEPLAINLOOSE]})\\s*$`);H("STAR","(<|>)?=?\\s*\\*");H("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");H("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Mc=k((RB,Tw)=>{"use strict";var vI=Object.freeze({loose:!0}),wI=Object.freeze({}),_I=r=>r?typeof r!="object"?vI:r:wI;Tw.exports=_I});var Gp=k((TB,Dw)=>{"use strict";var Iw=/^[0-9]+$/,Ow=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:rOw(e,r);Dw.exports={compareIdentifiers:Ow,rcompareIdentifiers:SI}});var qe=k((IB,Lw)=>{"use strict";var Rc=Eo(),{MAX_LENGTH:Nw,MAX_SAFE_INTEGER:Tc}=is(),{safeRe:Ic,t:Oc}=ss(),xI=Mc(),{compareIdentifiers:Jp}=Gp(),$I=(r,e)=>{let t=e.split(".");if(t.length>r.length)return!1;for(let n=0;nNw)throw new TypeError(`version is longer than ${Nw} characters`);Rc("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?Ic[Oc.LOOSE]:Ic[Oc.FULL]);if(!n)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>Tc||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Tc||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Tc||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(i=>{if(/^[0-9]+$/.test(i)){let s=+i;if(s>=0&&se.major?1:this.minore.minor?1:this.patche.patch?1:0}comparePre(e){if(e instanceof r||(e=new r(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{let n=this.prerelease[t],i=e.prerelease[t];if(Rc("prerelease compare",t,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return Jp(n,i)}while(++t)}compareBuild(e){e instanceof r||(e=new r(e,this.options));let t=0;do{let n=this.build[t],i=e.build[t];if(Rc("build compare",t,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return Jp(n,i)}while(++t)}inc(e,t,n){if(e.startsWith("pre")){if(!t&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(t){let i=`-${t}`.match(this.options.loose?Ic[Oc.PRERELEASELOOSE]:Ic[Oc.PRERELEASE]);if(!i||i[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,n),this.inc("pre",t,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,n),this.inc("pre",t,n);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let i=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[i];else{let s=this.prerelease.length;for(;--s>=0;)typeof this.prerelease[s]=="number"&&(this.prerelease[s]++,s=-2);if(s===-1){if(t===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(i)}}if(t){let s=[t,i];if(n===!1&&(s=[t]),$I(this.prerelease,t)){let o=this.prerelease[t.split(".").length];isNaN(o)&&(this.prerelease=s)}else this.prerelease=s}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Lw.exports=Yp});var _n=k((OB,jw)=>{"use strict";var Fw=qe(),EI=(r,e,t=!1)=>{if(r instanceof Fw)return r;try{return new Fw(r,e)}catch(n){if(!t)return null;throw n}};jw.exports=EI});var Bw=k((DB,qw)=>{"use strict";var kI=_n(),AI=(r,e)=>{let t=kI(r,e);return t?t.version:null};qw.exports=AI});var Vw=k((NB,Uw)=>{"use strict";var PI=_n(),CI=(r,e)=>{let t=PI(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};Uw.exports=CI});var Kw=k((LB,zw)=>{"use strict";var Hw=qe(),MI=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new Hw(r instanceof Hw?r.version:r,t).inc(e,n,i).version}catch{return null}};zw.exports=MI});var Jw=k((FB,Gw)=>{"use strict";var Ww=_n(),RI=(r,e)=>{let t=Ww(r,null,!0),n=Ww(e,null,!0),i=t.compare(n);if(i===0)return null;let s=i>0,o=s?t:n,a=s?n:t,c=!!o.prerelease.length;if(!!a.prerelease.length&&!c){if(!a.patch&&!a.minor)return"major";if(a.compareMain(o)===0)return a.minor&&!a.patch?"minor":"patch"}let u=c?"pre":"";return t.major!==n.major?u+"major":t.minor!==n.minor?u+"minor":t.patch!==n.patch?u+"patch":"prerelease"};Gw.exports=RI});var Xw=k((jB,Yw)=>{"use strict";var TI=qe(),II=(r,e)=>new TI(r,e).major;Yw.exports=II});var Zw=k((qB,Qw)=>{"use strict";var OI=qe(),DI=(r,e)=>new OI(r,e).minor;Qw.exports=DI});var t_=k((BB,e_)=>{"use strict";var NI=qe(),LI=(r,e)=>new NI(r,e).patch;e_.exports=LI});var n_=k((UB,r_)=>{"use strict";var FI=_n(),jI=(r,e)=>{let t=FI(r,e);return t&&t.prerelease.length?t.prerelease:null};r_.exports=jI});var Ht=k((VB,s_)=>{"use strict";var i_=qe(),qI=(r,e,t)=>new i_(r,t).compare(new i_(e,t));s_.exports=qI});var a_=k((HB,o_)=>{"use strict";var BI=Ht(),UI=(r,e,t)=>BI(e,r,t);o_.exports=UI});var l_=k((zB,c_)=>{"use strict";var VI=Ht(),HI=(r,e)=>VI(r,e,!0);c_.exports=HI});var Dc=k((KB,u_)=>{"use strict";var d_=qe(),zI=(r,e,t)=>{let n=new d_(r,t),i=new d_(e,t);return n.compare(i)||n.compareBuild(i)};u_.exports=zI});var p_=k((WB,f_)=>{"use strict";var KI=Dc(),WI=(r,e)=>r.sort((t,n)=>KI(t,n,e));f_.exports=WI});var m_=k((GB,h_)=>{"use strict";var GI=Dc(),JI=(r,e)=>r.sort((t,n)=>GI(n,t,e));h_.exports=JI});var ko=k((JB,y_)=>{"use strict";var YI=Ht(),XI=(r,e,t)=>YI(r,e,t)>0;y_.exports=XI});var Nc=k((YB,g_)=>{"use strict";var QI=Ht(),ZI=(r,e,t)=>QI(r,e,t)<0;g_.exports=ZI});var Xp=k((XB,b_)=>{"use strict";var eO=Ht(),tO=(r,e,t)=>eO(r,e,t)===0;b_.exports=tO});var Qp=k((QB,v_)=>{"use strict";var rO=Ht(),nO=(r,e,t)=>rO(r,e,t)!==0;v_.exports=nO});var Lc=k((ZB,w_)=>{"use strict";var iO=Ht(),sO=(r,e,t)=>iO(r,e,t)>=0;w_.exports=sO});var Fc=k((eU,__)=>{"use strict";var oO=Ht(),aO=(r,e,t)=>oO(r,e,t)<=0;__.exports=aO});var Zp=k((tU,S_)=>{"use strict";var cO=Xp(),lO=Qp(),dO=ko(),uO=Lc(),fO=Nc(),pO=Fc(),hO=(r,e,t,n)=>{switch(e){case"===":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r===t;case"!==":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r!==t;case"":case"=":case"==":return cO(r,t,n);case"!=":return lO(r,t,n);case">":return dO(r,t,n);case">=":return uO(r,t,n);case"<":return fO(r,t,n);case"<=":return pO(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};S_.exports=hO});var $_=k((rU,x_)=>{"use strict";var mO=qe(),yO=_n(),{safeRe:jc,t:qc}=ss(),gO=(r,e)=>{if(r instanceof mO)return r;if(typeof r=="number"&&(r=String(r)),typeof r!="string")return null;e=e||{};let t=null;if(!e.rtl)t=r.match(e.includePrerelease?jc[qc.COERCEFULL]:jc[qc.COERCE]);else{let c=e.includePrerelease?jc[qc.COERCERTLFULL]:jc[qc.COERCERTL],l;for(;(l=c.exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||l.index+l[0].length!==t.index+t[0].length)&&(t=l),c.lastIndex=l.index+l[1].length+l[2].length;c.lastIndex=-1}if(t===null)return null;let n=t[2],i=t[3]||"0",s=t[4]||"0",o=e.includePrerelease&&t[5]?`-${t[5]}`:"",a=e.includePrerelease&&t[6]?`+${t[6]}`:"";return yO(`${n}.${i}.${s}${o}${a}`,e)};x_.exports=gO});var k_=k((nU,E_)=>{"use strict";var bO=_n(),vO=is(),wO=qe(),_O=(r,e,t)=>{if(!vO.RELEASE_TYPES.includes(e))return null;let n=SO(r,t);return n&&xO(n,e)},SO=(r,e)=>{let t=r instanceof wO?r.version:r;return bO(t,e)},xO=(r,e)=>{if($O(e))return r.version;switch(r.prerelease=[],e){case"major":r.minor=0,r.patch=0;break;case"minor":r.patch=0;break}return r.format()},$O=r=>r.startsWith("pre");E_.exports=_O});var P_=k((iU,A_)=>{"use strict";var eh=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let i=this.map.keys().next().value;this.delete(i)}this.map.set(e,t)}return this}};A_.exports=eh});var zt=k((sU,T_)=>{"use strict";var EO=/\s+/g,th=class r{constructor(e,t){if(t=AO(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof rh)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(EO," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(i=>!M_(i[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let i of this.set)if(i.length===1&&NO(i[0])){this.set=[i];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e0&&(this.formatted+="||");let t=this.set[e];for(let n=0;n0&&(this.formatted+=" "),this.formatted+=t[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){e=e.replace(DO,"");let n=((this.options.includePrerelease&&IO)|(this.options.loose&&OO))+":"+e,i=C_.get(n);if(i)return i;let s=this.options.loose,o=s?st[Be.HYPHENRANGELOOSE]:st[Be.HYPHENRANGE];e=e.replace(o,WO(this.options.includePrerelease)),be("hyphen replace",e),e=e.replace(st[Be.COMPARATORTRIM],MO),be("comparator trim",e),e=e.replace(st[Be.TILDETRIM],RO),be("tilde trim",e),e=e.replace(st[Be.CARETTRIM],TO),be("caret trim",e);let a=e.split(" ").map(d=>LO(d,this.options)).join(" ").split(/\s+/).map(d=>KO(d,this.options));s&&(a=a.filter(d=>(be("loose invalid filter",d,this.options),!!d.match(st[Be.COMPARATORLOOSE])))),be("range list",a);let c=new Map,l=a.map(d=>new rh(d,this.options));for(let d of l){if(M_(d))return[d];c.set(d.value,d)}c.size>1&&c.has("")&&c.delete("");let u=[...c.values()];return C_.set(n,u),u}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>R_(n,t)&&e.set.some(i=>R_(i,t)&&n.every(s=>i.every(o=>s.intersects(o,t)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new PO(e,this.options)}catch{return!1}for(let t=0;tr.value==="<0.0.0-0",NO=r=>r.value==="",R_=(r,e)=>{let t=!0,n=r.slice(),i=n.pop();for(;t&&n.length;)t=n.every(s=>i.intersects(s,e)),i=n.pop();return t},LO=(r,e)=>(r=r.replace(st[Be.BUILD],""),be("comp",r,e),r=BO(r,e),be("caret",r),r=jO(r,e),be("tildes",r),r=VO(r,e),be("xrange",r),r=zO(r,e),be("stars",r),r),Re=r=>!r||r.toLowerCase()==="x"||r==="*",FO=(r,e,t)=>Re(r)&&!Re(e)||Re(e)&&t&&!Re(t),jO=(r,e)=>r.trim().split(/\s+/).map(t=>qO(t,e)).join(" "),qO=(r,e)=>{let t=e.loose?st[Be.TILDELOOSE]:st[Be.TILDE],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{be("tilde",r,i,s,o,a,c);let l;return Re(s)?l="":Re(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Re(a)?l=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:c?(be("replaceTilde pr",c),l=`>=${s}.${o}.${a}-${c} <${s}.${+o+1}.0-0`):l=`>=${s}.${o}.${a} <${s}.${+o+1}.0-0`,be("tilde return",l),l})},BO=(r,e)=>r.trim().split(/\s+/).map(t=>UO(t,e)).join(" "),UO=(r,e)=>{be("caret",r,e);let t=e.loose?st[Be.CARETLOOSE]:st[Be.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{be("caret",r,i,s,o,a,c);let l;return Re(s)?l="":Re(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Re(a)?s==="0"?l=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.0${n} <${+s+1}.0.0-0`:c?(be("replaceCaret pr",c),s==="0"?o==="0"?l=`>=${s}.${o}.${a}-${c} <${s}.${o}.${+a+1}-0`:l=`>=${s}.${o}.${a}-${c} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.${a}-${c} <${+s+1}.0.0-0`):(be("no pr"),s==="0"?o==="0"?l=`>=${s}.${o}.${a} <${s}.${o}.${+a+1}-0`:l=`>=${s}.${o}.${a} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.${a} <${+s+1}.0.0-0`),be("caret return",l),l})},VO=(r,e)=>(be("replaceXRanges",r,e),r.split(/\s+/).map(t=>HO(t,e)).join(" ")),HO=(r,e)=>{r=r.trim();let t=e.loose?st[Be.XRANGELOOSE]:st[Be.XRANGE];return r.replace(t,(n,i,s,o,a,c)=>{if(be("xRange",r,n,i,s,o,a,c),FO(s,o,a))return r;let l=Re(s),u=l||Re(o),d=u||Re(a),f=d;return i==="="&&f&&(i=""),c=e.includePrerelease?"-0":"",l?i===">"||i==="<"?n="<0.0.0-0":n="*":i&&f?(u&&(o=0),a=0,i===">"?(i=">=",u?(s=+s+1,o=0,a=0):(o=+o+1,a=0)):i==="<="&&(i="<",u?s=+s+1:o=+o+1),i==="<"&&(c="-0"),n=`${i+s}.${o}.${a}${c}`):u?n=`>=${s}.0.0${c} <${+s+1}.0.0-0`:d&&(n=`>=${s}.${o}.0${c} <${s}.${+o+1}.0-0`),be("xRange return",n),n})},zO=(r,e)=>(be("replaceStars",r,e),r.trim().replace(st[Be.STAR],"")),KO=(r,e)=>(be("replaceGTE0",r,e),r.trim().replace(st[e.includePrerelease?Be.GTE0PRE:Be.GTE0],"")),WO=r=>(e,t,n,i,s,o,a,c,l,u,d,f)=>(Re(n)?t="":Re(i)?t=`>=${n}.0.0${r?"-0":""}`:Re(s)?t=`>=${n}.${i}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,Re(l)?c="":Re(u)?c=`<${+l+1}.0.0-0`:Re(d)?c=`<${l}.${+u+1}.0-0`:f?c=`<=${l}.${u}.${d}-${f}`:r?c=`<${l}.${u}.${+d+1}-0`:c=`<=${c}`,`${t} ${c}`.trim()),GO=(r,e,t)=>{for(let n=0;n0){let i=r[n].semver;if(i.major===e.major&&i.minor===e.minor&&i.patch===e.patch)return!0}return!1}return!0}});var Ao=k((oU,F_)=>{"use strict";var Po=Symbol("SemVer ANY"),sh=class r{static get ANY(){return Po}constructor(e,t){if(t=I_(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),ih("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Po?this.value="":this.value=this.operator+this.semver.version,ih("comp",this)}parse(e){let t=this.options.loose?O_[D_.COMPARATORLOOSE]:O_[D_.COMPARATOR],n=e.match(t);if(!n)throw new TypeError(`Invalid comparator: ${e}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new N_(n[2],this.options.loose):this.semver=Po}toString(){return this.value}test(e){if(ih("Comparator.test",e,this.options.loose),this.semver===Po||e===Po)return!0;if(typeof e=="string")try{e=new N_(e,this.options)}catch{return!1}return nh(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new L_(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new L_(this.value,t).test(e.semver):(t=I_(t),t.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||nh(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||nh(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};F_.exports=sh;var I_=Mc(),{safeRe:O_,t:D_}=ss(),nh=Zp(),ih=Eo(),N_=qe(),L_=zt()});var Co=k((aU,j_)=>{"use strict";var JO=zt(),YO=(r,e,t)=>{try{e=new JO(e,t)}catch{return!1}return e.test(r)};j_.exports=YO});var B_=k((cU,q_)=>{"use strict";var XO=zt(),QO=(r,e)=>new XO(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));q_.exports=QO});var V_=k((lU,U_)=>{"use strict";var ZO=qe(),eD=zt(),tD=(r,e,t)=>{let n=null,i=null,s=null;try{s=new eD(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===-1)&&(n=o,i=new ZO(n,t))}),n};U_.exports=tD});var z_=k((dU,H_)=>{"use strict";var rD=qe(),nD=zt(),iD=(r,e,t)=>{let n=null,i=null,s=null;try{s=new nD(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===1)&&(n=o,i=new rD(n,t))}),n};H_.exports=iD});var G_=k((uU,W_)=>{"use strict";var oh=qe(),sD=zt(),K_=ko(),oD=(r,e)=>{r=new sD(r,e);let t=new oh("0.0.0");if(r.test(t)||(t=new oh("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n{let a=new oh(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||K_(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||K_(t,s))&&(t=s)}return t&&r.test(t)?t:null};W_.exports=oD});var Y_=k((fU,J_)=>{"use strict";var aD=zt(),cD=(r,e)=>{try{return new aD(r,e).range||"*"}catch{return null}};J_.exports=cD});var Bc=k((pU,e0)=>{"use strict";var lD=qe(),Z_=Ao(),{ANY:dD}=Z_,uD=zt(),fD=Co(),X_=ko(),Q_=Nc(),pD=Fc(),hD=Lc(),mD=(r,e,t,n)=>{r=new lD(r,n),e=new uD(e,n);let i,s,o,a,c;switch(t){case">":i=X_,s=pD,o=Q_,a=">",c=">=";break;case"<":i=Q_,s=hD,o=X_,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(fD(r,e,n))return!1;for(let l=0;l{p.semver===dD&&(p=new Z_(">=0.0.0")),d=d||p,f=f||p,i(p.semver,d.semver,n)?d=p:o(p.semver,f.semver,n)&&(f=p)}),d.operator===a||d.operator===c||(!f.operator||f.operator===a)&&s(r,f.semver))return!1;if(f.operator===c&&o(r,f.semver))return!1}return!0};e0.exports=mD});var r0=k((hU,t0)=>{"use strict";var yD=Bc(),gD=(r,e,t)=>yD(r,e,">",t);t0.exports=gD});var i0=k((mU,n0)=>{"use strict";var bD=Bc(),vD=(r,e,t)=>bD(r,e,"<",t);n0.exports=vD});var a0=k((yU,o0)=>{"use strict";var s0=zt(),wD=(r,e,t)=>(r=new s0(r,t),e=new s0(e,t),r.intersects(e,t));o0.exports=wD});var l0=k((gU,c0)=>{"use strict";var _D=Co(),SD=Ht();c0.exports=(r,e,t)=>{let n=[],i=null,s=null,o=r.sort((u,d)=>SD(u,d,t));for(let u of o)_D(u,e,t)?(s=u,i||(i=u)):(s&&n.push([i,s]),s=null,i=null);i&&n.push([i,null]);let a=[];for(let[u,d]of n)u===d?a.push(u):!d&&u===o[0]?a.push("*"):d?u===o[0]?a.push(`<=${d}`):a.push(`${u} - ${d}`):a.push(`>=${u}`);let c=a.join(" || "),l=typeof e.raw=="string"?e.raw:String(e);return c.length{"use strict";var d0=zt(),lh=Ao(),{ANY:ah}=lh,ch=Co(),dh=Ht(),xD=(r,e,t={})=>{if(r===e)return!0;r=new d0(r,t),e=new d0(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let o=ED(i,s,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},$D=[new lh(">=0.0.0-0")],u0=[new lh(">=0.0.0")],ED=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===ah){if(e.length===1&&e[0].semver===ah)return!0;t.includePrerelease?r=$D:r=u0}if(e.length===1&&e[0].semver===ah){if(t.includePrerelease)return!0;e=u0}let n=new Set,i,s;for(let p of r)p.operator===">"||p.operator===">="?i=f0(i,p,t):p.operator==="<"||p.operator==="<="?s=p0(s,p,t):n.add(p.semver);if(n.size>1)return null;let o;if(i&&s){if(o=dh(i.semver,s.semver,t),o>0)return null;if(o===0&&(i.operator!==">="||s.operator!=="<="))return null}for(let p of n){if(i&&!ch(p,String(i),t)||s&&!ch(p,String(s),t))return null;for(let h of e)if(!ch(p,String(h),t))return!1;return!0}let a,c,l,u,d=s&&!t.includePrerelease&&s.semver.prerelease.length?s.semver:!1,f=i&&!t.includePrerelease&&i.semver.prerelease.length?i.semver:!1;d&&d.prerelease.length===1&&s.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(let p of e){if(u=u||p.operator===">"||p.operator===">=",l=l||p.operator==="<"||p.operator==="<=",i){if(f&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===f.major&&p.semver.minor===f.minor&&p.semver.patch===f.patch&&(f=!1),p.operator===">"||p.operator===">="){if(a=f0(i,p,t),a===p&&a!==i)return!1}else if(i.operator===">="&&!p.test(i.semver))return!1}if(s){if(d&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===d.major&&p.semver.minor===d.minor&&p.semver.patch===d.patch&&(d=!1),p.operator==="<"||p.operator==="<="){if(c=p0(s,p,t),c===p&&c!==s)return!1}else if(s.operator==="<="&&!p.test(s.semver))return!1}if(!p.operator&&(s||i)&&o!==0)return!1}return!(i&&l&&!s&&o!==0||s&&u&&!i&&o!==0||f||d)},f0=(r,e,t)=>{if(!r)return e;let n=dh(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},p0=(r,e,t)=>{if(!r)return e;let n=dh(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};h0.exports=xD});var v0=k((vU,b0)=>{"use strict";var uh=ss(),y0=is(),kD=qe(),g0=Gp(),AD=_n(),PD=Bw(),CD=Vw(),MD=Kw(),RD=Jw(),TD=Xw(),ID=Zw(),OD=t_(),DD=n_(),ND=Ht(),LD=a_(),FD=l_(),jD=Dc(),qD=p_(),BD=m_(),UD=ko(),VD=Nc(),HD=Xp(),zD=Qp(),KD=Lc(),WD=Fc(),GD=Zp(),JD=$_(),YD=k_(),XD=Ao(),QD=zt(),ZD=Co(),eN=B_(),tN=V_(),rN=z_(),nN=G_(),iN=Y_(),sN=Bc(),oN=r0(),aN=i0(),cN=a0(),lN=l0(),dN=m0();b0.exports={parse:AD,valid:PD,clean:CD,inc:MD,diff:RD,major:TD,minor:ID,patch:OD,prerelease:DD,compare:ND,rcompare:LD,compareLoose:FD,compareBuild:jD,sort:qD,rsort:BD,gt:UD,lt:VD,eq:HD,neq:zD,gte:KD,lte:WD,cmp:GD,coerce:JD,truncate:YD,Comparator:XD,Range:QD,satisfies:ZD,toComparators:eN,maxSatisfying:tN,minSatisfying:rN,minVersion:nN,validRange:iN,outside:sN,gtr:oN,ltr:aN,intersects:cN,simplifyRange:lN,subset:dN,SemVer:kD,re:uh.re,src:uh.src,tokens:uh.t,SEMVER_SPEC_VERSION:y0.SEMVER_SPEC_VERSION,RELEASE_TYPES:y0.RELEASE_TYPES,compareIdentifiers:g0.compareIdentifiers,rcompareIdentifiers:g0.rcompareIdentifiers}});var mj={};ly(mj,{default:()=>Dd});module.exports=sE(mj);var Nt=require("obsidian"),Ld="https://mdbase.dev/contracts/catalog.json",Ls="mdbase.lock.yaml",Fr=".mdbase/obsidian-pack-install.json";function br(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid contract catalog or type pack.");return r}function Yt(r){if(typeof r!="string"||!r)throw new Error("Missing catalog field.");return r}function fy(r){let e=Yt(r);if(!/^sha256:[a-f0-9]{64}$/.test(e))throw new Error("Invalid pack digest.");return e}function Ra(r){let e=Yt(r);if(e.includes("\\")||e.includes(":")||Array.from(e).some(t=>t.charCodeAt(0)<32)||e.split("/").some(t=>!t||t==="."||t===".."||t.startsWith(".")))throw new Error(`Unsafe pack path: ${e}`);return e}async function Pi(r){let e=typeof r=="string"?new TextEncoder().encode(r):r;return`sha256:${Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",e))).map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Fd(r){return Array.isArray(r)?`[${r.map(Fd).join(",")}]`:r&&typeof r=="object"?`{${Object.entries(r).sort(([e],[t])=>et?1:0).map(([e,t])=>`${JSON.stringify(e)}:${Fd(t)}`).join(",")}}`:JSON.stringify(r)}function oE(r){let e=new URL(Yt(r),Ld);if(e.origin!==new URL(Ld).origin||!e.pathname.startsWith("/contracts/"))throw new Error("Pack artifacts must come from the first-party contract catalog.");return e.href}async function aE(){let r=await(0,Nt.requestUrl)({url:Ld,throw:!1});if(r.status!==200)throw new Error(`Catalog unavailable (${r.status}). Your vault is unchanged. Try again when online.`);if(r.arrayBuffer.byteLength>1024*1024)throw new Error("Contract catalog is too large.");let e=br(r.json);if(e.catalog_version!==2||!Array.isArray(e.packs))throw new Error("Unsupported contract catalog.");return e.packs.map(t=>{let n=br(t),i=br(n.display),s=br(n.installation);if(!Number.isInteger(n.resource_count)||Number(n.resource_count)<1||Number(n.resource_count)>100)throw new Error("Invalid pack resource count.");return{id:Yt(n.id),version:Yt(n.version),digest:fy(n.digest),provision:oE(n.provision),resource_count:Number(n.resource_count),display:{name:Yt(i.name),summary:Yt(i.summary)},installation:{visibility:Yt(s.visibility),recommendation:Yt(s.recommendation),primary_type:s.primary_type==null?null:Yt(s.primary_type),...typeof s.caution=="string"?{caution:s.caution}:{}}}})}async function Gn(r,e){let t=r.vault.getAbstractFileByPath(e);if(t&&!(t instanceof Nt.TFile))throw new Error(`A folder occupies ${e}.`);return t instanceof Nt.TFile?r.vault.read(t):null}async function uy(r,e){let t=e.split("/");t.pop();let n="";for(let i of t)n=n?`${n}/${i}`:i,r.vault.getAbstractFileByPath(n)||await r.vault.createFolder(n)}async function cE(r,e){let t=await(0,Nt.requestUrl)({url:e.provision,throw:!1});if(t.status!==200)throw new Error(`Type pack unavailable (${t.status}).`);if(t.arrayBuffer.byteLength>1024*1024||await Pi(t.arrayBuffer)!==e.digest)throw new Error("The type pack does not match its catalog digest.");return lE(r,e,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t.arrayBuffer)))}async function lE(r,e,t){let n=br(t),i=br(n.manifest);if(i.kind!=="mdbase.type-pack"||i.id!==e.id||i.version!==e.version||!Array.isArray(i.resources)||i.resources.length!==e.resource_count||!Array.isArray(n.resources)||n.resources.length!==i.resources.length)throw new Error("The type-pack identity or resources do not match the catalog.");let s=new Map;for(let m of n.resources){let y=br(m),g=Ra(y.source);if(s.has(g))throw new Error("Duplicate pack source.");let b=Yt(y.document);if(new TextEncoder().encode(b).byteLength>262144)throw new Error("Pack resource is too large.");s.set(g,b)}let o=new Set,a=[],c=[],l=await Gn(r,Ls),u=l?(0,Nt.parseYaml)(l):{kind:"mdbase.type-pack-lock",lock_version:1,packs:[]};if(u.kind!=="mdbase.type-pack-lock"||u.lock_version!==1||!Array.isArray(u.packs))throw new Error("Existing pack lock cannot be read safely.");let d=u.packs.find(m=>m.id===e.id),f=await Pi(Fd(i));if(d&&(d.version!==e.version||d.digest!==f))throw new Error("This pack is already installed at another revision. Upgrade it with mdbase editor; Obsidian currently supports fresh installs and same-version repair only.");for(let m of i.resources){let y=br(m),g=Ra(y.source),b=Ra(y.target);if(!["contract","type","schema"].includes(String(y.kind))||!["managed","seed"].includes(String(y.mode))||o.has(b))throw new Error("Invalid pack resource or duplicate target.");let v=y.kind==="type"?"_types/":y.kind==="contract"?"_contracts/":"schemas/";if(!b.startsWith(v))throw new Error(`Unsupported pack target ${b}. Default definition folders are required.`);o.add(b);let S=s.get(g),_=fy(y.digest);if(!S||await Pi(S)!==_)throw new Error(`Resource digest mismatch: ${g}`);if(u.packs.some(R=>R.id!==e.id&&R.resources.some($=>$.mode==="managed"&&$.target===b)))throw new Error(`${b} belongs to another installed pack.`);let E=await Gn(r,b),A=d?.resources.find(R=>R.target===b);if(y.mode==="managed"&&E!==null&&await Pi(E)!==_)throw new Error(`${b} already exists with different contents. Nothing was overwritten.`);let x=E===null&&!(y.mode==="seed"&&A)?"create":y.mode==="seed"?"preserve":"unchanged";a.push({path:b,before:E,after:S,action:x}),c.push({kind:y.kind,mode:y.mode,source:g,target:b,digest:_})}let p={id:e.id,version:e.version,digest:f,installed_by:d?.installed_by??"mdbase-obsidian",resources:c},h=`${JSON.stringify({...u,packs:[...u.packs.filter(m=>m.id!==e.id),p].sort((m,y)=>m.id.localeCompare(y.id))},null,2)} +`;return{pack:e,provision:t,lockBefore:l,lockAfter:h,files:a}}async function jd(r){if(!await r.vault.adapter.exists(Fr))return;let e=br(JSON.parse(await r.vault.adapter.read(Fr)));if(!Array.isArray(e.created))throw new Error("Invalid pack recovery journal.");if(await Gn(r,Ls)===e.lockAfter){await r.vault.adapter.remove(Fr);return}for(let t of[...e.created].reverse()){let n=br(t),i=Ra(n.path),s=r.vault.getAbstractFileByPath(i);if(s instanceof Nt.TFile&&await Pi(await r.vault.read(s))===n.digest)await r.fileManager.trashFile(s);else if(s)throw new Error(`Pack recovery stopped: ${i} changed. Your edits and the journal were preserved.`)}await r.vault.adapter.remove(Fr)}var Nd=new WeakSet;async function dE(r,e,t,n){if(Nd.has(r))throw new Error("Another contract pack is installing. Wait for it to finish.");Nd.add(r);try{await uE(r,e,t,n)}finally{Nd.delete(r)}}async function uE(r,e,t,n){if(t(),await r.vault.adapter.exists(Fr))throw new Error("Recover the previous pack installation before trying again.");if(await Gn(r,Ls)!==e.lockBefore)throw new Error("Pack lock changed. Review again.");for(let s of e.files)if(await Gn(r,s.path)!==s.before)throw new Error(`${s.path} changed. Review again.`);await uy(r,Fr);let i={lockAfter:e.lockAfter,created:[]};await r.vault.adapter.write(Fr,JSON.stringify(i));try{let s=e.files.filter(a=>a.action==="create");n?.(0,s.length);for(let[a,c]of s.entries()){if(t(),await uy(r,c.path),await Gn(r,c.path)!==null)throw new Error(`${c.path} appeared during installation.`);if(i.created.push({path:c.path,digest:await Pi(c.after)}),await r.vault.adapter.write(Fr,JSON.stringify(i)),await r.vault.create(c.path,c.after),await Gn(r,c.path)!==c.after)throw new Error(`${c.path} changed during installation. Recovery will preserve competing edits.`);n?.(a+1,s.length)}t();let o=r.vault.getAbstractFileByPath(Ls);o instanceof Nt.TFile?await r.vault.process(o,a=>{if(a!==e.lockBefore)throw new Error("Pack lock changed during installation.");return e.lockAfter}):await r.vault.create(Ls,e.lockAfter),await r.vault.adapter.remove(Fr)}catch(s){throw await jd(r),s}}var Ta=class extends Nt.Modal{constructor(t,n,i){super(t);this.assertWritable=n;this.installed=i;this.dismissed=!1}onOpen(){this.titleEl.setText("Ready-made types \xB7 mdbase-contracts"),this.load()}async load(){this.contentEl.empty(),this.contentEl.createEl("p",{text:"Loading first-party contract catalog\u2026"});try{let t=await aE();if(this.dismissed)return;this.contentEl.empty(),this.contentEl.createEl("p",{text:"Install standard application contracts plus editable starter types. Nothing grants applications access to your vault. Existing starter types are preserved."});let n=this.contentEl.createEl("details");n.createEl("summary",{text:"Advanced and integration packs"});for(let i of t.filter(s=>s.installation.visibility!=="hidden")){let s=(i.installation.visibility==="default"?this.contentEl:n).createDiv({cls:"mdbase-editor-section"});s.createEl("h3",{text:i.display.name}),s.createDiv({cls:"mdbase-muted",text:`Version ${i.version}`}),s.createEl("p",{text:i.display.summary}),i.installation.caution&&s.createEl("p",{text:i.installation.caution});let o=s.createEl("button",{text:"Review installation"}),a=s.createDiv();o.onclick=()=>{o.disabled=!0,cE(this.app,i).then(c=>{if(this.dismissed)return;a.empty();for(let u of c.files)a.createDiv({text:`${u.action} \xB7 ${u.path}`});let l=a.createEl("button",{text:"Install reviewed pack",cls:"mod-cta"});l.onclick=()=>{l.disabled=!0,dE(this.app,c,this.assertWritable,(u,d)=>{l.textContent=`Installing ${u} of ${d} files\u2026`}).then(async()=>{await this.installed(i.installation.primary_type),this.close()}).catch(u=>{a.createDiv({cls:"mdbase-inline-error",text:String(u)}),l.disabled=!1,l.textContent="Install reviewed pack"})}}).catch(c=>{a.createDiv({cls:"mdbase-inline-error",text:String(c)})}).finally(()=>{o.disabled=!1})}}}catch(t){if(this.dismissed)return;this.contentEl.empty(),this.contentEl.createEl("p",{cls:"mdbase-inline-error",text:String(t)}),this.contentEl.createEl("button",{text:"Retry catalog"}).onclick=()=>void this.load()}}onClose(){this.dismissed=!0}};var Ia=class{constructor(){this.checked=new Set;this.revision=0;this.lastCompletedAt=null;this.completedRevision=-1;this.cancelled=!1;this.progress=null}changed(e){this.revision++,e?this.checked.delete(e):this.checked.clear()}markChecked(e){this.checked.add(e)}isChecked(e){return this.checked.has(e)}summary(e){if(this.progress)return this.progress.phase==="uniqueness"?`Checked ${this.progress.completed} of ${this.progress.total} notes \xB7 checking uniqueness\u2026`:`Checking ${this.progress.completed} of ${this.progress.total} notes\u2026`;let t=e.filter(n=>this.checked.has(n)).length;return this.cancelled?`Validation stopped \xB7 ${t} of ${e.length} notes checked \xB7 results incomplete`:this.lastCompletedAt&&this.completedRevision===this.revision?`Validated ${new Date(this.lastCompletedAt).toLocaleTimeString()} \xB7 ${e.length} notes \xB7 including uniqueness`:this.lastCompletedAt?`Changed since last collection validation \xB7 ${t} of ${e.length} notes checked`:t?`Checked ${t} of ${e.length} notes \xB7 collection uniqueness not checked`:"Not checked yet"}};var it=require("obsidian");var bw=require("obsidian");Vt();function YT(r){let e=r.trim();if(!e||e.startsWith("/")||e.includes("\\")||Array.from(e).some(t=>t.charCodeAt(0)<32)||e.split("/").some(t=>!t||t==="."||t===".."||t.startsWith(".")))throw new Error("Choose a visible, vault-relative note path without .. or empty folders.");return e.endsWith(".md")?e:`${e}.md`}var $c=class extends bw.Modal{constructor(t,n,i,s,o){super(t);this.type=n;this.config=i;this.types=s;this.create=o;this.inputs=new Map;this.customPath=!1;this.suggestionVersion=0;this.creating=!1;this.dismissed=!1;this.frontmatter=Dp(n,i)}onOpen(){this.titleEl.setText(`New ${this.type.name}`),this.contentEl.addClass("mdbase-create-note");let t=Np(this.type,this.frontmatter),n=this.type.display_name_key??"title";!t.some(([c])=>c===n)&&this.frontmatter[n]==null&&t.unshift([n,this.type.fields[n]??{type:"string",description:"Used for the file name."}]);for(let[c,l]of t){let u=this.contentEl.createDiv({cls:"mdbase-form-row"}),d=u.createEl("label",{text:`${c}${l.required?" *":""}`});l.description&&u.createDiv({cls:"mdbase-form-description",text:l.description});let f;if(l.type==="boolean"||l.type==="enum"){let h=u.createEl("select");f=h,h.createEl("option",{value:"",text:"Choose\u2026"}),(l.type==="boolean"?[!0,!1]:l.values??[]).forEach((y,g)=>h.createEl("option",{value:String(g),text:String(y)}))}else if(["object","list","any"].includes(l.type??""))f=u.createEl("textarea"),f.placeholder=l.type==="object"?"YAML object":l.type==="list"?"YAML list or comma-separated values":"Value";else{let h=l.type==="date"?"date":l.type==="datetime"?"datetime-local":l.type==="time"?"time":"text";if(f=u.createEl("input",{type:h}),["integer","number"].includes(l.type??"")&&(f.inputMode="decimal"),l.type==="link"){let m=u.createEl("datalist");m.id=`mdbase-links-${this.inputs.size}`,this.app.vault.getMarkdownFiles().slice(0,500).forEach(y=>m.createEl("option",{value:`[[${y.path.replace(/\.md$/,"")}]]`})),f.setAttr("list",m.id)}}d.htmlFor=f.id=`mdbase-note-${c}`;let p=u.createDiv({cls:"mdbase-inline-error",attr:{"aria-live":"polite"}});f.addEventListener("input",()=>{this.readInputs(),this.suggestPath()}),f.addEventListener("change",()=>{this.readInputs(),this.suggestPath()}),this.inputs.set(c,{input:f,definition:l,error:p})}let i=this.contentEl.createDiv({cls:"mdbase-form-row"}),s=i.createEl("label",{text:"Location"});this.pathInput=i.createEl("input",{type:"text"}),s.htmlFor=this.pathInput.id="mdbase-note-location",this.pathInput.addEventListener("input",()=>{this.customPath=!0,this.problem.textContent=""});let o=i.createEl("button",{text:"Use suggested location"});o.onclick=()=>{this.customPath=!1,this.suggestPath()},this.problem=this.contentEl.createDiv({cls:"mdbase-inline-error",attr:{role:"alert"}});let a=this.contentEl.createDiv({cls:"modal-button-container"});a.createEl("button",{text:"Cancel"}).onclick=()=>{this.creating||this.close()},this.submit=a.createEl("button",{text:"Create note",cls:"mod-cta"}),this.submit.onclick=()=>void this.save(),this.suggestPath(),this.inputs.values().next().value?.input.focus()}readInputs(){let t=!0;for(let[n,{input:i,definition:s,error:o}]of this.inputs){o.textContent="";try{if(!i.value.trim()){if(delete this.frontmatter[n],s.required)throw new Error("Required");continue}let a=s.type==="boolean"?[!0,!1]:s.values??[];this.frontmatter[n]=["boolean","enum"].includes(s.type??"")?a[Number(i.value)]:xc(i.value,s)}catch(a){t=!1,o.textContent=a instanceof Error?a.message:String(a)}}return t}async suggestPath(){let t=++this.suggestionVersion;try{let n=await Lp(this.app.vault,this.type,this.frontmatter);!this.dismissed&&t===this.suggestionVersion&&!this.customPath&&(this.pathInput.value=n)}catch(n){!this.dismissed&&t===this.suggestionVersion&&(this.problem.textContent=String(n))}}async save(){if(!(this.creating||!this.readInputs()))try{let t=YT(this.pathInput.value);if(bt(t,this.config))throw new Error("Choose a location included in this collection, not a definition or excluded folder.");if(this.app.vault.getAbstractFileByPath(t))throw new Error("A file already exists at this location. Choose another path.");let n=[...this.types.values()].flatMap(i=>i.name===this.type.name||this.type.extends===i.name?es(t,this.frontmatter,i):[]);if(n.some(i=>i.severity==="error")){for(let i of n){let s=i.field?this.inputs.get(i.field):void 0;s&&(s.error.textContent=i.message)}throw new Error(n.filter(i=>i.severity==="error").map(i=>i.message).join(" \xB7 "))}this.creating=!0,this.submit.disabled=!0,await this.create(t,structuredClone(this.frontmatter)),this.close()}catch(t){this.problem.textContent=t instanceof Error?t.message:String(t)}finally{this.creating=!1,this.submit.disabled=!1}}onClose(){this.dismissed=!0}};Vt();var ts=require("obsidian");var jp=class extends ts.SuggestModal{constructor(t,n,i){super(t);this.resultHandled=!1;this.typeDefs=[...n].sort((s,o)=>s.name.localeCompare(o.name)),this.onResult=i,this.setPlaceholder("Type to search..."),this.setInstructions([{command:"\u2191\u2193",purpose:"navigate"},{command:"\u21B5",purpose:"select"},{command:"esc",purpose:"cancel"}]),this.containerEl.addClass("mdbase-type-picker-modal"),this.titleEl.setText("Select type definition")}getSuggestions(t){let n=t.trim().toLowerCase();return n?this.typeDefs.filter(i=>{let s=i.match?.path_glob??"";return`${i.name} ${i.display_name_key??""} ${i.filePath} ${s}`.toLowerCase().includes(n)}).slice(0,100):this.typeDefs.slice(0,100)}renderSuggestion(t,n){let i=n.createDiv({cls:"mdbase-type-picker-suggestion"});i.createDiv({cls:"mdbase-type-picker-name",text:t.name});let s=i.createDiv({cls:"mdbase-type-picker-meta"});s.createSpan({cls:"mdbase-type-picker-path",text:t.filePath}),s.createSpan({cls:"mdbase-type-picker-count",text:`${Object.keys(t.fields??{}).length} fields`}),t.match?.path_glob&&i.createDiv({cls:"mdbase-type-picker-match",text:`match: ${t.match.path_glob}`})}onChooseSuggestion(t){this.resultHandled=!0,this.onResult({type:"selected",typeDef:t})}onClose(){window.setTimeout(()=>{this.resultHandled||this.onResult({type:"cancelled"})},0),super.onClose()}};function qp(r,e){return new Promise(t=>{new jp(r,e,i=>{if(i.type==="selected"){t(i.typeDef);return}t(null)}).open()})}var Ec=class extends ts.Modal{constructor(){super(...arguments);this.resolve=null;this.settled=!1}confirm(t,n=[]){return new Promise(i=>{this.resolve=i,this.titleEl.setText("Confirm high-impact type changes"),this.contentEl.createEl("p",{text:n.length?`${n.length} existing ${n.length===1?"note":"notes"} would fail validation. Only the type definition will be saved; notes are not changed.`:"These changes may invalidate existing notes. Only the type definition will be saved."});let s=this.contentEl.createEl("ul",{cls:"mdbase-confirm-change-list"});for(let l of t)s.createEl("li",{text:l.summary});if(n.length){let l=this.contentEl.createEl("ul",{cls:"mdbase-confirm-change-list mdbase-confirm-notes"});for(let u of n.slice(0,5))l.createEl("li",{text:u});n.length>5&&l.createEl("li",{text:`${n.length-5} more`})}let o=this.contentEl.createDiv({cls:"modal-button-container"}),a=o.createEl("button",{text:"Keep reviewing"});a.onclick=()=>this.finish(!1);let c=o.createEl("button",{text:"Save high-impact changes"});c.addClass("mod-warning"),c.onclick=()=>this.finish(!0),this.open()})}onClose(){this.settled||this.finish(!1,!1),this.contentEl.empty()}finish(t,n=!0){this.settled||(this.settled=!0,this.resolve?.(t),this.resolve=null,n&&this.close())}},kc=class extends ts.Modal{constructor(){super(...arguments);this.resolve=null;this.settled=!1}confirm(t,n){return new Promise(i=>{this.resolve=i;let s=[...new Set(n.map(d=>d.path))],o=`${s.length} ${s.length===1?"note":"notes"}`;this.titleEl.setText(`${t} in ${o}?`),this.contentEl.createEl("p",{text:`Only the '${n[0]?.field??"affected"}' frontmatter field changes in each note. Notes that changed since validation are skipped.`});let a=this.contentEl.createEl("ul",{cls:"mdbase-confirm-change-list"});for(let d of s.slice(0,8))a.createEl("li",{text:d});s.length>8&&a.createEl("li",{text:`${s.length-8} more`});let c=this.contentEl.createDiv({cls:"modal-button-container"}),l=c.createEl("button",{text:"Cancel"});l.onclick=()=>this.finish(!1);let u=c.createEl("button",{text:`Update ${o}`});u.addClass("mod-cta"),u.onclick=()=>this.finish(!0),this.open()})}onClose(){this.settled||this.finish(!1,!1),this.contentEl.empty()}finish(t,n=!0){this.settled||(this.settled=!0,this.resolve?.(t),this.resolve=null,n&&this.close())}},Ac=class extends ts.Modal{constructor(){super(...arguments);this.resolve=null;this.settled=!1}choose(t){return new Promise(n=>{this.resolve=n,this.titleEl.setText("Disconnect this vault?"),this.contentEl.createEl("p",{text:`This stops synchronization with ${t}. It does not delete the hosted collection.`}),this.contentEl.createEl("p",{text:"Keep all local files, or remove unchanged synced files. Local edits are kept either way."});let i=this.contentEl.createDiv({cls:"modal-button-container"}),s=i.createEl("button",{text:"Cancel"});s.onclick=()=>this.finish(null);let o=i.createEl("button",{text:"Keep files",cls:"mod-cta"});o.onclick=()=>this.finish("keep");let a=i.createEl("button",{text:"Remove unchanged files"});a.addClass("mod-warning"),a.onclick=()=>this.finish("remove"),this.open()})}onClose(){this.settled||this.finish(null,!1),this.contentEl.empty()}finish(t,n=!0){this.settled||(this.settled=!0,this.resolve?.(t),this.resolve=null,n&&this.close())}};function vw(r){let{app:e}=r,t=()=>r.getMirrorProfile()!==null;r.addCommand({id:"mdbase-open",name:"Open workspace",callback:()=>void r.openWorkspace()}),r.addCommand({id:"mdbase-initialize-collection",name:"Initialize collection",checkCallback:n=>t()||e.vault.getAbstractFileByPath("mdbase.yaml")?!1:(n||QT(r),!0)}),r.addCommand({id:"mdbase-create-type",name:"Create type definition",callback:()=>void r.openWorkspace("types").then(n=>n.createNewType())}),r.addCommand({id:"mdbase-edit-type",name:"Edit type definition",callback:()=>void ZT(r)}),r.addCommand({id:"mdbase-create-note-from-type",name:"Create note from type",callback:()=>void Bp(r)}),r.addCommand({id:"mdbase-validate-current-note",name:"Validate current note",checkCallback:n=>{let i=e.workspace.getActiveFile();return!(i instanceof it.TFile)||i.extension!=="md"?!1:(n||eI(r,i),!0)}}),r.addCommand({id:"mdbase-validate-collection",name:"Validate collection",callback:()=>void r.runCollectionValidation(!0)}),r.addCommand({id:"mdbase-sync-now",name:"Sync now",checkCallback:n=>t()?(n||XT(r),!0):!1}),r.addCommand({id:"mdbase-cancel-sync",name:"Cancel current sync",checkCallback:n=>r.sync.isSyncing()?(n||r.sync.cancel(),!0):!1}),r.addCommand({id:"mdbase-resolve-conflicts",name:"Resolve sync conflicts",checkCallback:n=>!t()||!r.sync.state.status?.conflicts.length?!1:(n||r.openWorkspace("sync").then(i=>i.focusSyncSection("conflicts")),!0)}),r.addCommand({id:"mdbase-reconnect",name:"Reconnect collection",checkCallback:n=>{let i=r.sync.state.problem;return!t()||!i||i.action!=="reauthorize"?!1:(n||r.openWorkspace("sync").then(s=>s.reconnectCollection()),!0)}}),r.addCommand({id:"mdbase-copy-sync-diagnostics",name:"Copy sync diagnostics",checkCallback:n=>t()?(n||r.copySyncDiagnostics(),!0):!1}),r.addCommand({id:"mdbase-note-sync-history",name:"Show sync history for current note",checkCallback:n=>{let i=e.workspace.getActiveFile();return!i||!t()?!1:(n||r.openNoteSyncHistory(i.path),!0)}}),r.registerEvent(e.workspace.on("file-menu",(n,i)=>{!(i instanceof it.TFile)||!t()||n.addItem(s=>s.setTitle("Sync history").setIcon("history").onClick(()=>r.openNoteSyncHistory(i.path)))}))}async function XT(r){let e=await r.sync.syncNow(),{message:t,problem:n}=r.sync.state;if(e==="needs_review"){let i=r.sync.safety()?.reasons??[];new it.Notice(`Review before syncing: ${i.join(", ").toLowerCase()||"changes need attention"}.`),await r.openWorkspace("sync")}else e==="busy"?new it.Notice("A sync is already running."):e==="paused"?new it.Notice("Sync is paused."):e==="failed"?new it.Notice(n?.message??(t||"Sync failed.")):t&&new it.Notice(t)}async function QT(r){r.connectSync.assertLocalAuthorityWritable();let{created:e}=await xo(r.app.vault,{seedNoteType:!1});r.invalidateSchemaCache(),new it.Notice(e.length?`Initialized mdbase collection: ${e.join(", ")}`:"mdbase collection already initialized.")}async function ZT(r){let e=await r.requireConfigAndTypes();if(!e)return;if(e.types.size===0){new it.Notice("No type definitions found.");return}let t=r.app.workspace.getActiveFile(),n=[];if(t instanceof it.TFile&&t.extension==="md"){let o=[...e.types.values()].find(a=>a.filePath===t.path);if(o)n=[o];else{let a=Me(await r.app.vault.cachedRead(t));a.error||(n=Ge(t.path,a.frontmatter,e.config,e.types).flatMap(c=>e.types.get(c)??[]))}}let i=n.length===1?n[0]:await qp(r.app,n.length?n:[...e.types.values()]);if(!i)return;await(await r.openWorkspace("types")).editType(i.filePath)}async function eI(r,e){let t=await r.validateFileAndStore(e,"manual");if(t.length===0){new it.Notice("No issues in current note.");return}new it.Notice(`Found ${t.length} issue${t.length===1?"":"s"} in current note.`),(await r.openWorkspace("issues")).showIssuesForPath(e.path)}async function Bp(r,e){r.connectSync.assertLocalAuthorityWritable();let t=await r.requireConfigAndTypes();if(!t)return;if(t.types.size===0){new it.Notice("No type definitions found.");return}if(r.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access.");let n=e?t.types.get(e):await qp(r.app,Array.from(t.types.values()));n&&new $c(r.app,n,t.config,t.types,async(i,s)=>{if(r.connectSync.assertLocalAuthorityWritable(),r.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access.");let{createNoteFromType:o}=await Promise.resolve().then(()=>(Vt(),gw)),a=await o(r.app.vault,i,s);await r.app.workspace.getLeaf(!0).openFile(a),await r.validateFileAndStore(a,"manual")}).open()}var ww=require("obsidian");Vt();function Up(r,e){let t=Me(r);if(t.error)throw new Error(`Invalid frontmatter: ${t.error}`);return tI(t.frontmatter,e)?{content:`--- +${(0,ww.stringifyYaml)(t.frontmatter).trimEnd()} --- -${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(` +${t.body}`,changed:!0}:{content:r,changed:!1}}function _w(r){if(!r.field)return null;if(["unknown_field","missing_required"].includes(r.code))return/[.[\]]/.test(r.field)?null:[r.field];if(!["schema_additional_properties","schema_required"].includes(r.code))return null;let e=r.details?.instance_path,t=r.details?.property;return typeof e!="string"||typeof t!="string"?null:[...e===""?[]:e.slice(1).split("/").map(n=>n.replace(/~1/g,"/").replace(/~0/g,"~")),t]}function Sw(r){return _w(r)?["unknown_field","schema_additional_properties"].includes(r.code)?"Remove field":"Add placeholder":null}function tI(r,e){let t=_w(e);if(!t?.length)return!1;let n=r;for(let a of t.slice(0,-1)){if(!n||typeof n!="object"||!Object.prototype.hasOwnProperty.call(n,a))return!1;n=n[a]}if(!n||typeof n!="object"||Array.isArray(n))return!1;let i=n,s=t[t.length-1],o=Object.prototype.hasOwnProperty.call(i,s);if(["unknown_field","schema_additional_properties"].includes(e.code)){if(!o)return!1;delete i[s]}else{if(o)return!1;Object.defineProperty(i,s,{value:"TODO",enumerable:!0,configurable:!0,writable:!0})}return!0}var L=require("obsidian");var O=class extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name="InteropError"}toPortableError(e){return{code:this.code,message:this.message,...this.details===void 0?{}:{details:this.details},...e===void 0?{}:{retryable:e}}}},$o=class extends Error{status;error;constructor(e,t){super(t.message),this.status=e,this.error=t,this.name="ActionHandlerError"}};var xw=Wn(Zf(),1),$w=Wn(lp(),1);var Vp={contract:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/v0.3/data-contract.schema.json",title:"mdbase v0.3 contract frontmatter",type:"object",required:["kind","contract_type","id","version"],properties:{kind:{const:"mdbase.contract"},contract_type:{enum:["record","event","action"]},id:{$ref:"#/$defs/contractId"},version:{$ref:"#/$defs/semanticVersion"},name:{type:"string",minLength:1},description:{type:"string"},record_schema:{$ref:"#/$defs/schemaWrapper"},binding_schema:{$ref:"#/$defs/schemaWrapper"},data_schema:{$ref:"#/$defs/schemaWrapper"},source_schema:{$ref:"#/$defs/schemaWrapper"},input_schema:{$ref:"#/$defs/schemaWrapper"},output_schema:{$ref:"#/$defs/schemaWrapper"},error_schema:{$ref:"#/$defs/schemaWrapper"},provider_schema:{$ref:"#/$defs/schemaWrapper"},behavior:{$ref:"#/$defs/actionBehavior"}},patternProperties:{"^x-[A-Za-z][A-Za-z0-9._:-]{0,127}$":!0},oneOf:[{properties:{contract_type:{const:"record"},record_schema:!0,binding_schema:!0,data_schema:!1,source_schema:!1,input_schema:!1,output_schema:!1,error_schema:!1,provider_schema:!1,behavior:!1},required:["record_schema"]},{properties:{contract_type:{const:"event"},record_schema:!1,binding_schema:!1,data_schema:!0,source_schema:!0,input_schema:!1,output_schema:!1,error_schema:!1,provider_schema:!1,behavior:!1},required:["data_schema"]},{properties:{contract_type:{const:"action"},record_schema:!1,binding_schema:!1,data_schema:!1,source_schema:!1,input_schema:!0,output_schema:!0,error_schema:!0,provider_schema:!0,behavior:!0},required:["input_schema"]}],additionalProperties:!1,$defs:{contractId:{type:"string",minLength:3,maxLength:128,pattern:"^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$"},semanticVersion:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},schemaWrapper:{type:"object",required:["dialect"],properties:{dialect:{const:"json-schema-2020-12"},value:{type:"object"},ref:{type:"string",minLength:1}},oneOf:[{required:["value"],properties:{value:!0,ref:!1}},{required:["ref"],properties:{ref:!0,value:!1}}],additionalProperties:!1},actionBehavior:{type:"object",properties:{idempotency:{enum:["none","optional","required"]},cancellation:{enum:["none","cooperative"]}},additionalProperties:!1}}},profile:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/profile.schema.json",title:"mdbase event and action interoperability profile 0.1",oneOf:[{$ref:"#/$defs/event"},{$ref:"#/$defs/actionRequest"},{$ref:"#/$defs/actionInvocation"},{$ref:"#/$defs/actionOutcome"},{$ref:"#/$defs/actionCancellation"},{$ref:"#/$defs/eventSourceDeclaration"},{$ref:"#/$defs/actionProviderDeclaration"},{$ref:"#/$defs/conformanceClaim"}],$defs:{contractId:{type:"string",minLength:3,maxLength:128,pattern:"^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$"},semanticVersion:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},semanticVersionRequirement:{type:"string",minLength:1,maxLength:128},digest:{type:"string",pattern:"^sha256:[0-9a-f]{64}$"},portableId:{type:"string",minLength:1,maxLength:256,pattern:"^[A-Za-z0-9][A-Za-z0-9._:@/-]*$"},exactContract:{type:"object",required:["id","version","digest"],properties:{id:{$ref:"#/$defs/contractId"},version:{$ref:"#/$defs/semanticVersion"},digest:{$ref:"#/$defs/digest"}},additionalProperties:!1},contractRequirement:{type:"object",required:["id","version"],properties:{id:{$ref:"#/$defs/contractId"},version:{$ref:"#/$defs/semanticVersionRequirement"},digest:{$ref:"#/$defs/digest"}},additionalProperties:!1},implementationIdentity:{type:"object",required:["application","implementation","version"],properties:{application:{$ref:"#/$defs/portableId"},implementation:{$ref:"#/$defs/portableId"},version:{$ref:"#/$defs/semanticVersion"},instance_id:{$ref:"#/$defs/portableId"}},additionalProperties:!1},transportCapabilities:{type:"object",required:["delivery","ordering","cancellation","deadlines"],properties:{delivery:{type:"array",minItems:1,uniqueItems:!0,items:{enum:["ephemeral","at_least_once","durable_cursor","offline_queue"]}},ordering:{type:"array",uniqueItems:!0,items:{enum:["none","source","subject"]}},cancellation:{type:"boolean"},deadlines:{type:"boolean"},provider_discovery:{type:"boolean"},max_payload_bytes:{type:"integer",minimum:1},outcome_retention_seconds:{type:"integer",minimum:0},request_deduplication:{type:"boolean"},cross_process_identity:{type:"boolean"}},additionalProperties:!1},extensionValue:{oneOf:[{type:"null"},{type:"boolean"},{type:"integer"},{type:"number"},{type:"string"}]},event:{title:"mdbase CloudEvents event envelope",type:"object",required:["specversion","id","source","type","time","datacontenttype","dataschema","data","mdbaseprofile","mdbasecontractversion","mdbasecontractdigest","mdbaseapplication","mdbaseimplementation","mdbaseimplementationversion"],properties:{specversion:{const:"1.0"},id:{$ref:"#/$defs/portableId"},source:{type:"string",format:"uri-reference",minLength:1},type:{$ref:"#/$defs/contractId"},time:{type:"string",format:"date-time"},subject:{type:"string",format:"uri-reference",minLength:1},datacontenttype:{const:"application/json"},dataschema:{type:"string",format:"uri",minLength:1},data:!0,mdbaseprofile:{const:"0.1"},mdbasecontractversion:{$ref:"#/$defs/semanticVersion"},mdbasecontractdigest:{$ref:"#/$defs/digest"},mdbaseapplication:{$ref:"#/$defs/portableId"},mdbaseimplementation:{$ref:"#/$defs/portableId"},mdbaseimplementationversion:{$ref:"#/$defs/semanticVersion"},mdbaseinstanceid:{$ref:"#/$defs/portableId"},correlationid:{$ref:"#/$defs/portableId"},causationid:{$ref:"#/$defs/portableId"}},propertyNames:{pattern:"^[a-z0-9]+$"},additionalProperties:{$ref:"#/$defs/extensionValue"}},actionRequest:{title:"mdbase action request",type:"object",required:["kind","profile_version","request_id","contract","caller","created_at","input"],properties:{kind:{const:"mdbase.action.request"},profile_version:{const:"0.1"},request_id:{$ref:"#/$defs/portableId"},contract:{$ref:"#/$defs/contractRequirement"},caller:{$ref:"#/$defs/implementationIdentity"},created_at:{type:"string",format:"date-time"},correlation_id:{$ref:"#/$defs/portableId"},causation_id:{$ref:"#/$defs/portableId"},subject:{type:"string",format:"uri-reference",minLength:1},idempotency_key:{type:"string",minLength:1,maxLength:512},deadline:{type:"string",format:"date-time"},requested_provider:{type:"object",properties:{application:{$ref:"#/$defs/portableId"},implementation:{$ref:"#/$defs/portableId"},instance_id:{$ref:"#/$defs/portableId"}},minProperties:1,additionalProperties:!1},authorization_context:{type:"string",format:"uri-reference",minLength:1},input:!0},additionalProperties:!1},actionInvocation:{title:"mdbase admitted action invocation",type:"object",required:["kind","profile_version","invocation_id","attempt_id","request_id","contract","caller","provider","provider_declaration_digest","handler_id","admitted_at","input"],properties:{kind:{const:"mdbase.action.invocation"},profile_version:{const:"0.1"},invocation_id:{$ref:"#/$defs/portableId"},attempt_id:{$ref:"#/$defs/portableId"},request_id:{$ref:"#/$defs/portableId"},contract:{$ref:"#/$defs/exactContract"},caller:{$ref:"#/$defs/implementationIdentity"},provider:{$ref:"#/$defs/implementationIdentity"},provider_declaration_digest:{$ref:"#/$defs/digest"},handler_id:{$ref:"#/$defs/portableId"},admitted_at:{type:"string",format:"date-time"},correlation_id:{$ref:"#/$defs/portableId"},causation_id:{$ref:"#/$defs/portableId"},subject:{type:"string",format:"uri-reference",minLength:1},idempotency_key:{type:"string",minLength:1,maxLength:512},deadline:{type:"string",format:"date-time"},authorization_context:{type:"string",format:"uri-reference",minLength:1},input:!0},additionalProperties:!1},portableError:{type:"object",required:["code","message"],properties:{code:{enum:["unknown_contract","unsupported_contract_version","contract_digest_conflict","invalid_event_data","invalid_action_input","invalid_action_output","no_provider","ambiguous_provider","requested_provider_unavailable","unauthorized","capability_denied","request_rejected","deadline_exceeded","cancellation_unsupported","cancelled","handler_failure","outcome_indeterminate","transport_unavailable","unsupported_transport_capability"]},message:{type:"string",minLength:1},details:!0,retryable:{type:"boolean"}},additionalProperties:!1},actionOutcome:{title:"mdbase action outcome",type:"object",required:["kind","profile_version","outcome_id","request_id","invocation_id","attempt_id","contract","provider","provider_declaration_digest","status","completed_at"],properties:{kind:{const:"mdbase.action.outcome"},profile_version:{const:"0.1"},outcome_id:{$ref:"#/$defs/portableId"},request_id:{$ref:"#/$defs/portableId"},invocation_id:{$ref:"#/$defs/portableId"},attempt_id:{$ref:"#/$defs/portableId"},contract:{$ref:"#/$defs/exactContract"},provider:{$ref:"#/$defs/implementationIdentity"},provider_declaration_digest:{$ref:"#/$defs/digest"},status:{enum:["succeeded","rejected","failed","cancelled","outcome_indeterminate"]},completed_at:{type:"string",format:"date-time"},output:!0,error:{$ref:"#/$defs/portableError"}},allOf:[{if:{properties:{status:{const:"succeeded"}},required:["status"]},then:{required:["output"],not:{required:["error"]}},else:{required:["error"],not:{required:["output"]}}}],additionalProperties:!1},actionCancellation:{title:"mdbase action cancellation request",type:"object",required:["kind","profile_version","cancellation_id","request_id","caller","requested_at"],properties:{kind:{const:"mdbase.action.cancel"},profile_version:{const:"0.1"},cancellation_id:{$ref:"#/$defs/portableId"},request_id:{$ref:"#/$defs/portableId"},caller:{$ref:"#/$defs/implementationIdentity"},requested_at:{type:"string",format:"date-time"},reason:{type:"string",maxLength:1024}},additionalProperties:!1},eventSourceDeclaration:{title:"mdbase event-source declaration",type:"object",required:["kind","profile_version","declaration_id","declaration_digest","source","contracts"],properties:{kind:{const:"mdbase.event-source"},profile_version:{const:"0.1"},declaration_id:{$ref:"#/$defs/portableId"},declaration_digest:{$ref:"#/$defs/digest"},source:{$ref:"#/$defs/implementationIdentity"},contracts:{type:"array",minItems:1,items:{type:"object",required:["requirement","resolved"],properties:{requirement:{$ref:"#/$defs/contractRequirement"},resolved:{$ref:"#/$defs/exactContract"},binding:!0,ordering:{type:"array",uniqueItems:!0,items:{enum:["none","source","subject"]}}},additionalProperties:!1}}},additionalProperties:!1},actionProviderDeclaration:{title:"mdbase action-provider declaration",type:"object",required:["kind","profile_version","declaration_id","declaration_digest","provider","handlers"],properties:{kind:{const:"mdbase.action-provider"},profile_version:{const:"0.1"},declaration_id:{$ref:"#/$defs/portableId"},declaration_digest:{$ref:"#/$defs/digest"},provider:{$ref:"#/$defs/implementationIdentity"},handlers:{type:"array",minItems:1,items:{type:"object",required:["handler_id","requirement","resolved"],properties:{handler_id:{$ref:"#/$defs/portableId"},requirement:{$ref:"#/$defs/contractRequirement"},resolved:{$ref:"#/$defs/exactContract"},binding:!0,idempotency:{type:"object",required:["mode"],properties:{mode:{enum:["none","request"]},retention_seconds:{type:"integer",minimum:1}},additionalProperties:!1},cancellation:{enum:["none","cooperative"]},max_concurrency:{type:"integer",minimum:1}},additionalProperties:!1}}},additionalProperties:!1},conformanceClaim:{title:"mdbase interoperability conformance claim",type:"object",required:["kind","profile_version","implementation","roles","transport"],properties:{kind:{const:"mdbase.interop.conformance"},profile_version:{const:"0.1"},implementation:{$ref:"#/$defs/implementationIdentity"},roles:{type:"array",minItems:1,uniqueItems:!0,items:{enum:["event_source","event_consumer","action_caller","action_provider","bridge"]}},transport:{$ref:"#/$defs/transportCapabilities"},evidence:{type:"array",items:{type:"object",required:["scenario","result"],properties:{scenario:{type:"string",minLength:1},result:{const:"pass"},uri:{type:"string",format:"uri-reference"}},additionalProperties:!1}}},additionalProperties:!1}}},event:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/event.schema.json",title:"mdbase CloudEvents event envelope",$ref:"profile.schema.json#/$defs/event"},actionRequest:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-request.schema.json",title:"mdbase action request",$ref:"profile.schema.json#/$defs/actionRequest"},actionInvocation:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-invocation.schema.json",title:"mdbase admitted action invocation",$ref:"profile.schema.json#/$defs/actionInvocation"},actionOutcome:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-outcome.schema.json",title:"mdbase action outcome",$ref:"profile.schema.json#/$defs/actionOutcome"},actionCancellation:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-cancellation.schema.json",title:"mdbase action cancellation request",$ref:"profile.schema.json#/$defs/actionCancellation"},eventSourceDeclaration:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/event-source-declaration.schema.json",title:"mdbase event-source declaration",$ref:"profile.schema.json#/$defs/eventSourceDeclaration"},actionProviderDeclaration:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-provider-declaration.schema.json",title:"mdbase action-provider declaration",$ref:"profile.schema.json#/$defs/actionProviderDeclaration"},conformanceClaim:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/conformance-claim.schema.json",title:"mdbase interoperability conformance claim",$ref:"profile.schema.json#/$defs/conformanceClaim"}};var rI=$w.default;function Ew(){return Object.fromEntries(Object.entries(Vp).map(([r,e])=>[r,structuredClone(e)]))}function Hp(){let r=new xw.Ajv2020({allErrors:!0,strict:!1,validateFormats:!0});rI(r);let e=Ew();r.addSchema(e.profile);for(let[t,n]of Object.entries(e))t!=="profile"&&r.addSchema(n);return r}function Vr(r,e){let t=String(Vp[e].$id),n=r.getSchema(t);if(!n)throw new Error(`Canonical interoperability schema is unavailable: ${e}`);return n}function wn(r){return(r??[]).map(e=>`${e.instancePath||"/"} ${e.message??e.keyword}`).join("; ")}function $r(r,e){if(!("value"in r))throw new O("contract_digest_conflict",`${e} must be resolved to an inline JSON Schema before runtime registration.`);return structuredClone(r.value)}function kw(r){let e={kind:r.kind,contract_type:r.contract_type,id:r.id,version:r.version};switch(r.contract_type){case"record":e.record_schema=$r(r.record_schema,"record_schema"),r.binding_schema&&(e.binding_schema=$r(r.binding_schema,"binding_schema"));break;case"event":e.data_schema=$r(r.data_schema,"data_schema"),r.source_schema&&(e.source_schema=$r(r.source_schema,"source_schema"));break;case"action":e.input_schema=$r(r.input_schema,"input_schema"),r.output_schema&&(e.output_schema=$r(r.output_schema,"output_schema")),r.error_schema&&(e.error_schema=$r(r.error_schema,"error_schema")),r.provider_schema&&(e.provider_schema=$r(r.provider_schema,"provider_schema")),r.behavior&&(e.behavior=structuredClone(r.behavior));break}return e}async function Pc(r){return ns(kw(r))}async function ns(r){return`sha256:${await nI(zp(r))}`}function Aw(r,e){return{data:rs(r,e.data_schema,`${e.id} data_schema`),...e.source_schema?{source:rs(r,e.source_schema,`${e.id} source_schema`)}:{}}}function Pw(r,e){return{input:rs(r,e.input_schema,`${e.id} input_schema`),...e.output_schema?{output:rs(r,e.output_schema,`${e.id} output_schema`)}:{},...e.error_schema?{error:rs(r,e.error_schema,`${e.id} error_schema`)}:{},...e.provider_schema?{provider:rs(r,e.provider_schema,`${e.id} provider_schema`)}:{}}}function Cc(r,e,t,n){if(!(!r||r(e)))throw new O(t,`${n} failed JSON Schema validation: ${wn(r.errors)}`)}function rs(r,e,t){try{return r.compile($r(e,t))}catch(n){throw new O("contract_digest_conflict",`${t} could not be compiled: ${n instanceof Error?n.message:String(n)}`)}}function zp(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(zp).join(",")}]`:`{${Object.entries(r).filter(([,t])=>t!==void 0).sort(([t],[n])=>tn?1:0).map(([t,n])=>`${JSON.stringify(t)}:${zp(n)}`).join(",")}}`}async function nI(r){let e=new TextEncoder().encode(r),t=await globalThis.crypto.subtle.digest("SHA-256",e);return[...new Uint8Array(t)].map(n=>n.toString(16).padStart(2,"0")).join("")}var zr=Wn(v0(),1);var fh={delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},uN=new Set(["specversion","id","source","type","time","subject","datacontenttype","dataschema","data","mdbaseprofile","mdbasecontractversion","mdbasecontractdigest","mdbaseapplication","mdbaseimplementation","mdbaseimplementationversion","mdbaseinstanceid","correlationid","causationid"]),Mo=class{options;profileVersion="0.1";transport;ajv=Hp();contractValidator=Vr(this.ajv,"contract");eventValidator=Vr(this.ajv,"event");actionRequestValidator=Vr(this.ajv,"actionRequest");actionInvocationValidator=Vr(this.ajv,"actionInvocation");actionOutcomeValidator=Vr(this.ajv,"actionOutcome");eventSourceDeclarationValidator=Vr(this.ajv,"eventSourceDeclaration");actionProviderDeclarationValidator=Vr(this.ajv,"actionProviderDeclaration");contracts=new Map;clients=new Map;eventSources=new Map;actionProviders=new Map;subscriptions=new Map;activeActions=new Map;completedActions=new Map;admissionLocks=new Map;recentEvents=new Map;authorize;now;idFactory;recentEventLimit;completedRequestLimit;nextSequence=0;disposed=!1;constructor(e={}){this.options=e,this.authorize=e.authorize??(()=>!1),this.now=e.now??(()=>new Date),this.idFactory=e.idFactory??(t=>{this.nextSequence+=1;let n=typeof globalThis.crypto?.randomUUID=="function"?globalThis.crypto.randomUUID():`${this.now().getTime().toString(36)}-${this.nextSequence.toString(36)}`;return`${t}_${n}`}),this.recentEventLimit=Math.max(1,e.recentEventLimit??1e3),this.completedRequestLimit=Math.max(1,e.completedRequestLimit??1e3),this.transport={...fh,...structuredClone(e.transport??{}),delivery:[...e.transport?.delivery??fh.delivery],ordering:[...e.transport?.ordering??fh.ordering]}}connect(e){this.assertActive(),fN(e);let t=this.idFactory("client"),n={identity:structuredClone(e),disposed:!1,sources:new Set,providers:new Set,subscriptions:new Set};return this.clients.set(t,n),{identity:structuredClone(e),registerEventSource:i=>this.registerEventSource(t,i),publishEvent:i=>this.publishEvent(t,i),subscribeEvents:(i,s)=>this.subscribeEvents(t,i,s),registerActionProvider:i=>this.registerActionProvider(t,i),invokeAction:i=>this.invokeAction(t,i),cancelAction:(i,s)=>this.cancelAction(t,i,s),dispose:()=>this.disposeClient(t)}}describe(){return this.assertActive(),{profile_version:"0.1",transport:structuredClone(this.transport),contracts:[...this.contracts.values()].map(({artifact:e,reference:t})=>({artifact:structuredClone(e),reference:structuredClone(t)})).sort((e,t)=>e.reference.id.localeCompare(t.reference.id)||e.reference.version.localeCompare(t.reference.version)),event_sources:[...this.eventSources.values()].map(({declaration:e})=>structuredClone(e)).sort((e,t)=>e.declaration_id.localeCompare(t.declaration_id)),action_providers:[...this.actionProviders.values()].map(({declaration:e})=>structuredClone(e)).sort((e,t)=>e.declaration_id.localeCompare(t.declaration_id))}}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of[...this.clients.keys()])await this.disposeClient(e,!0);this.contracts.clear(),this.recentEvents.clear(),this.completedActions.clear()}}async registerEventSource(e,t){let n=this.requireClient(e);if(t.contracts.length===0)throw new O("request_rejected","An event-source declaration must include a contract.");let i=`${e}:${t.declaration_id}`;if(this.eventSources.has(i))throw new O("request_rejected",`Event-source declaration ${t.declaration_id} is already registered.`);let s=new Map;for(let l of t.contracts){let u=await this.prepareEventContract(l.contract),d=w0(l.requirement,u.reference);if(_0(d,u.reference),await this.assertAuthorized({operation:"register_event_source",principal:n.identity,contract:u.reference}),u.sourceValidator&&!u.sourceValidator(l.binding??{}))throw new O("request_rejected",`${u.reference.id} source binding is invalid: ${wn(u.sourceValidator.errors)}`);let f=Uc(u.reference);if(s.has(f))throw new O("contract_digest_conflict",`Event contract ${f} is repeated by one declaration.`);s.set(f,{contract:u,requirement:d,...l.binding===void 0?{}:{binding:structuredClone(l.binding)},...l.ordering===void 0?{}:{ordering:[...l.ordering]}})}let o={kind:"mdbase.event-source",profile_version:"0.1",declaration_id:t.declaration_id,source:structuredClone(n.identity),contracts:[...s.values()].map(({contract:l,requirement:u,binding:d,ordering:f})=>({requirement:structuredClone(u),resolved:structuredClone(l.reference),...d===void 0?{}:{binding:d},...f===void 0?{}:{ordering:f}}))},a={...o,declaration_digest:await ns(o)};Sn(this.eventSourceDeclarationValidator,a,"request_rejected","Event-source declaration"),this.commitContracts([...s.values()].map(({contract:l})=>l)),this.eventSources.set(i,{id:i,clientId:e,declaration:structuredClone(a),contracts:new Map([...s.entries()].map(([l,u])=>[l,{contract:u.contract,...u.binding===void 0?{}:{binding:u.binding}}]))}),n.sources.add(i);let c=!0;return{declaration:structuredClone(a),dispose:()=>{c&&(c=!1,this.removeEventSource(i))}}}async publishEvent(e,t){let n=this.requireClient(e),i=Uc(t.contract),s=[...n.sources].map(h=>this.eventSources.get(h)).find(h=>h?.contracts.has(i));if(!s)throw new O("unknown_contract",`This client has not registered event contract ${t.contract.id} ${t.contract.version}.`);let o=s.contracts.get(i)?.contract;if(!o)throw new O("unknown_contract",`Event contract ${i} is unavailable.`);if(t.contract.digest&&t.contract.digest!==o.reference.digest)throw new O("contract_digest_conflict",`Event contract ${i} has a different digest.`);await this.assertAuthorized({operation:"publish_event",principal:n.identity,contract:o.reference,...t.subject===void 0?{}:{subject:t.subject}}),ph(t.data,"invalid_event_data",`Event ${o.reference.id} data`),Cc(o.dataValidator,t.data,"invalid_event_data",`Event ${o.reference.id} data`);let a=t.extensions??{};for(let h of Object.keys(a))if(uN.has(h))throw new O("request_rejected",`Event extension ${h} is reserved.`);let c={...structuredClone(a),specversion:"1.0",id:t.id??this.idFactory("evt"),source:pN(n.identity),type:o.reference.id,time:t.time??this.now().toISOString(),...t.subject===void 0?{}:{subject:t.subject},datacontenttype:"application/json",dataschema:$0(o.reference),data:structuredClone(t.data),mdbaseprofile:"0.1",mdbasecontractversion:o.reference.version,mdbasecontractdigest:o.reference.digest,mdbaseapplication:n.identity.application,mdbaseimplementation:n.identity.implementation,mdbaseimplementationversion:n.identity.version,...n.identity.instance_id===void 0?{}:{mdbaseinstanceid:n.identity.instance_id},...t.correlation_id===void 0?{}:{correlationid:t.correlation_id},...t.causation_id===void 0?{}:{causationid:t.causation_id}};Sn(this.eventValidator,c,"invalid_event_data","Event envelope"),hh(this.transport,c),hN(c,o.reference);let l=`${c.source}\0${c.id}`,u=this.recentEvents.get(l);if(u){if(JSON.stringify(u)!==JSON.stringify(c))throw new O("contract_digest_conflict",`Event ${c.source} ${c.id} was reused with different content.`);return{event:structuredClone(u),deliveries:0,duplicate:!0}}this.recentEvents.set(l,structuredClone(c)),x0(this.recentEvents,this.recentEventLimit);let d=[...this.subscriptions.values()].filter(({subscription:h})=>Vc(h.contract,o.reference)),f=await Promise.allSettled(d.map(async h=>await this.isAuthorized({operation:"subscribe_event",principal:h.principal,contract:o.reference,...c.subject===void 0?{}:{subject:c.subject}})?(await h.handler(structuredClone(c)),!0):!1)),p=0;for(let h of f)h.status==="fulfilled"&&h.value?p+=1:h.status==="rejected"&&this.report({severity:"error",code:"event_consumer_failed",message:`An event consumer failed while handling ${c.type}.`,contract:o.reference,cause:h.reason});return{event:structuredClone(c),deliveries:p,duplicate:!1}}async subscribeEvents(e,t,n){let i=this.requireClient(e);mh(t.contract),gN(this.transport,t.require_transport),await this.assertAuthorized({operation:"subscribe_event",principal:i.identity,contract:t.contract});let s=this.idFactory("subscription");this.subscriptions.set(s,{id:s,clientId:e,principal:structuredClone(i.identity),subscription:structuredClone(t),handler:n}),i.subscriptions.add(s);let o=!0;return{dispose:()=>{o&&(o=!1,this.removeSubscription(s))}}}async registerActionProvider(e,t){let n=this.requireClient(e);if(t.handlers.length===0)throw new O("request_rejected","An action-provider declaration must include a handler.");let i=`${e}:${t.declaration_id}`;if(this.actionProviders.has(i))throw new O("request_rejected",`Action-provider declaration ${t.declaration_id} is already registered.`);let s=[],o=new Set;for(let d of t.handlers){if(o.has(d.handler_id))throw new O("request_rejected",`Handler ${d.handler_id} is repeated.`);o.add(d.handler_id);let f=await this.prepareActionContract(d.contract),p=w0(d.requirement,f.reference);if(_0(p,f.reference),await this.assertAuthorized({operation:"register_action_provider",principal:n.identity,contract:f.reference,provider:n.identity}),f.providerValidator&&!f.providerValidator(d.binding??{}))throw new O("request_rejected",`${f.reference.id} provider binding is invalid: ${wn(f.providerValidator.errors)}`);let h=d.contract.behavior?.idempotency??"none";if(d.idempotency?.mode==="request"&&h==="none")throw new O("request_rejected",`${f.reference.id} does not permit request deduplication.`);if(h==="required"&&d.idempotency?.mode!=="request")throw new O("request_rejected",`${f.reference.id} requires a provider with request deduplication.`);let m=d.contract.behavior?.cancellation??"none";if(d.cancellation==="cooperative"&&m!=="cooperative")throw new O("request_rejected",`${f.reference.id} does not declare cooperative cancellation.`);s.push({contract:f,declaration:{handler_id:d.handler_id,requirement:p,resolved:structuredClone(f.reference),...d.binding===void 0?{}:{binding:structuredClone(d.binding)},...d.idempotency===void 0?{}:{idempotency:structuredClone(d.idempotency)},...d.cancellation===void 0?{}:{cancellation:d.cancellation},...d.max_concurrency===void 0?{}:{max_concurrency:d.max_concurrency}},handler:d.handler})}let a={kind:"mdbase.action-provider",profile_version:"0.1",declaration_id:t.declaration_id,provider:structuredClone(n.identity),handlers:s.map(({declaration:d})=>structuredClone(d))},c={...a,declaration_digest:await ns(a)};Sn(this.actionProviderDeclarationValidator,c,"request_rejected","Action-provider declaration"),this.commitContracts(s.map(({contract:d})=>d));let l=s.map(({contract:d,declaration:f,handler:p})=>({registrationId:i,clientId:e,declaration:structuredClone(c),handlerDeclaration:structuredClone(f),contract:d,handler:p,active:0}));this.actionProviders.set(i,{id:i,clientId:e,declaration:structuredClone(c),handlers:l}),n.providers.add(i);let u=!0;return{declaration:structuredClone(c),dispose:()=>{u&&(u=!1,this.removeActionProvider(i))}}}async invokeAction(e,t){let n=this.requireClient(e);mh(t.contract);let i=t.request_id??this.idFactory("req");this.cleanCompletedActions(),ph(t.input,"invalid_action_input",`Action ${t.contract.id} input`);let s={kind:"mdbase.action.request",profile_version:"0.1",request_id:i,contract:structuredClone(t.contract),caller:structuredClone(n.identity),created_at:t.created_at??this.now().toISOString(),...t.correlation_id===void 0?{}:{correlation_id:t.correlation_id},...t.causation_id===void 0?{}:{causation_id:t.causation_id},...t.subject===void 0?{}:{subject:t.subject},...t.idempotency_key===void 0?{}:{idempotency_key:t.idempotency_key},...t.deadline===void 0?{}:{deadline:t.deadline},...t.requested_provider===void 0?{}:{requested_provider:structuredClone(t.requested_provider)},input:structuredClone(t.input)};Sn(this.actionRequestValidator,s,"request_rejected","Action request"),hh(this.transport,s);let o=await this.acquireAdmission(i);try{let a=await ns(mN(s)),c=this.activeActions.get(i);if(c){if(S0(e,i,a,c),c.handler.handlerDeclaration.idempotency?.mode!=="request")throw new O("request_rejected",`Action request ${i} is already active without deduplication.`);return structuredClone(await c.promise)}let l=this.completedActions.get(i);if(l){if(S0(e,i,a,l),!l.reusable)throw new O("request_rejected",`Action request ${i} was already completed without deduplication.`);return structuredClone(l.outcome)}if(s.deadline&&new Date(s.deadline).getTime()<=this.now().getTime())throw new O("deadline_exceeded",`Action request ${i} passed its deadline before admission.`);if(s.deadline&&!this.transport.deadlines)throw new O("unsupported_transport_capability","The active transport cannot enforce action deadlines.");let u=this.resolveActionCandidates(s.contract,s.requested_provider);u.length===0&&this.throwResolutionFailure(s.contract,s.requested_provider);let d=[];for(let E of u)await this.isAuthorized({operation:"invoke_action",principal:n.identity,contract:E.contract.reference,provider:E.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}})&&d.push(E);if(d.length===0)throw new O("unauthorized",`No authorized provider can execute ${s.contract.id}.`);if(d.length>1)throw new O("ambiguous_provider",`Action ${s.contract.id} has ${d.length} eligible providers; select one explicitly.`);let f=d[0];if(f.handlerDeclaration.max_concurrency!==void 0&&f.active>=f.handlerDeclaration.max_concurrency)throw new O("request_rejected",`Provider ${f.declaration.provider.implementation} is at capacity.`);if((f.contract.artifact.behavior?.idempotency??"none")==="required"&&!s.idempotency_key)throw new O("request_rejected",`${f.contract.reference.id} requires an idempotency key.`);Cc(f.contract.inputValidator,s.input,"invalid_action_input",`Action ${f.contract.reference.id} input`);let h={operation:"invoke_action",principal:n.identity,contract:f.contract.reference,provider:f.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}},m=await this.options.authorizationContext?.(h),y={kind:"mdbase.action.invocation",profile_version:"0.1",invocation_id:this.idFactory("inv"),attempt_id:this.idFactory("attempt"),request_id:i,contract:structuredClone(f.contract.reference),caller:structuredClone(n.identity),provider:structuredClone(f.declaration.provider),provider_declaration_digest:f.declaration.declaration_digest,handler_id:f.handlerDeclaration.handler_id,admitted_at:this.now().toISOString(),...s.correlation_id===void 0?{}:{correlation_id:s.correlation_id},...s.causation_id===void 0?{}:{causation_id:s.causation_id},...s.subject===void 0?{}:{subject:s.subject},...s.idempotency_key===void 0?{}:{idempotency_key:s.idempotency_key},...s.deadline===void 0?{}:{deadline:s.deadline},...m===void 0?{}:{authorization_context:m},input:structuredClone(s.input)};Sn(this.actionInvocationValidator,y,"request_rejected","Action invocation"),await this.options.onInvocation?.(structuredClone(y));let g=new AbortController,b;if(y.deadline){let E=Math.max(0,new Date(y.deadline).getTime()-this.now().getTime());b=setTimeout(()=>g.abort(new O("deadline_exceeded",`Action request ${i} exceeded its deadline.`)),E)}f.active+=1;let v=this.executeAction(f,y,g).finally(()=>{b!==void 0&&clearTimeout(b),f.active=Math.max(0,f.active-1),this.activeActions.delete(i)});this.activeActions.set(i,{clientId:e,requestId:i,requestDigest:a,handler:f,invocation:y,controller:g,promise:v}),o();let S=await v,_=f.handlerDeclaration.idempotency?.retention_seconds??300;return this.completedActions.set(i,{clientId:e,requestDigest:a,outcome:structuredClone(S),reusable:f.handlerDeclaration.idempotency?.mode==="request",expiresAt:this.now().getTime()+_*1e3}),x0(this.completedActions,this.completedRequestLimit),structuredClone(S)}finally{o()}}async executeAction(e,t,n){try{let i=await e.handler(structuredClone(t.input),{invocation:structuredClone(t),signal:n.signal});if(n.signal.aborted){let o=n.signal.reason;return o instanceof O&&o.code==="deadline_exceeded"?this.failureOutcome(t,"failed",o.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}ph(i,"invalid_action_output",`Action ${e.contract.reference.id} output`),Cc(e.contract.outputValidator,i,"invalid_action_output",`Action ${e.contract.reference.id} output`);let s={kind:"mdbase.action.outcome",profile_version:"0.1",outcome_id:this.idFactory("outcome"),request_id:t.request_id,invocation_id:t.invocation_id,attempt_id:t.attempt_id,contract:structuredClone(t.contract),provider:structuredClone(t.provider),provider_declaration_digest:t.provider_declaration_digest,status:"succeeded",completed_at:this.now().toISOString(),output:structuredClone(i)};return Sn(this.actionOutcomeValidator,s,"invalid_action_output","Action outcome"),hh(this.transport,s),s}catch(i){if(i instanceof $o)return e.contract.errorValidator&&!e.contract.errorValidator(i.error.details??{})?this.failureOutcome(t,"failed",{code:"handler_failure",message:`Provider returned invalid declared error details: ${wn(e.contract.errorValidator.errors)}`}):this.failureOutcome(t,i.status,i.error);if(i instanceof O)return this.failureOutcome(t,i.code==="cancelled"?"cancelled":i.code==="outcome_indeterminate"?"outcome_indeterminate":"failed",i.toPortableError());if(n.signal.aborted||bN(i)){let s=n.signal.reason;return s instanceof O&&s.code==="deadline_exceeded"?this.failureOutcome(t,"failed",s.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}return this.report({severity:"error",code:"action_handler_failed",message:`Provider ${t.provider.implementation} failed ${t.contract.id}.`,principal:t.provider,contract:t.contract,cause:i}),this.failureOutcome(t,"failed",{code:"handler_failure",message:"The selected provider failed while executing the action."})}}failureOutcome(e,t,n){let i={kind:"mdbase.action.outcome",profile_version:"0.1",outcome_id:this.idFactory("outcome"),request_id:e.request_id,invocation_id:e.invocation_id,attempt_id:e.attempt_id,contract:structuredClone(e.contract),provider:structuredClone(e.provider),provider_declaration_digest:e.provider_declaration_digest,status:t,completed_at:this.now().toISOString(),error:structuredClone(n)};return Sn(this.actionOutcomeValidator,i,"invalid_action_output","Action outcome"),i}async cancelAction(e,t,n){let i=this.requireClient(e),s=this.admissionLocks.get(t);s&&await s;let o=this.activeActions.get(t);if(!o){let a=this.completedActions.get(t);if(a&&a.clientId!==e)throw new O("unauthorized",`Action request ${t} belongs to another caller.`);return a?structuredClone(a.outcome):null}if(o.clientId!==e)throw new O("unauthorized",`Action request ${t} belongs to another caller.`);if(await this.assertAuthorized({operation:"cancel_action",principal:i.identity,contract:o.invocation.contract,provider:o.invocation.provider,...o.invocation.subject===void 0?{}:{subject:o.invocation.subject}}),!this.transport.cancellation)throw new O("unsupported_transport_capability","The active transport cannot deliver cancellation.");if(o.handler.handlerDeclaration.cancellation!=="cooperative")throw new O("cancellation_unsupported",`Provider ${o.invocation.provider.implementation} does not support cancellation.`);return o.controller.abort(new O("cancelled",n?.trim()||`Action request ${t} was cancelled.`)),structuredClone(await o.promise)}resolveActionCandidates(e,t){let n=[...this.actionProviders.values()].flatMap(({handlers:s})=>s).filter(({contract:s,declaration:o})=>Vc(e,s.reference)&&yN(t,o.provider)),i=(0,zr.maxSatisfying)([...new Set(n.map(({contract:s})=>s.reference.version))],e.version,{includePrerelease:!0});return i?n.filter(({contract:s})=>s.reference.version===i).sort((s,o)=>s.declaration.provider.application.localeCompare(o.declaration.provider.application)||s.declaration.provider.implementation.localeCompare(o.declaration.provider.implementation)||(s.declaration.provider.instance_id??"").localeCompare(o.declaration.provider.instance_id??"")||s.handlerDeclaration.handler_id.localeCompare(o.handlerDeclaration.handler_id)):[]}throwResolutionFailure(e,t){let n=[...this.contracts.values()].filter(i=>i.artifact.contract_type==="action"&&i.reference.id===e.id);throw n.length===0?new O("unknown_contract",`Action contract ${e.id} is unknown.`):n.some(({reference:i})=>Vc(e,i))?t?new O("requested_provider_unavailable",`The requested provider is unavailable for ${e.id}.`):new O("no_provider",`No provider is registered for ${e.id}.`):new O("unsupported_contract_version",`No ${e.id} artifact satisfies ${e.version}.`)}async prepareEventContract(e){if(this.assertContractArtifact(e),e.contract_type!=="event")throw new O("unknown_contract",`${e.id} is not an event contract.`);let t={id:e.id,version:e.version,digest:await Pc(e)};this.assertNoContractConflict(t);let n=Aw(this.ajv,e);return{artifact:structuredClone(e),reference:t,dataValidator:n.data,...n.source===void 0?{}:{sourceValidator:n.source}}}async prepareActionContract(e){if(this.assertContractArtifact(e),e.contract_type!=="action")throw new O("unknown_contract",`${e.id} is not an action contract.`);let t={id:e.id,version:e.version,digest:await Pc(e)};this.assertNoContractConflict(t);let n=Pw(this.ajv,e);return{artifact:structuredClone(e),reference:t,inputValidator:n.input,...n.output===void 0?{}:{outputValidator:n.output},...n.error===void 0?{}:{errorValidator:n.error},...n.provider===void 0?{}:{providerValidator:n.provider}}}assertContractArtifact(e){if(Sn(this.contractValidator,e,"contract_digest_conflict",`Contract ${e.id||""}`),!(0,zr.valid)(e.version))throw new O("unsupported_contract_version",`${e.id} version must be exact SemVer.`)}assertNoContractConflict(e){let t=this.contracts.get(Uc(e));if(t&&t.reference.digest!==e.digest)throw new O("contract_digest_conflict",`Contract ${e.id} ${e.version} conflicts with the registered artifact.`)}commitContracts(e){let t=new Map;for(let n of e){let i=Uc(n.reference),s=t.get(i)??this.contracts.get(i);if(s&&s.reference.digest!==n.reference.digest)throw new O("contract_digest_conflict",`Contract ${n.reference.id} ${n.reference.version} conflicts within the registration.`);t.set(i,n)}for(let[n,i]of t)this.contracts.has(n)||this.contracts.set(n,i)}async disposeClient(e,t=!1){let n=this.clients.get(e);if(!(!n||n.disposed)){n.disposed=!0;for(let i of[...n.subscriptions])this.removeSubscription(i);for(let i of[...n.sources])this.removeEventSource(i);for(let i of[...n.providers])this.removeActionProvider(i);for(let i of[...this.activeActions.values()])i.clientId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new O("cancelled","The caller unloaded.")),i.handler.clientId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new O("cancelled","The provider unloaded."));this.clients.delete(e),t||this.assertActive()}}removeEventSource(e){let t=this.eventSources.get(e);t&&(this.eventSources.delete(e),this.clients.get(t.clientId)?.sources.delete(e))}removeActionProvider(e){let t=this.actionProviders.get(e);if(t){this.actionProviders.delete(e),this.clients.get(t.clientId)?.providers.delete(e);for(let n of this.activeActions.values())n.handler.registrationId===e&&n.handler.handlerDeclaration.cancellation==="cooperative"&&n.controller.abort(new O("cancelled","The provider unloaded."))}}removeSubscription(e){let t=this.subscriptions.get(e);t&&(this.subscriptions.delete(e),this.clients.get(t.clientId)?.subscriptions.delete(e))}requireClient(e){this.assertActive();let t=this.clients.get(e);if(!t||t.disposed)throw new O("transport_unavailable","Interop client is disposed.");return t}assertActive(){if(this.disposed)throw new O("transport_unavailable","Interop bridge is disposed.")}async assertAuthorized(e){if(!await this.isAuthorized(e))throw new O("unauthorized",`${e.operation} is not authorized.`)}async isAuthorized(e){try{return await this.authorize(structuredClone(e))}catch(t){return this.report({severity:"error",code:"authorization_failed",message:`Authorization failed for ${e.operation}.`,principal:e.principal,cause:t}),!1}}cleanCompletedActions(){let e=this.now().getTime();for(let[t,n]of this.completedActions)n.expiresAt<=e&&this.completedActions.delete(t)}async acquireAdmission(e){let t=this.admissionLocks.get(e)??Promise.resolve(),n,i=new Promise(a=>{n=a}),s=t.then(()=>i);this.admissionLocks.set(e,s),await t;let o=!1;return()=>{o||(o=!0,n(),this.admissionLocks.get(e)===s&&this.admissionLocks.delete(e))}}report(e){this.options.onDiagnostic?.(structuredClone(e))}};function Sn(r,e,t,n){if(!r(e))throw new O(t,`${n} is invalid: ${wn(r.errors)}`)}function fN(r){for(let[e,t]of Object.entries(r))if(t!==void 0&&(typeof t!="string"||t.length===0||!/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/u.test(t)))throw new O("request_rejected",`Implementation identity ${e} is invalid.`);if(!(0,zr.valid)(r.version))throw new O("request_rejected","Implementation identity version must be exact SemVer.")}function mh(r){if(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u.test(r.id))throw new O("unknown_contract",`Contract ID ${r.id} is invalid.`);if(!(0,zr.validRange)(r.version,{includePrerelease:!0}))throw new O("unsupported_contract_version",`Contract requirement ${r.version} is not a SemVer range.`);if(r.digest&&!/^sha256:[0-9a-f]{64}$/u.test(r.digest))throw new O("contract_digest_conflict","Contract digest is invalid.")}function w0(r,e){let t=r??{id:e.id,version:e.version,digest:e.digest};return mh(t),structuredClone(t)}function _0(r,e){if(!Vc(r,e))throw new O("unsupported_contract_version",`${e.id} ${e.version} does not satisfy its implementation requirement.`)}function Vc(r,e){return r.id===e.id&&(0,zr.satisfies)(e.version,r.version,{includePrerelease:!0})&&(!r.digest||r.digest===e.digest)}function Uc(r){return`${r.id}@${r.version}`}function $0(r){return`urn:mdbase:contract:${r.id}:${r.version}:${r.digest}`}function pN(r){return`urn:mdbase:app:${[r.application,r.implementation,...r.instance_id?[r.instance_id]:[]].map(encodeURIComponent).join(":")}`}function hN(r,e){if(r.type!==e.id||r.mdbasecontractversion!==e.version||r.mdbasecontractdigest!==e.digest||r.dataschema!==$0(e))throw new O("contract_digest_conflict","Event contract evidence is inconsistent.")}function mN(r){let{created_at:e,...t}=r;return t}function S0(r,e,t,n){if(n.clientId!==r)throw new O("unauthorized",`Action request ${e} belongs to another caller.`);if(n.requestDigest!==t)throw new O("request_rejected",`Action request ${e} was reused with different content.`)}function ph(r,e,t){let n=new Set,i=(s,o)=>{if(!(s===null||typeof s=="boolean"||typeof s=="string")){if(typeof s=="number"){if(Number.isFinite(s))return;throw new O(e,`${t}${o} must be a finite JSON number.`)}if(typeof s!="object")throw new O(e,`${t}${o} is not a JSON value.`);if(n.has(s))throw new O(e,`${t}${o} contains a cycle.`);if(n.add(s),Array.isArray(s))s.forEach((a,c)=>i(a,`${o}/${c}`));else{let a=Object.getPrototypeOf(s);if(a!==Object.prototype&&a!==null)throw new O(e,`${t}${o} must be a plain JSON object.`);for(let[c,l]of Object.entries(s))i(l,`${o}/${c}`)}n.delete(s)}};i(r,"")}function hh(r,e){if(r.max_payload_bytes===void 0)return;let t=JSON.stringify(e),n=new TextEncoder().encode(t).byteLength;if(n>r.max_payload_bytes)throw new O("unsupported_transport_capability",`The portable envelope is ${n} bytes; the active transport allows ${r.max_payload_bytes}.`)}function yN(r,e){return r?(r.application===void 0||r.application===e.application)&&(r.implementation===void 0||r.implementation===e.implementation)&&(r.instance_id===void 0||r.instance_id===e.instance_id):!0}function gN(r,e){if(e){if(e.delivery?.some(t=>!r.delivery.includes(t)))throw new O("unsupported_transport_capability","The active transport lacks a required delivery capability.");if(e.ordering?.some(t=>!r.ordering.includes(t)))throw new O("unsupported_transport_capability","The active transport lacks a required ordering capability.");for(let t of["cancellation","deadlines","provider_discovery","request_deduplication","cross_process_identity"])if(e[t]===!0&&r[t]!==!0)throw new O("unsupported_transport_capability",`The active transport lacks ${t}.`);if(e.max_payload_bytes!==void 0&&(r.max_payload_bytes===void 0||r.max_payload_bytese;){let t=r.keys().next().value;if(t===void 0)return;r.delete(t)}}function bN(r){return r instanceof Error&&r.name==="AbortError"}var Hc=class{constructor(e,t){this.app=e;this.profileVersion="0.1";this.bridge=new Mo({authorize:()=>t(),transport:{delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},onDiagnostic:n=>{(n.severity==="error"?console.error:console.warn)(`[mdbase/interop] ${n.code}: ${n.message}`,n.cause??"")}}),this.transport=this.bridge.describe().transport}connect(e){let t=e.manifest?.id,n=e.manifest?.version;if(!t||!n)throw new Error("Only a loaded Obsidian plugin with manifest identity can connect to mdbase interop.");let i=this.app.plugins;if(!i||i.getPlugin(t)!==e)throw new Error(`Obsidian plugin ${t} is not the active loaded instance.`);return this.bridge.connect({application:t,implementation:`${t}.obsidian`,version:n})}describe(){return this.bridge.describe()}dispose(){return this.bridge.dispose()}};Vt();var J=require("obsidian"),s$=Wn(wp(),1);var zc=Symbol.for("yaml.alias"),Kc=Symbol.for("yaml.document"),rr=Symbol.for("yaml.map"),yh=Symbol.for("yaml.pair"),Pt=Symbol.for("yaml.scalar"),Kr=Symbol.for("yaml.seq"),ot=Symbol.for("yaml.node.type"),nr=r=>!!r&&typeof r=="object"&&r[ot]===zc,kr=r=>!!r&&typeof r=="object"&&r[ot]===Kc,ir=r=>!!r&&typeof r=="object"&&r[ot]===rr,te=r=>!!r&&typeof r=="object"&&r[ot]===yh,W=r=>!!r&&typeof r=="object"&&r[ot]===Pt,sr=r=>!!r&&typeof r=="object"&&r[ot]===Kr;function ae(r){if(r&&typeof r=="object")switch(r[ot]){case rr:case Kr:return!0}return!1}function ne(r){if(r&&typeof r=="object")switch(r[ot]){case zc:case rr:case Pt:case Kr:return!0}return!1}var Wc=r=>(W(r)||ae(r))&&!!r.anchor;var vt=Symbol("break visit"),E0=Symbol("skip children"),Ar=Symbol("remove node");function Pr(r,e){let t=k0(e);kr(r)?os(null,r.contents,t,Object.freeze([r]))===Ar&&(r.contents=null):os(null,r,t,Object.freeze([]))}Pr.BREAK=vt;Pr.SKIP=E0;Pr.REMOVE=Ar;function os(r,e,t,n){let i=A0(r,e,t,n);if(ne(i)||te(i))return P0(r,n,i),os(r,i,t,n);if(typeof i!="symbol"){if(ae(e)){n=Object.freeze(n.concat(e));for(let s=0;sr.replace(/[!,[\]{}]/g,e=>vN[e]),Cr=class r{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},r.defaultYaml,e),this.tags=Object.assign({},r.defaultTags,t)}clone(){let e=new r(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new r(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:r.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},r.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:r.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},r.defaultTags),this.atNextDocument=!1);let n=e.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[s,o]=n;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[s]=n;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return t(6,`Unsupported YAML version ${s}`,o),!1}}default:return t(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}let[,n,i]=e.match(/^(.*!)([^!]*)$/s);i||t(`The ${e} tag has no suffix`);let s=this.tags[n];if(s)try{return s+decodeURIComponent(i)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+wN(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),i;if(e&&n.length>0&&ne(e.contents)){let s={};Pr(e.contents,(o,a)=>{ne(a)&&a.tag&&(s[a.tag]=!0)}),i=Object.keys(s)}else i=[];for(let[s,o]of n)s==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(o)))&&t.push(`%TAG ${s} ${o}`);return t.join(` +`)}};Cr.defaultYaml={explicit:!1,version:"1.2"};Cr.defaultTags={"!!":"tag:yaml.org,2002:"};function Jc(r){if(/[\x00-\x19\s,[\]{}]/.test(r)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(r)}`;throw new Error(t)}return!0}function gh(r){let e=new Set;return Pr(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function bh(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function C0(r,e){let t=[],n=new Map,i=null;return{onAnchor:s=>{t.push(s),i??(i=gh(r));let o=bh(e,i);return i.add(o),o},setAnchors:()=>{for(let s of t){let o=n.get(s);if(typeof o=="object"&&o.anchor&&(W(o.node)||ae(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:n}}function xn(r,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,s=n.length;iTe(n,String(i),t));if(r&&typeof r.toJSON=="function"){if(!t||!Wc(r))return r.toJSON(e,t);let n={aliasCount:0,count:1,res:void 0};t.anchors.set(r,n),t.onCreate=s=>{n.res=s,delete t.onCreate};let i=r.toJSON(e,t);return t.onCreate&&t.onCreate(i),i}return typeof r=="bigint"&&!t?.keep?Number(r):r}var $n=class{constructor(e){Object.defineProperty(this,ot,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:i,reviver:s}={}){if(!kr(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},a=Te(this,"",o);if(typeof i=="function")for(let{count:c,res:l}of o.anchors.values())i(l,c);return typeof s=="function"?xn(s,{"":a},"",a):a}};var Wr=class extends $n{constructor(e){super(zc),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if(t?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],Pr(e,{Node:(s,o)=>{(nr(o)||Wc(o))&&n.push(o)}}),t&&(t.aliasResolveCache=n));let i;for(let s of n){if(s===this)break;s.anchor===this.source&&(i=s)}if(i&&t){let{anchors:s,doc:o,maxAliasCount:a}=t,c=s.get(i);if(c||(Te(i,null,t),c=s.get(i)),c?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(a>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=Yc(o,i,s)),c.count*c.aliasCount>a)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}}return i}toJSON(e,t){if(!t)return{source:this.source};let n=this.resolve(t.doc,t);if(!n){let i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(i)}return t.anchors.get(n).res}toString(e,t,n){let i=`*${this.source}`;if(e){if(Jc(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(e.implicitKey)return`${i} `}return i}};function Yc(r,e,t){if(nr(e)){let n=e.resolve(r),i=t&&n&&t.get(n);return i?i.count*i.aliasCount:0}else if(ae(e)){let n=0;for(let i of e.items){let s=Yc(r,i,t);s>n&&(n=s)}return n}else if(te(e)){let n=Yc(r,e.key,t),i=Yc(r,e.value,t);return Math.max(n,i)}return 1}var Xc=r=>!r||typeof r!="function"&&typeof r!="object",F=class extends $n{constructor(e){super(Pt),this.value=e}toJSON(e,t){return t?.keep?this.value:Te(this.value,e,t)}toString(){return String(this.value)}};F.BLOCK_FOLDED="BLOCK_FOLDED";F.BLOCK_LITERAL="BLOCK_LITERAL";F.PLAIN="PLAIN";F.QUOTE_DOUBLE="QUOTE_DOUBLE";F.QUOTE_SINGLE="QUOTE_SINGLE";var _N="tag:yaml.org,2002:";function SN(r,e,t){if(e){let n=t.filter(s=>s.tag===e),i=n.find(s=>!s.format)??n[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return t.find(n=>n.identify?.(r)&&!n.format)}function Gr(r,e,t){if(kr(r)&&(r=r.contents),ne(r))return r;if(te(r)){let d=t.schema[rr].createNode?.(t.schema,null,t);return d.items.push(r),d}(r instanceof String||r instanceof Number||r instanceof Boolean||typeof BigInt<"u"&&r instanceof BigInt)&&(r=r.valueOf());let{aliasDuplicateObjects:n,onAnchor:i,onTagObj:s,schema:o,sourceObjects:a}=t,c;if(n&&r&&typeof r=="object"){if(c=a.get(r),c)return c.anchor??(c.anchor=i(r)),new Wr(c.anchor);c={anchor:null,node:null},a.set(r,c)}e?.startsWith("!!")&&(e=_N+e.slice(2));let l=SN(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let d=new F(r);return c&&(c.node=d),d}l=r instanceof Map?o[rr]:Symbol.iterator in Object(r)?o[Kr]:o[rr]}s&&(s(l),delete t.onTagObj);let u=l?.createNode?l.createNode(t.schema,r,t):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(t.schema,r,t):new F(r);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}function Ro(r,e,t){let n=t;for(let i=e.length-1;i>=0;--i){let s=e[i];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=n,n=o}else n=new Map([[s,n]])}return Gr(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:r,sourceObjects:new Map})}var ls=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,cs=class extends $n{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(n=>ne(n)||te(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(ls(e))this.add(t);else{let[n,...i]=e,s=this.get(n,!0);if(ae(s))s.addIn(i,t);else if(s===void 0&&this.schema)this.set(n,Ro(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let i=this.get(t,!0);if(ae(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...i]=e,s=this.get(n,!0);return i.length===0?!t&&W(s)?s.value:s:ae(s)?s.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!te(t))return!1;let n=t.value;return n==null||e&&W(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let i=this.get(t,!0);return ae(i)?i.hasIn(n):!1}setIn(e,t){let[n,...i]=e;if(i.length===0)this.set(n,t);else{let s=this.get(n,!0);if(ae(s))s.setIn(i,t);else if(s===void 0&&this.schema)this.set(n,Ro(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};var M0=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function Kt(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var Mr=(r,e,t)=>r.endsWith(` +`)?Kt(t,e):t.includes(` `)?` -`+Vt(t,e):(r.endsWith(" ")?"":" ")+t;var bh="flow",Qc="block",Io="quoted";function Oo(r,e,t="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return r;ii-Math.max(2,s)?l.push(0):d=i-n);let f,p,h=!1,m=-1,y=-1,g=-1;t===Qc&&(m=R0(r,m,e.length),m!==-1&&(d=m+c));for(let v;v=r[m+=1];){if(t===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===` +`+Kt(t,e):(r.endsWith(" ")?"":" ")+t;var vh="flow",Qc="block",To="quoted";function Io(r,e,t="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return r;ii-Math.max(2,s)?l.push(0):d=i-n);let f,p,h=!1,m=-1,y=-1,g=-1;t===Qc&&(m=R0(r,m,e.length),m!==-1&&(d=m+c));for(let v;v=r[m+=1];){if(t===To&&v==="\\"){switch(y=m,r[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}g=m}if(v===` `)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=d)if(f)l.push(f),d=f+c,f=void 0;else if(t===To){for(;p===" "||p===" ";)p=v,v=r[m+=1],h=!0;let S=m>g+1?m-2:y-1;if(u[S])return r;l.push(S),u[S]=!0,d=S+c,f=void 0}else h=!0}p=v}if(h&&a&&a(),l.length===0)return r;o&&o();let b=r.slice(0,l[0]);for(let v=0;v({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),tl=r=>/^(%|---|\.\.\.)/m.test(r);function 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({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),tl=r=>/^(%|---|\.\.\.)/m.test(r);function xN(r,e,t){if(!e||e<0)return!1;let n=e-t,i=r.length;if(i<=n)return!1;for(let s=0,o=0;sn)return!0;if(o=s+1,i-o<=n)return!1}return!0}function Oo(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,i=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(tl(r)?" ":""),o="",a=0;for(let c=0,l=t[c];l;l=t[++c])if(l===" "&&t[c+1]==="\\"&&t[c+2]==="n"&&(o+=t.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(t[c+1]){case"u":{o+=t.slice(a,c);let u=t.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||t[c+2]==='"'||t.length `;let d,f;for(f=t.length;f>0;--f){let _=t[f-1];if(_!==` `&&_!==" "&&_!==" ")break}let p=t.substring(f),h=p.indexOf(` `);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} +$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,A=el(n,!0);o!=="folded"&&e!==F.BLOCK_FOLDED&&(A.onOverflow=()=>{E=!0});let x=Io(`${b}${_}${p}`,l,Qc,A);if(!E)return`>${S} ${l}${x}`}return t=t.replace(/\n+/g,`$&${l}`),`|${S} -${l}${b}${t}${p}`}function _N(r,e,t,n){let{type:i,value:s}=r,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:u}=e;if(a&&s.includes(` -`)||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):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===` +${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 ds(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||u||!s.includes(` +`)?ds(s,e):Zc(r,e,t,n);if(!a&&!u&&i!==F.PLAIN&&s.includes(` +`))return Zc(r,e,t,n);if(tl(s)){if(c==="")return e.forceBlockIndent=!0,Zc(r,e,t,n);if(a&&c===l)return ds(s,e)}let d=s.replace(/\n+/g,`$& +${c}`);if(o){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(d),{compat:p,tags:h}=e.doc.schema;if(h.some(f)||p?.some(f))return ds(s,e)}return a?d:Io(d,c,vh,el(e,!1))}function li(r,e,t,n){let{implicitKey:i,inFlow:s}=e,o=typeof r.value=="string"?r:Object.assign({},r,{value:String(r.value)}),{type:a}=r;a!==F.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=F.QUOTE_DOUBLE);let c=u=>{switch(u){case F.BLOCK_FOLDED:case F.BLOCK_LITERAL:return i||s?ds(o.value,e):Zc(o,e,t,n);case F.QUOTE_DOUBLE:return Oo(o.value,e);case F.QUOTE_SINGLE:return wh(o.value,e);case F.PLAIN:return $N(o,e,t,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:u,defaultStringType:d}=e.options,f=i&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}function rl(r,e){let t=Object.assign({blockQuote:!0,commentString:M0,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},r.schema.toStringOptions,e),n;switch(t.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:r,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:n,options:t}}function EN(r,e){if(e.tag){let i=r.filter(s=>s.tag===e.tag);if(i.length>0)return i.find(s=>s.format===e.format)??i[0]}let t,n;if(W(e)){n=e.value;let i=r.filter(s=>s.identify?.(n));if(i.length>1){let s=i.filter(o=>o.test);s.length>0&&(i=s)}t=i.find(s=>s.format===e.format)??i.find(s=>!s.format)}else n=e,t=r.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!t){let i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return t}function kN(r,e,{anchors:t,doc:n}){if(!n.directives)return"";let i=[],s=(W(r)||ae(r))&&r.anchor;s&&Jc(s)&&(t.add(s),i.push(`&${s}`));let o=r.tag??(e.default?null:e.tag);return o&&i.push(n.directives.tagString(o)),i.join(" ")}function Jr(r,e,t,n){if(te(r))return r.toString(e,t,n);if(nr(r)){if(e.doc.directives)return r.toString(e);if(e.resolvedAliases?.has(r))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(r):e.resolvedAliases=new Set([r]),r=r.resolve(e.doc)}let i,s=ne(r)?r:e.doc.createNode(r,{onTagObj:c=>i=c});i??(i=EN(e.doc.schema.tags,s));let o=kN(s,i,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof i.stringify=="function"?i.stringify(s,e,t,n):W(s)?li(s,e,t,n):s.toString(e,t,n);return o?W(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} +${e.indent}${a}`:a}function T0({key:r,value:e},t,n,i){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=t,f=ne(r)&&r.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(ae(r)||!ne(r)&&typeof r=="object"){let A="With simple keys, collection cannot be used as a key value";throw new Error(A)}}let p=!d&&(!r||f&&e==null&&!t.inFlow||ae(r)||(W(r)?r.type===F.BLOCK_FOLDED||r.type===F.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(d||!s),indent:a+c});let h=!1,m=!1,y=Jr(r,t,()=>h=!0,()=>m=!0);if(!p&&!t.inFlow&&y.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(t.inFlow){if(s||e==null)return h&&n&&n(),y===""?"?":p?`? ${y}`:y}else if(s&&!d||e==null&&p)return y=`? ${y}`,f&&!h?y+=Mr(y,t.indent,l(f)):m&&i&&i(),y;h&&(f=null),p?(f&&(y+=Mr(y,t.indent,l(f))),y=`? ${y} +${a}:`):(y=`${y}:`,f&&(y+=Mr(y,t.indent,l(f))));let g,b,v;ne(e)?(g=!!e.spaceBefore,b=e.commentBefore,v=e.comment):(g=!1,b=null,v=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!f&&W(e)&&(t.indentAtStart=y.length+1),m=!1,!u&&c.length>=2&&!t.inFlow&&!p&&sr(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let S=!1,_=Jr(e,t,()=>S=!0,()=>m=!0),E=" ";if(f||g||b){if(E=g?` +`:"",b){let A=l(b);E+=` +${Kt(A,t.indent)}`}_===""&&!t.inFlow?E===` `&&v&&(E=` `):E+=` -${t.indent}`}else if(!p&&ae(e)){let k=_[0],x=_.indexOf(` -`),T=x!==-1,$=t.inFlow??e.flow??e.items.length===0;if(T||!$){let q=!1;if(T&&(k==="&"||k==="!")){let C=_.indexOf(" ");k==="&"&&C!==-1&&Cr===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;hr===il||typeof r=="symbol"&&r.description===il,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new F(Symbol(il)),{addToJSMap:xh}),stringify:()=>il},I0=(r,e)=>(or.identify(e)||W(e)&&(!e.type||e.type===F.PLAIN)&&or.identify(e.value))&&r?.doc.schema.tags.some(t=>t.tag===or.tag&&t.default);function xh(r,e,t){let n=O0(r,t);if(sr(n))for(let i of n.items)Sh(r,e,i);else if(Array.isArray(n))for(let i of n)Sh(r,e,i);else Sh(r,e,n)}function Sh(r,e,t){let n=O0(r,t);if(!ir(n))throw new Error("Merge sources must be maps or map aliases");let i=n.toJSON(null,r,Map);for(let[s,o]of i)e instanceof Map?e.has(s)||e.set(s,o):e instanceof Set?e.add(s):Object.prototype.hasOwnProperty.call(e,s)||Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function O0(r,e){return r&&nr(e)?e.resolve(r.doc,r):e}function sl(r,e,{key:t,value:n}){if(ne(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(I0(r,t))xh(r,e,n);else{let i=Te(t,"",r);if(e instanceof Map)e.set(i,Te(n,i,r));else if(e instanceof Set)e.add(i);else{let s=AN(t,i,r),o=Te(n,s,r);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function AN(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(ne(r)&&t?.doc){let n=rl(t.doc,{});n.anchors=new Set;for(let s of t.anchors.keys())n.anchors.add(s.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=r.toString(n);if(!t.mapKeyWarned){let s=JSON.stringify(i);s.length>40&&(s=s.substring(0,36)+'..."'),nl(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return i}return JSON.stringify(e)}function us(r,e,t){let n=Gr(r,void 0,t),i=Gr(e,void 0,t);return new _e(n,i)}var _e=class r{constructor(e,t=null){Object.defineProperty(this,ot,{value:yh}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return ne(t)&&(t=t.clone(e)),ne(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return sl(t,n,this)}toString(e,t,n){return e?.doc?T0(this,e,t,n):JSON.stringify(this)}};function al(r,e,t){return(e.inFlow??r.flow?CN:PN)(r,e,t)}function PN({comment:r,items:e},t,{blockItemPrefix:n,flowChars:i,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=t,u=Object.assign({},t,{indent:s,type:null}),d=!1,f=[];for(let h=0;hy=null,()=>d=!0);y&&(g+=Mr(g,s,l(y))),d&&y&&(d=!1),f.push(n+g)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let h=1;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?` +`+Kt(l(r),c),a&&a()):d&&o&&o(),p}function CN({items:r},e,{flowChars:t,itemIndent:n}){let{indent:i,indentStep:s,flowCollectionPadding:o,options:{commentString:a}}=e;n+=s;let c=Object.assign({},e,{indent:n,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let h=0;hy=null);l||(l=d.length>u||g.includes(` +`)),h0&&(l||(l=d.reduce((b,v)=>b+v.length+2,2)+(g.length+2)>e.options.lineWidth)),l&&(g+=",")),y&&(g+=Mr(g,n,a(y))),d.push(g),u=d.length}let{start:f,end:p}=t;if(d.length===0)return f+p;if(!l){let h=d.reduce((m,y)=>m+y.length+2,2);l=e.options.lineWidth>0&&h>e.options.lineWidth}if(l){let h=f;for(let m of d)h+=m?` ${s}${i}${m}`:` `;return`${h} -${i}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function ol({indent:r,options:{commentString:e}},t,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let s=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}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function ol({indent:r,options:{commentString:e}},t,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let s=Kt(e(n),r);t.push(s.trimStart())}}function En(r,e){let t=W(e)?e.value:e;for(let n of r)if(te(n)&&(n.key===e||n.key===t||W(n.key)&&n.key.value===t))return n}var Ee=class extends cs{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(rr,e),this.items=[]}static from(e,t,n){let{keepUndefined:i,replacer:s}=n,o=new this(e),a=(c,l)=>{if(typeof s=="function")l=s.call(t,c,l);else if(Array.isArray(s)&&!s.includes(c))return;(l!==void 0||i)&&o.items.push(us(c,l,n))};if(t instanceof Map)for(let[c,l]of t)a(c,l);else if(t&&typeof t=="object")for(let c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){let n;te(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new _e(e,e?.value):n=new _e(e.key,e.value);let i=En(this.items,n.key),s=this.schema?.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);W(i.value)&&Xc(n.value)?i.value.value=n.value:i.value=n.value}else if(s){let o=this.items.findIndex(a=>s(n,a)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){let t=En(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let i=En(this.items,e)?.value;return(!t&&W(i)?i.value:i)??void 0}has(e){return!!En(this.items,e)}set(e,t){this.add(new _e(e,t),!0)}toJSON(e,t,n){let i=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(i);for(let s of this.items)sl(t,i,s);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(let i of this.items)if(!te(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),al(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};var ar={collection:"map",default:!0,nodeClass:Ee,tag:"tag:yaml.org,2002:map",resolve(r,e){return ir(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>Ee.from(r,e,t)};var Je=class extends cs{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Kr,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=cl(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=cl(e);if(typeof n!="number")return;let i=this.items[n];return!t&&W(i)?i.value:i}has(e){let t=cl(e);return typeof t=="number"&&t=0?e:null}var cr={collection:"seq",default:!0,nodeClass:Je,tag:"tag:yaml.org,2002:seq",resolve(r,e){return sr(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>Je.from(r,e,t)};var kn={identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify(r,e,t,n){return e=Object.assign({actualString:!0},e),li(r,e,t,n)}};var di={identify:r=>r==null,createNode:()=>new F(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new F(null),stringify:({source:r},e)=>typeof r=="string"&&di.test.test(r)?r:e.options.nullStr};var Do={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new F(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&Do.test.test(r)){let n=r[0]==="t"||r[0]==="T";if(e===n)return r}return e?t.options.trueStr:t.options.falseStr}};function Ye({format:r,minFractionDigits:e,tag:t,value:n}){if(typeof n=="bigint")return String(n);let i=typeof n=="number"?n:Number(n);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let s=Object.is(n,-0)?"-0":JSON.stringify(n);if(!r&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let a=e-(s.length-o-1);for(;a-- >0;)s+="0"}return s}var ll={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ye},dl={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():Ye(r)}},ul={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(r){let e=new F(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:Ye};var fl=r=>typeof r=="bigint"||Number.isInteger(r),$h=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function D0(r,e,t){let{value:n}=r;return fl(n)&&n>=0?t+n.toString(e):Ye(r)}var pl={identify:r=>fl(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>$h(r,2,8,t),stringify:r=>D0(r,8,"0o")},hl={identify:fl,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>$h(r,0,10,t),stringify:Ye},ml={identify:r=>fl(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>$h(r,2,16,t),stringify:r=>D0(r,16,"0x")};var N0=[ar,cr,kn,di,Do,pl,hl,ml,ll,dl,ul];function L0(r){return typeof r=="bigint"||Number.isInteger(r)}var yl=({value:r})=>JSON.stringify(r),MN=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:yl},{identify:r=>r==null,createNode:()=>new F(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:yl},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:yl},{identify:L0,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(r,e,{intAsBigInt:t})=>t?BigInt(r):parseInt(r,10),stringify:({value:r})=>L0(r)?r.toString():JSON.stringify(r)},{identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:r=>parseFloat(r),stringify:yl}],RN={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},F0=[ar,cr].concat(MN,RN);var No={identify:r=>r instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(r,e){if(typeof atob=="function"){let t=atob(r.replace(/[\n\r]/g,"")),n=new Uint8Array(t.length);for(let i=0;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 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(` +${s.comment}`:n.comment}n=i}r.items[t]=te(n)?n:new _e(n)}}else e("Expected a sequence for this tag");return r}function kh(r,e,t){let{replacer:n}=t,i=new Je(r);i.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;i.items.push(us(a,c,t))}return i}var Lo={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Eh,createNode:kh};var fs=class r extends Je{constructor(){super(),this.add=Ee.prototype.add.bind(this),this.delete=Ee.prototype.delete.bind(this),this.get=Ee.prototype.get.bind(this),this.has=Ee.prototype.has.bind(this),this.set=Ee.prototype.set.bind(this),this.tag=r.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let i of this.items){let s,o;if(te(i)?(s=Te(i.key,"",t),o=Te(i.value,s,t)):s=Te(i,"",t),n.has(s))throw new Error("Ordered maps must not include duplicate keys");n.set(s,o)}return n}static from(e,t,n){let i=kh(e,t,n),s=new this;return s.items=i.items,s}};fs.tag="tag:yaml.org,2002:omap";var Fo={collection:"seq",identify:r=>r instanceof Map,nodeClass:fs,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Eh(r,e),n=[];for(let{key:i}of t.items)W(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new fs,t)},createNode:(r,e,t)=>fs.from(r,e,t)};function j0({value:r,source:e},t){return e&&(r?Ah:Ph).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Ah={identify:r=>r===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new F(!0),stringify:j0},Ph={identify:r=>r===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new F(!1),stringify:j0};var q0={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ye},B0={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r.replace(/_/g,"")),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():Ye(r)}},U0={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(r){let e=new F(parseFloat(r.replace(/_/g,""))),t=r.indexOf(".");if(t!==-1){let n=r.substring(t+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:Ye};var jo=r=>typeof r=="bigint"||Number.isInteger(r);function gl(r,e,t,{intAsBigInt:n}){let i=r[0];if((i==="-"||i==="+")&&(e+=1),r=r.substring(e).replace(/_/g,""),n){switch(t){case 2:r=`0b${r}`;break;case 8:r=`0o${r}`;break;case 16:r=`0x${r}`;break}let o=BigInt(r);return i==="-"?BigInt(-1)*o:o}let s=parseInt(r,t);return i==="-"?-1*s:s}function Ch(r,e,t){let{value:n}=r;if(jo(n)){let i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return Ye(r)}var V0={identify:jo,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>gl(r,2,2,t),stringify:r=>Ch(r,2,"0b")},H0={identify:jo,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>gl(r,1,8,t),stringify:r=>Ch(r,8,"0")},z0={identify:jo,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>gl(r,0,10,t),stringify:Ye},K0={identify:jo,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>gl(r,2,16,t),stringify:r=>Ch(r,16,"0x")};var ps=class r extends Ee{constructor(e){super(e),this.tag=r.tag}add(e){let t;te(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new _e(e.key,null):t=new _e(e,null),En(this.items,t.key)||this.items.push(t)}get(e,t){let n=En(this.items,e);return!t&&te(n)?W(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=En(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new _e(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){let{replacer:i}=n,s=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof i=="function"&&(o=i.call(t,o,o)),s.items.push(us(o,null,n));return s}};ps.tag="tag:yaml.org,2002:set";var qo={collection:"map",identify:r=>r instanceof Set,nodeClass:ps,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>ps.from(r,e,t),resolve(r,e){if(ir(r)){if(r.hasAllNullValues(!0))return Object.assign(new ps,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};function Mh(r,e){let t=r[0],n=t==="-"||t==="+"?r.substring(1):r,i=o=>e?BigInt(o):Number(o),s=n.replace(/_/g,"").split(":").reduce((o,a)=>o*i(60)+i(a),i(0));return t==="-"?i(-1)*s:s}function W0(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Ye(r);let n="";e<0&&(n="-",e*=t(-1));let i=t(60),s=[e%i];return e<60?s.unshift(0):(e=(e-s[0])/i,s.unshift(e%i),e>=60&&(e=(e-s[0])/i,s.unshift(e))),n+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var bl={identify:r=>typeof r=="bigint"||Number.isInteger(r),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(r,e,{intAsBigInt:t})=>Mh(r,t),stringify:W0},vl={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:r=>Mh(r,!1),stringify:W0},hs={identify:r=>r instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(r){let e=r.match(hs.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,n,i,s,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,n-1,i,s||0,o||0,a||0,c),u=e[8];if(u&&u!=="Z"){let d=Mh(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:r})=>r?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};var Rh=[ar,cr,kn,di,Ah,Ph,V0,H0,z0,K0,q0,B0,U0,No,or,Fo,Lo,qo,bl,vl,hs];var G0=new Map([["core",N0],["failsafe",[ar,cr,kn]],["json",F0],["yaml11",Rh],["yaml-1.1",Rh]]),J0={binary:No,bool:Do,float:ul,floatExp:dl,floatNaN:ll,floatTime:vl,int:hl,intHex:ml,intOct:pl,intTime:bl,map:ar,merge:or,null:di,omap:Fo,pairs:Lo,seq:cr,set:qo,timestamp:hs},Y0={"tag:yaml.org,2002:binary":No,"tag:yaml.org,2002:merge":or,"tag:yaml.org,2002:omap":Fo,"tag:yaml.org,2002:pairs":Lo,"tag:yaml.org,2002:set":qo,"tag:yaml.org,2002:timestamp":hs};function wl(r,e,t){let n=G0.get(e);if(n&&!r)return t&&!n.includes(or)?n.concat(or):n.slice();let i=n;if(!i)if(Array.isArray(r))i=[];else{let s=Array.from(G0.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(r))for(let s of r)i=i.concat(s);else typeof r=="function"&&(i=r(i.slice()));return t&&(i=i.concat(or)),i.reduce((s,o)=>{let a=typeof o=="string"?J0[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(J0).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}var TN=(r,e)=>r.keye.key?1:0,Bo=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?wl(e,"compat"):e?wl(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?Y0:{},this.tags=wl(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,rr,{value:ar}),Object.defineProperty(this,Pt,{value:kn}),Object.defineProperty(this,Kr,{value:cr}),this.sortMapEntries=typeof o=="function"?o:o===!0?TN:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function X0(r,e){let t=[],n=e.directives===!0;if(e.directives!==!1&&r.directives){let c=r.directives.toString(r);c?(t.push(c),n=!0):r.directives.docStart&&(n=!0)}n&&t.push("---");let i=rl(r,e),{commentString:s}=i.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=s(r.commentBefore);t.unshift(Kt(c,""))}let o=!1,a=null;if(r.contents){if(ne(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let u=s(r.contents.commentBefore);t.push(Kt(u,""))}i.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=Jr(r.contents,i,()=>a=null,c);a&&(l+=Mr(l,"",s(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(Jr(r.contents,i));if(r.directives?.docEnd)if(r.comment){let c=s(r.comment);c.includes(` +`)?(t.push("..."),t.push(Kt(c,""))):t.push(`... ${c}`)}else t.push("...");else{let c=r.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(Kt(s(c),"")))}return t.join(` `)+` -`}var 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 +`}var An=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ot,{value:Kc});let i=null;typeof t=="function"||Array.isArray(t)?i=t:n===void 0&&t&&(n=t,t=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=s;let{version:o}=s;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Cr({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let e=Object.create(r.prototype,{[ot]:{value:Kc}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=ne(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){ms(this.contents)&&this.contents.add(e)}addIn(e,t){ms(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=gh(this);e.anchor=!t||n.has(t)?bh(t||"a",n):t}return new Wr(e.anchor)}createNode(e,t,n){let i;if(typeof t=="function")e=t.call({"":e},"",e),i=t;else if(Array.isArray(t)){let y=b=>typeof b=="number"||b instanceof String||b instanceof Number,g=t.filter(y).map(String);g.length>0&&(t=t.concat(g)),i=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:u}=n??{},{onAnchor:d,setAnchors:f,sourceObjects:p}=C0(this,o||"a"),h={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:p},m=Gr(e,u,h);return a&&ae(m)&&(m.flow=!0),f(),m}createPair(e,t,n={}){let i=this.createNode(e,null,n),s=this.createNode(t,null,n);return new _e(i,s)}delete(e){return ms(this.contents)?this.contents.delete(e):!1}deleteIn(e){return ls(e)?this.contents==null?!1:(this.contents=null,!0):ms(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return ae(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return ls(e)?!t&&W(this.contents)?this.contents.value:this.contents:ae(this.contents)?this.contents.getIn(e,t):void 0}has(e){return ae(this.contents)?this.contents.has(e):!1}hasIn(e){return ls(e)?this.contents!==void 0:ae(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Ro(this.schema,[e],t):ms(this.contents)&&this.contents.set(e,t)}setIn(e,t){ls(e)?this.contents=t:this.contents==null?this.contents=Ro(this.schema,Array.from(e),t):ms(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let n;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Cr({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Cr({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let i=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new Bo(Object.assign(n,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:i,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},c=Te(this.contents,t??"",a);if(typeof s=="function")for(let{count:l,res:u}of a.anchors.values())s(u,l);return typeof o=="function"?xn(o,{"":c},"",c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return X0(this,e)}};function ms(r){if(ae(r))return!0;throw new Error("Expected a YAML collection as document contents")}var Uo=class extends Error{constructor(e,t,n,i){super(),this.name=e,this.code=n,this.message=i,this.pos=t}},lr=class extends Uo{constructor(e,t,n){super("YAMLParseError",e,t,n)}},Vo=class extends Uo{constructor(e,t,n){super("YAMLWarning",e,t,n)}},Th=(r,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:n,col:i}=t.linePos[0];t.message+=` at line ${n}, column ${i}`;let s=i-1,o=r.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="\u2026"+o.substring(a),s-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,s))){let a=r.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026 `),o=a+o}if(/[^ ]/.test(o)){let a=1,c=t.linePos[1];c?.line===n&&c.col>i&&(a=Math.max(1,Math.min(c.col-i,80-s)));let l=" ".repeat(s)+"^".repeat(a);t.message+=`: ${o} ${l} -`}};function Pr(r,{flow:e,indicator:t,next:n,offset:i,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,u=a,d="",f="",p=!1,h=!1,m=null,y=null,g=null,b=null,v=null,S=null,_=null;for(let x of r)switch(h&&(x.type!=="space"&&x.type!=="newline"&&x.type!=="comma"&&s(x.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h=!1),m&&(l&&x.type!=="comment"&&x.type!=="newline"&&s(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),x.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&x.source.includes(" ")&&(m=x),u=!0;break;case"comment":{u||s(x,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let T=x.source.substring(1)||" ";d?d+=f+T:d=T,f="",l=!1;break}case"newline":l?d?d+=x.source:(!S||t!=="seq-item-ind")&&(c=!0):f+=x.source,l=!0,p=!0,(y||g)&&(b=x),u=!0;break;case"anchor":y&&s(x,"MULTIPLE_ANCHORS","A node can have at most one anchor"),x.source.endsWith(":")&&s(x.offset+x.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=x,_??(_=x.offset),l=!1,u=!1,h=!0;break;case"tag":{g&&s(x,"MULTIPLE_TAGS","A node can have at most one tag"),g=x,_??(_=x.offset),l=!1,u=!1,h=!0;break}case t:(y||g)&&s(x,"BAD_PROP_ORDER",`Anchors and tags must be after the ${x.source} indicator`),S&&s(x,"UNEXPECTED_TOKEN",`Unexpected ${x.source} in ${e??"collection"}`),S=x,l=t==="seq-item-ind"||t==="explicit-key-ind",u=!1;break;case"comma":if(e){v&&s(x,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),v=x,l=!1,u=!1;break}default:s(x,"UNEXPECTED_TOKEN",`Unexpected ${x.type} token`),l=!1,u=!1}let E=r[r.length-1],k=E?E.offset+E.source.length:i;return h&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&s(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(l&&m.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&s(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:v,found:S,spaceBefore:c,comment:d,hasNewline:p,anchor:y,tag:g,newlineAfterProp:b,end:k,start:_??k}}function An(r){if(!r)return null;switch(r.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(r.source.includes(` -`))return!0;if(r.end){for(let e of r.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of r.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(An(e.key)||An(e.value))return!0}return!1;default:return!0}}function zo(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 _l(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let i=typeof n=="function"?n:(s,o)=>s===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?` +`}};function Rr(r,{flow:e,indicator:t,next:n,offset:i,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,u=a,d="",f="",p=!1,h=!1,m=null,y=null,g=null,b=null,v=null,S=null,_=null;for(let x of r)switch(h&&(x.type!=="space"&&x.type!=="newline"&&x.type!=="comma"&&s(x.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h=!1),m&&(l&&x.type!=="comment"&&x.type!=="newline"&&s(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),x.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&x.source.includes(" ")&&(m=x),u=!0;break;case"comment":{u||s(x,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let R=x.source.substring(1)||" ";d?d+=f+R:d=R,f="",l=!1;break}case"newline":l?d?d+=x.source:(!S||t!=="seq-item-ind")&&(c=!0):f+=x.source,l=!0,p=!0,(y||g)&&(b=x),u=!0;break;case"anchor":y&&s(x,"MULTIPLE_ANCHORS","A node can have at most one anchor"),x.source.endsWith(":")&&s(x.offset+x.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=x,_??(_=x.offset),l=!1,u=!1,h=!0;break;case"tag":{g&&s(x,"MULTIPLE_TAGS","A node can have at most one tag"),g=x,_??(_=x.offset),l=!1,u=!1,h=!0;break}case t:(y||g)&&s(x,"BAD_PROP_ORDER",`Anchors and tags must be after the ${x.source} indicator`),S&&s(x,"UNEXPECTED_TOKEN",`Unexpected ${x.source} in ${e??"collection"}`),S=x,l=t==="seq-item-ind"||t==="explicit-key-ind",u=!1;break;case"comma":if(e){v&&s(x,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),v=x,l=!1,u=!1;break}default:s(x,"UNEXPECTED_TOKEN",`Unexpected ${x.type} token`),l=!1,u=!1}let E=r[r.length-1],A=E?E.offset+E.source.length:i;return h&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&s(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(l&&m.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&s(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:v,found:S,spaceBefore:c,comment:d,hasNewline:p,anchor:y,tag:g,newlineAfterProp:b,end:A,start:_??A}}function Pn(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(Pn(e.key)||Pn(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==="}")&&Pn(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function _l(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let i=typeof n=="function"?n:(s,o)=>s===o||W(s)&&W(o)&&s.value===o.value;return e.some(s=>i(s.key,t))}var Q0="All mapping items must start at the same column";function Z0({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=Rr(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",Q0)),!m.anchor&&!m.tag&&!p){l=m.end,m.comment&&(a.comment?a.comment+=` +`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||Pn(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",Q0);t.atKey=!0;let g=m.end,b=f?r(t,f,m,i):e(t,g,d,null,m,i);t.schema.compat&&Ho(n.indent,f,i),t.atKey=!1,_l(t,a.items,b)&&i(g,"DUPLICATE_KEY","Map keys must be unique");let v=Rr(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 tS({composeNode:r,composeEmptyNode:e},t,n,i,s){let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?Ee:Je),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=Tr(h,m,t.options.strict,i);y.comment&&(l.comment?l.comment+=` +`+y.comment:l.comment=y.comment),l.range=[n.offset,m,y.offset]}else l.range=[n.offset,m,m];return l}function Dh(r,e,t,n,i,s){let o=t.type==="block-map"?Z0(r,e,t,n,s):t.type==="block-seq"?eS(r,e,t,n,s):tS(r,e,t,n,s),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function rS(r,e,t,n,i){let s=n.tag,o=s?e.directives.tagName(s.source,f=>i(s,"TAG_RESOLVE_FAILED",f)):null;if(t.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=n,h=f&&s?f.offset>s.offset?f:s:f??s;h&&(!p||p.offsetf.tag===o&&f.collection===a);if(!c){let f=e.schema.knownTags[o];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?i(s,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Dh(r,e,t,i,o)}let l=Dh(r,e,t,i,o,c),u=c.resolve?.(l,f=>i(s,"TAG_RESOLVE_FAILED",f),e.options)??l,d=ne(u)?u:new F(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}function Nh(r,e,t){let n=e.offset,i=IN(e,r.options.strict,t);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};let s=i.mode===">"?F.BLOCK_FOLDED:F.BLOCK_LITERAL,o=e.source?ON(e.source):[],a=o.length;for(let m=o.length-1;m>=0;--m){let y=o[m][1];if(y===""||y==="\r")a=m;else break}if(a===0){let m=i.chomp==="+"&&o.length>0?` `.repeat(Math.max(1,o.length-1)):"",y=n+i.length;return e.source&&(y+=e.source.length),{value:m,type:s,comment:i.comment,range:[n,y,y]}}let c=e.indent+i.indent,l=e.offset+i.length,u=0;for(let m=0;mc&&(c=y.length);else{y.length=a;--m)o[m][0].length>c&&(a=m+1);let d="",f="",p=!1;for(let m=0;mc||g[0]===" "?(f===" "?f=` @@ -109,94 +109,95 @@ ${l} `+o[m][0].slice(c);d[d.length-1]!==` `&&(d+=` `);break;default:d+=` -`}let h=n+i.length+e.source.length;return{value:d,type:s,comment:i.comment,range:[n,h,h]}}function CN({offset:r,props:e},t,n){if(e[0].type!=="block-scalar-header")return n(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:i}=e[0],s=i[0],o=0,a="",c=-1;for(let f=1;ft(n+f,p,h);switch(i){case"scalar":a=F.PLAIN,c=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("(?t(n+f,p,h);switch(i){case"scalar":a=F.PLAIN,c=DN(s,l);break;case"single-quoted-scalar":a=F.QUOTE_SINGLE,c=NN(s,l);break;case"double-quoted-scalar":a=F.QUOTE_DOUBLE,c=LN(s,l);break;default:return t(r,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[n,n+s.length,n+s.length]}}let u=n+s.length,d=Tr(o,u,e,t);return{value:c,type:a,comment:d.comment,range:[n,u,d.offset]}}function DN(r,e){let t="";switch(r[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${r[0]}`;break}case"@":case"`":{t=`reserved character ${r[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),nS(r)}function NN(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),nS(r.slice(1,-1)).replace(/''/g,"'")}function nS(r){let e=/(.*?)\r?\n/sy,t=e.exec(r);if(!t)return r;let n,i;try{n=new RegExp("(?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===` +`)&&(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 FN(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 NN={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:` -`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function LN(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 Lh(r,e,t,n){let{value:i,type:s,comment:o,range:a}=e.type==="block-scalar"?Dh(r,e,n):Nh(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=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;in(t,"TAG_RESOLVE_FAILED",d)):null,l;r.options.stringKeys&&r.atKey?l=r.schema[Pt]:c?l=BN(r.schema,i,c,t,n):e.type==="scalar"?l=UN(r,i,e,n):l=r.schema[Pt];let u;try{let d=l.resolve(i,f=>n(t??e,"TAG_RESOLVE_FAILED",f),r.options);u=W(d)?d:new F(d)}catch(d){let f=d instanceof Error?d.message:String(d);n(t??e,"TAG_RESOLVE_FAILED",f),u=new F(i)}return u.range=a,u.source=i,s&&(u.type=s),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function BN(r,e,t,n,i){if(t==="!")return r[Pt];let s=[];for(let a of r.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;let o=r.knownTags[t];return o&&!o.collection?(r.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),r[Pt])}function UN({atKey:r,directives:e,schema:t},n,i,s){let o=t.tags.find(a=>(a.default===!0||r&&a.default==="key")&&a.test?.test(n))||t[Pt];if(t.compat){let a=t.compat.find(c=>c.default&&c.test?.test(n))??t[Pt];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),u=`Value may be parsed as either ${c} or ${l}`;s(i,"TAG_RESOLVE_FAILED",u,!0)}}return o}function iS(r,e,t){if(e){t??(t=e.length);for(let n=t-1;n>=0;--n){let i=e[n];switch(i.type){case"space":case"comment":case"newline":r-=i.source.length;continue}for(i=e[++n];i?.type==="space";)r+=i.source.length,i=e[++n];break}}return r}var VN={composeNode:jh,composeEmptyNode:Sl};function jh(r,e,t,n){let i=r.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=t,l,u=!0;switch(e.type){case"alias":l=HN(r,e,n),(a||c)&&n(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Fh(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=rS(VN,r,e,t,n),a&&(l.anchor=a.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);n(e,"RESOURCE_EXHAUSTION",f)}break;default:{let d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=Sl(r,e.offset,void 0,null,t,n)),a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&r.options.stringKeys&&(!W(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),r.options.keepSourceTokens&&u&&(l.srcToken=e),l}function Sl(r,e,t,n,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){let u={type:"scalar",offset:iS(e,t,n),indent:-1,source:""},d=Fh(r,u,a,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(d.spaceBefore=!0),s&&(d.comment=s,d.range[2]=c),d}function HN({options:r},{offset:e,source:t,end:n},i){let s=new Wr(t.substring(1));s.source===""&&i(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&i(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+t.length,a=Tr(n,o,r.strict,i);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}function sS(r,e,{offset:t,start:n,value:i,end:s},o){let a=Object.assign({_directives:e},r),c=new An(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Rr(n,{indicator:"doc-start",next:i??s?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?jh(l,i,u,o):Sl(l,u.end,n,null,u,o);let d=c.contents.range[2],f=Tr(s,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[t,d,f.offset],c}function zo(r){if(typeof r=="number")return[r,r+1];if(Array.isArray(r))return r.length===2?r:[r[0],r[1]];let{offset:e,source:t}=r;return[e,e+(typeof t=="string"?t.length:1)]}function oS(r){let e="",t=!1,n=!1;for(let i=0;i{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} +`)+(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 Ko=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,i,s)=>{let o=zo(t);s?this.warnings.push(new Vo(o,n,i)):this.errors.push(new lr(o,n,i))},this.directives=new Cr({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:i}=oS(this.prelude);if(n){let s=e.contents;if(t)e.comment=e.comment?`${e.comment} ${n}`:n;else if(i||e.directives.docStart||!s)e.commentBefore=n;else if(ae(s)&&!s.flow&&s.items.length>0){let o=s.items[0];te(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${n} ${a}`:n}else{let o=s.commentBefore;s.commentBefore=o?`${n} -${o}`:n}}if(t){for(let s=0;s{let s=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{let s=zo(e);s[0]+=t,this.onError(s,"BAD_DIRECTIVE",n,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=sS(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new lr(zo(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){let n="Unexpected doc-end without preceding document";this.errors.push(new lr(zo(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=Tr(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let n=this.doc.comment;this.doc.comment=n?`${n} +${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new lr(zo(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let n=Object.assign({_directives:this.directives},this.options),i=new An(void 0,n);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,t,t],this.decorate(i,!1),yield i}}};var qh=Symbol("break visit"),zN=Symbol("skip children"),aS=Symbol("remove item");function ui(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),cS(Object.freeze([]),r,e)}ui.BREAK=qh;ui.SKIP=zN;ui.REMOVE=aS;ui.itemAtPath=(r,e)=>{let t=r;for(let[n,i]of e){let s=t?.[n];if(s&&"items"in s)t=s.items[i];else return}return t};ui.parentCollection=(r,e)=>{let t=ui.itemAtPath(r,e.slice(0,-1)),n=e[e.length-1][0],i=t?.[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function cS(r,e,t){let n=t(e,r);if(typeof n=="symbol")return n;for(let i of["key","value"]){let s=e[i];if(s&&"items"in s){for(let o=0;o":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===` +`: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 dr(r){switch(r){case void 0:case" ":case` +`:case"\r":case" ":return!0;default:return!1}}var dS=new Set("0123456789ABCDEFabcdef"),WN=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),$l=new Set(",[]{}"),GN=new Set(` ,[]{} +\r `),Hh=r=>!r||GN.has(r),Wo=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===` `?!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==="...")&&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=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&dr(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&ethis.indentValue&&!dr(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===":")&&dr(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(Hh),"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=>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` +`,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=>dr(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 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===` +`&&s>=this.pos&&s+1+t>a)e=s;else break}while(!0);return yield xl,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,i;for(;i=this.buffer[++n];)if(i===":"){let s=this.buffer[n+1];if(dr(s)||e&&$l.has(s))break;t=n}else if(dr(i)){let s=this.buffer[n+1];if(i==="\r"&&(s===` `?(n+=1,i=` `,s=this.buffer[n+1]):t=n),s==="#"||e&&$l.has(s))break;if(i===` -`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&$l.has(i))break;t=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield xl,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(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===` +`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&$l.has(i))break;t=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield xl,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Hh),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,n=this.charAt(1);if(dr(n)||t&&$l.has(n)){t?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!dr(t)&&t!==">";)t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if(WN.has(t))t=this.buffer[++e];else if(t==="%"&&dS.has(this.buffer[e+1])&&dS.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` `?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 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.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 Go=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t>1;this.lineStarts[s]=0;)switch(r[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;r[++e]?.type==="space";);return r.splice(e,r.length)}function kl(r,e){if(e.length<1e5)Array.prototype.push.apply(r,e);else for(let t=0;t0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let n=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in n?n.indent:0:t.type==="flow-collection"&&n.type==="document"&&(t.indent=0),t.type==="flow-collection"&&fS(t),n.type){case"document":n.value=t;break;case"block-scalar":n.props.push(t);break;case"block-map":{let i=n.items[n.items.length-1];if(i.value){n.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=t;else{Object.assign(i,{key:t,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{let i=n.items[n.items.length-1];i.value?n.items.push({start:[],value:t}):i.value=t;break}case"flow-collection":{let i=n.items[n.items.length-1];!i||i.value?n.items.push({start:[],key:t,sep:[]}):i.sep?i.value=t:Object.assign(i,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){let i=t.items[t.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&uS(i.start)===-1&&(t.indent===0||i.start.every(s=>s.type!=="comment"||s.indent=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,i=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",s=[];if(i&&t.sep&&!t.value){let o=[];for(let a=0;ae.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(s=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||t.value?(s.push(this.sourceToken),e.items.push({start:s}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):i||t.value?(s.push(this.sourceToken),e.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(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(` +`,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)){kl(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(Cn(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(pS(t.key)&&!Cn(t.sep,"newline")){let o=ys(t.start),a=t.key,c=t.sep;c.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else s.length>0?t.sep=t.sep.concat(s,this.sourceToken):t.sep.push(this.sourceToken);else if(Cn(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=ys(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||i?e.items.push({start:s,key:null,sep:[this.sourceToken]}):Cn(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);i||t.value?(e.items.push({start:s,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!Cn(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&e.items.push({start:s});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){kl(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||Cn(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:i,sep:[]}):t.sep?this.stack.push(i):Object.assign(t,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let i=El(n),s=ys(i);fS(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(` `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(` -`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=El(e),n=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=El(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 KN(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new Jo||null,prettyErrors:e}}function mS(r,e={}){let{lineCounter:t,prettyErrors:n}=KN(e),i=new Yo(t?.addNewLine),s=new Wo(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 ar(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(Th(r,t)),o.warnings.forEach(Th(r,t))),o}function ui(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let i=mS(r,t);if(!i)return null;if(i.warnings.forEach(s=>nl(i.options.logLevel,s)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:n},t))}var JN=r=>r/2**32|0,YN=r=>r>>>0;function yS(r,e,t,n){let i=JN(t),s=YN(t);r.setUint32(e,n?s:i,n),r.setUint32(e+4,n?i:s,n)}function gS(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}var Hh=r=>r?`"${r}" `:"";function XN(r,e=""){if(typeof r!="number")throw new TypeError(Hh(e)+"expected number, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError(Hh(e)+"expected integer >= 0, got "+r);return r}function kl(r,e,t=""){if(gS(r)&&(e===void 0||r.length===e))return r;e!==void 0&&XN(e,"length");let n=gS(r),i=e!==void 0?` of length ${e}`:"",s=n?`length=${r.length}`:`type=${typeof r}`,o=Hh(t)+"expected Uint8Array"+i+", got "+s;throw n?new RangeError(o):new TypeError(o)}var QN=(r,e)=>{if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof r)},bS=(r,e)=>{QN(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 zh(r,e=!0){if(r.destroyed)throw new Error("hash was destroyed");if(e&&r.finished)throw new Error("digest() was already called")}function vS(r,e){kl(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 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;t= '+t)}function gs(...r){for(let e=0;e>>e}function Cl(r,e){return r<>>32-e>>>0}var rL=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",nL=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Le(r){if(Al(r),rL)return r.toHex();let e="";for(let t=0;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(` +`)&&e.slice(1)===r}function um(r,e){if(r===e)return!0;if(Array.isArray(r)||Array.isArray(e))return Array.isArray(r)&&Array.isArray(e)&&r.length===e.length&&r.every((i,s)=>um(i,e[s]));if(!r||!e||typeof r!="object"||typeof e!="object")return!1;let t=Object.entries(r),n=e;return t.length===Object.keys(n).length&&t.every(([i,s])=>Object.prototype.hasOwnProperty.call(n,i)&&um(s,n[i]))}var $s=class{fileSystem;runtime;mode;blobStore;constructor(e,t,n,i){this.fileSystem=e,this.runtime=t,this.mode=n,this.blobStore=i}async recordPathPolicy(e){return lx(Object.keys(e.resources??{}),()=>this.fileSystem.read("mdbase.yaml"))}async put(e,t,n={}){let{managedState:i=e,acceptedHash:s,materialized:o,inspectionPreflighted:a}=n;a||In(t.path,await this.recordPathPolicy(e)),o===void 0&&!a&&fx(t.path,t.record_id,Object.keys(e.resources??{}),Object.entries(e.records),Object.entries(e.files??{}));let c=o?.document??Il(t),l=a===1?await this.fileSystem.readText(t.path):await this.fileSystem.read(t.path),u=typeof l=="string"||l===null?l:void 0,d=i?.records[t.record_id],f=u==null?null:this.runtime.digest(u);if(a!==1&&f!==null&&u!==c&&!(d!==void 0&&d.path===t.path&&f===d.hash)&&(!s||f!==s))throw new $t(t.record_id,t.path);d&&d.path!==t.path&&await this.remove(i,t.record_id,d.path);let p=u===c?f:this.runtime.digest(c);u!==c&&await this.fileSystem.write(t.path,c,u),e.records[t.record_id]={path:t.path,revision:t.revision,hash:o?.hash??p,...this.mode==="read_write"?{record:t}:{}}}async putFile(e,t,n=e,i){if(xt(t),!this.blobStore)throw new w("file_storage_unavailable","Selected collection files require a content-addressed blob store adapter.");px(t.path,t.file_id,e),e.files??={};let s=n.files?.[t.file_id],o=await this.fileSystem.inspectBinary(t.path),a=Rt(t.path),c=Object.values(n.files??{}).find(h=>Rt(h.file.path)===a),l=[...Object.values(n.resources??{}),...Object.values(n.records)].find(h=>Rt(h.path)===a),u=l?await this.fileSystem.read(t.path):null,d=s?.file.path===t.path&&tn(o,s.file),f=c!==void 0&&tn(o,c.file),p=l!==void 0&&u!==null&&this.runtime.digest(u)===l.hash;if(o!==null&&!tn(o,t)&&!d&&!f&&!p&&!(i!==void 0&&o?.size===i.size&&o.content_digest===i.content_digest))throw new $t(t.file_id,t.path);if(s&&s.file.path!==t.path){let h=await this.fileSystem.inspectBinary(s.file.path);if(h!==null&&!tn(h,s.file))throw new $t(t.file_id,s.file.path)}tn(o,t)||await this.fileSystem.writeBinary(t.path,Bl(this.blobStore.read(t.content_digest),t),o),s&&s.file.path!==t.path&&await this.fileSystem.remove(s.file.path,s.file),e.files[t.file_id]={file:t}}async removeFile(e,t){let n=e.files?.[t];if(!n)return;let i=await this.fileSystem.inspectBinary(n.file.path);if(i!==null&&!tn(i,n.file))throw new $t(t,n.file.path);i!==null&&await this.fileSystem.remove(n.file.path,i),delete e.files[t]}async remove(e,t,n,i={}){let s=e.records[t],o=s?.path??n;i.inspectionPreflighted||In(o,await this.recordPathPolicy(e));let a=await this.fileSystem.read(o);if(a!==null&&s&&this.runtime.digest(a)!==s.hash)throw new $t(t,s.path);a!==null&&await this.fileSystem.remove(o,a),delete e.records[t]}async putResource(e,t,n){let i=await this.fileSystem.read(t.path),s=n?.resources?.[t.path];if(i!==null&&i!==t.document&&(!s||this.runtime.digest(i)!==s.hash))throw new $t(`resource:${t.path}`,t.path);await this.fileSystem.write(t.path,t.document,i),e.resources??={},e.resources[t.path]={path:t.path,revision:t.revision,hash:this.runtime.digest(t.document)}}async removeResource(e,t,n){let i=await this.fileSystem.read(t);if(i!==null&&this.runtime.digest(i)!==n.hash)throw new $t(`resource:${t}`,t);i!==null&&await this.fileSystem.remove(t,i),e.resources&&delete e.resources[t]}};async function mx(r,e,t,n){for(let i in r.records){if(!Object.hasOwn(r.records,i))continue;let s=r.records[i];In(s.path,e);let o=await t.read(s.path);if(o===null||n(o)!==s.hash)throw new $t(i,s.path)}for(let[i,s]of Object.entries(r.resources??{})){let o=await t.read(s.path);if(o===null||n(o)!==s.hash)throw new $t(`resource:${i}`,s.path)}for(let[i,s]of Object.entries(r.files??{})){let o=await t.inspectBinary(s.file.path);if(!tn(o,s.file))throw new $t(i,s.file.path)}}async function yx(r){let{state:e,selectiveSync:t,fileSystem:n,pathPolicy:i,digest:s}=r;if(t.excluded_folders.length>0||t.file_classes.length!==5)throw new w("promotion_incomplete_file_projection","Moving the source of truth requires every collection file class with no excluded folders.");if(Object.keys(e.planned_conflicts??{}).length>0||e.batch!==void 0)throw new w("promotion_not_converged","Upload or resolve every local change before moving the source of truth.");await mx(e,i,n,s);let o=new Set(Object.keys(e.resources??{})),a=new Set(Object.values(e.records).map(d=>d.path)),c=(await n.listMarkdown(o)).filter(d=>!a.has(d));if(c.length>0)throw new w("promotion_unmanaged_files",`Synchronize unmanaged Markdown before promotion: ${c.join(", ")}.`);if(!n.listBinary)throw new w("promotion_file_scan_unavailable","Moving the source of truth requires binary file enumeration.");let l=new Set(Object.values(e.files??{}).map(d=>d.file.path)),u=(await n.listBinary(new Set([...o,...a]))).filter(d=>!l.has(d));if(u.length>0)throw new w("promotion_unmanaged_files",`Synchronize unmanaged files before moving the source of truth: ${u.join(", ")}.`);return{cursor:e.cursor,digest:Dl([...Object.entries(e.resources??{}).map(([d,f])=>({kind:"resource",path:d,identity:"",document_hash:Yh(f.hash)})),...Object.entries(e.records).map(([d,f])=>({kind:"record",path:f.path,identity:d,document_hash:Yh(f.hash)})),...Object.values(e.files??{}).map(({file:d})=>({kind:"file",path:d.path,identity:d.file_id,document_hash:Nl(d)}))])}}function Ir(r,e,t,n,i){return{status:r,plan_fingerprint:e.fingerprint,applied:n,pending:t.pending,checkpoint_cursor:t.cursor,conflicts:t.conflicts.length,issues:e.issues,...i?{failure:i}:{}}}function gx(r,e){if(["planned","applying","cancelled","stale","blocked","failed"].includes(r.state))return r;let t=[...r.local_issues];for(let n of e.issues)n.path&&(n.code==="invalid_frontmatter"||n.code==="file_read_failed")&&!t.some(({path:i,code:s,message:o})=>i===n.path&&s===n.code&&o===n.message)&&t.push({path:n.path,code:n.code,message:n.message});return r.conflicts.length>0||t.length>0||e.summary.blocking_issues>0||e.summary.conflicts>0?{...r,state:"attention",local_issues:t}:{...r,state:e.actions.some(n=>n.command!=="advance_checkpoint")?"changes_waiting":"up_to_date"}}function Wt(r,e){if(!r)return{state:"not_initialized",mode:e,pending:0,pending_files:0,conflicts:[],local_issues:[],cursor:null,last_synced_at:null};let t=[];for(let[o,a]of Object.entries(r.planned_conflicts??{})){let c=t.findIndex(({entity:u,object_id:d})=>u===a.entity&&d===o);c!==-1&&t.splice(c,1);let l=a.local.state==="exact"?a.local.object.path:a.remote.state==="exact"?a.remote.object.path:null;t.push({entity:a.entity,object_id:o,decision_id:a.decision_id??"",path:l,kind:a.conflict_kind==="rejected"?"rejected":"conflicted",message:a.conflict_kind==="rejected"?"The authority rejected this local change.":"Local and authority changes need a decision."})}let n=[],i=r.batch?r.batch.plan.actions.slice(r.batch.next_action).filter(o=>o.command!=="advance_checkpoint").length:0;return{state:(r.batch?r.batch.phase==="prepared"?"planned":r.batch.phase==="applying"||r.batch.phase==="effects_complete"?"applying":r.batch.phase==="cancelled"?"cancelled":r.batch.failure?.code==="sync_plan_stale"?"stale":"blocked":null)??(t.length?"attention":"up_to_date"),mode:e,pending:i,pending_files:r.batch?r.batch.plan.actions.slice(r.batch.next_action).filter(o=>o.command!=="advance_checkpoint"&&("target"in o&&o.target.entity==="file"||"source"in o&&o.source.entity==="file"||"entity"in o&&o.entity==="file")).length:0,conflicts:t,local_issues:n,cursor:r.batch?.checkpoint_before.cursor??r.cursor,last_synced_at:r.last_synced_at??null,generation:r.generation??0,pending_checkpoint:r.batch?.checkpoint_after.cursor??null,...r.batch?{plan_fingerprint:r.batch.plan.fingerprint}:{},...r.last_completed_plan?{last_completed_plan:r.last_completed_plan}:{},recovery_required:r.batch!==void 0,...r.batch?.failure?{failure:r.batch.failure}:{}}}async function l2(r,e,t){let n=await e.openSession();if(n.protocol_version!==1||n.protocol_profile!=="exact_document_v1"||n.replica_id!==r||n.mode!==t)throw new w("sync_protocol_incompatible",`Filesystem mirror requires exact-document v1 and its own ${t.replace("_","-")} replica.`);return n}async function Jl(r,e,t,n,i){let s=await l2(r,e,t),o=s.resources.documents??[],a=Wl(o),c=new Gl(a,o,i.digest),l=[];await hx(e,s,async f=>{for(let p of f){let h=c.validate(p);bi(n,h.record.path)&&l.push(h)}});let u=[],d=new Set;return await HS(e,s,async f=>{for(let p of f)if(Ul(n,p)){if(d.has(p.file_id))throw new w("invalid_snapshot",`Hosted snapshot repeats file identity ${p.file_id}.`);d.add(p.file_id),u.push(p)}}),ea([...o.map(f=>f.path),...l.map(({record:f})=>f.path),...u.map(f=>f.path)]),{session:s,resources:o,records:l,files:u}}var Yl="exact_document_plan_only_v1",Xl="three_way_exact_document_v1",Ql="portable_mirror_projection_v1";function Zl(r){return JSON.stringify(fm(r))}function _i(r,e){return`sha256:${e(Zl(r))}`}function fm(r){if(r===null||typeof r=="string"||typeof r=="boolean")return r;if(typeof r=="number"){if(!Number.isSafeInteger(r))throw new w("invalid_sync_plan","Sync plans contain only safe integer numeric values.");return r}if(Array.isArray(r))return r.map(fm);if(typeof r=="object"){let e={};for(let t of Object.keys(r).sort()){let n=r[t];if(n===void 0)throw new w("invalid_sync_plan",`Sync plan field ${t} is undefined rather than an explicit state.`);e[t]=fm(n)}return e}throw new w("invalid_sync_plan","Sync plans contain only canonical I-JSON values.")}function Sx(r,e,t){let n=new Map(r.base.map(u=>[u.identity,u])),i=new Map(r.remote.map(u=>[u.identity,u])),s=new Map,o=new Map(r.local.map(u=>[u.object.path,u]));for(let u of r.local)!u.stable_identity||u.object.identity===""||(s.set(u.object.identity,u.object),o.delete(u.object.path));for(let[u,d]of n){let f=o.get(d.path);f&&(s.set(u,{...f.object,identity:u}),o.delete(d.path))}for(let[u,d]of i){if(s.has(u))continue;let f=o.get(d.path);f&&f.object.entity===d.entity&&(s.set(u,{...f.object,identity:u}),o.delete(d.path))}for(let[u,d]of n){if(s.has(u))continue;let f=[...o.values()].filter(h=>h.object.entity===d.entity&&h.object.payload_revision===d.payload_revision);if(f.length!==1)continue;let p=f[0];s.set(u,{...p.object,identity:u,revision:p.object.payload_revision===d.payload_revision?d.revision:p.object.revision}),o.delete(p.object.path)}for(let u of o.values()){let d=u.stable_identity?u.object.identity:v2(e,u.object,t);s.set(d,{...u.object,identity:d})}let a=new Set([...n.keys(),...s.keys(),...i.keys()]),c=new Map([...s.values()].map(u=>[u.path,u])),l=new Map([...i.values()].map(u=>[u.path,u]));return[...a].sort().map(u=>{let d=n.get(u),f=s.get(u),p=i.get(u),h=p?.path??f?.path??d.path,m=f?.path??p?.path??d.path;return{entity:(f??p??d).entity,identity:u,base:ta(d),local:ta(f),remote:ta(p),local_target_owner:ta(c.get(h)),remote_target_owner:ta(l.get(m))}})}function gm(r,e){let t=r.issues.some(A=>A.blocking),n=[],i=r.issues.filter(A=>A.blocking),s=[...r.objects].sort(_2),o=new Set(s.filter(A=>{if(r.mode!=="read_only"||A.local.state!=="exact"||A.remote.state!=="exact"||A.local.object.path!==A.remote.object.path)return!1;let x=i.filter(R=>R.path===A.local.object.path);return x.length>0&&x.every(R=>R.code==="invalid_frontmatter")})),a=new Set(i.map(A=>A.path).filter(A=>A!==void 0&&![...o].some(x=>x.local.object.path===A))),c=new Set,l=A=>[A.base,A.local,A.remote].filter(x=>x.state==="exact").map(x=>x.object.path),u=new Map,d=new Map,f=A=>A.split("/").map((x,R,$)=>$.slice(0,R+1).join("/")),p=(A,x,R)=>{A.has(x)||A.set(x,new Set),A.get(x).add(R)};if(a.size)for(let A of s)for(let x of l(A)){p(u,x,A);for(let R of f(x))p(d,R,A)}let h=[...a],m=new Set;for(let A=0;A!A.path)){for(let A of s)c.has(A)||y2(r,A,n,o.has(A));n=f2(n,r.objects,e),n=d2(n,r.objects)}if(n.length>0||!t&&(r.kind!=="incremental"||r.boundary.checkpoint.cursor!==r.boundary.authority_cursor)){let A=n.map(x=>x.key);n.push({key:"checkpoint",depends_on_keys:A,command:"advance_checkpoint",reason:r.kind==="incremental"?"remote_change":r.kind,expected:r.boundary.checkpoint,next:t?r.boundary.checkpoint:{generation:r.boundary.checkpoint.generation+1,cursor:r.boundary.authority_cursor}})}let g=new Map;for(let A of n){let{key:x,depends_on_keys:R,...$}=A;g.set(x,_i({action_scope:{replica_id:r.boundary.replica_id,scope_epoch:r.boundary.scope_epoch,generation:r.boundary.checkpoint.generation},key:x,...$},e))}let b=n.map(A=>{let{key:x,depends_on_keys:R,...$}=A,q={...$,action_id:g.get(x),depends_on:R.map(M=>g.get(M))};if((q.command==="put_remote"||q.command==="move_remote"||q.command==="delete_remote")&&(q.idempotency_key=q.action_id),q.command==="move_remote"){let M=R.find(V=>V===`${q.source.identity}:put-remote`);M&&(q.revision_from_dependency=g.get(M))}return q}),v=[...c].filter(A=>!i.some(x=>l(A).includes(x.path))).map(A=>({code:"local_collision",blocking:!0,path:l(A)[0],message:"Deferred because a related path transition is blocked. Independent files can still sync."})),S=[...r.issues,...v].sort(S2),_={uploads:b.filter($2).length,downloads:b.filter(E2).length,conflicts:b.filter(A=>A.command==="record_conflict").length,blocking_issues:S.filter(A=>A.blocking).length},E={plan_version:1,engine_profile:Yl,protocol_profile:"exact_document_v1",planner_policy:Xl,projection_policy:Ql,replica_id:r.boundary.replica_id,mode:r.mode,kind:r.kind,base_cursor:r.boundary.checkpoint.cursor,authority_cursor:r.boundary.authority_cursor,scope_epoch:r.boundary.scope_epoch,checkpoint_generation:r.boundary.checkpoint.generation,selective_sync:r.selective_sync,actions:b,issues:S,summary:_};return{...E,fingerprint:_i(E,e)}}function d2(r,e){if(!r.some(c=>c.command==="move_remote"))return r;let t=[...r],n=new Set;for(let c of u2(t))for(let l of c){let u=t.find(d=>d.key===l);u?.command==="move_remote"&&n.add(u.source.identity)}let i=mm(t),s=new Map(t.map(c=>[c.key,c])),o=!0;for(;o;){o=!1;for(let c of t){if(c.command!=="move_remote")continue;let l=c.expected_target_owner;if(l.state!=="exact"||l.object.identity===c.source.identity)continue;let u=s.get(i.get(Or(l.object))??""),d=u&&bx(u);(!u||d&&n.has(d))&&!n.has(c.source.identity)&&(n.add(c.source.identity),o=!0)}}if(n.size>0){t=t.filter(l=>{let u=bx(l);return!u||!n.has(u)||l.command!=="put_remote"&&l.command!=="move_remote"});let c=new Map(e.map(l=>[l.identity,l]));for(let l of[...n].sort()){let u=c.get(l);!u||u.entity==="resource"||t.push({key:`${l}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"local_change",identity:l,entity:u.entity,local:u.local,remote:u.remote,conflict_kind:"path_occupied"})}}let a=mm(t);for(let c of t){if(c.command!=="move_remote")continue;let l=c.expected_target_owner;if(l.state!=="exact"||l.object.identity===c.source.identity)continue;let u=a.get(Or(l.object));!u||u===c.key||(c.depends_on_keys.includes(u)||c.depends_on_keys.push(u),c.expected_target_owner={state:"absent"})}return xx(t)}function u2(r){let e=r.filter(s=>s.command==="move_remote"),t=new Map(e.map(s=>[s.key,s])),n=mm(r),i=new Map;for(let s of e){let o=[],a=new Map,c=s;for(;c;){let l=a.get(c.key);if(l!==void 0){let d=o.slice(l);i.set([...d].sort().join("\0"),d);break}a.set(c.key,o.length),o.push(c.key);let u=c.expected_target_owner;c=u.state==="exact"?t.get(n.get(Or(u.object))??""):void 0}}return[...i.values()]}function mm(r){let e=new Map;for(let t of r)t.command==="move_remote"?e.set(Or(t.source),t.key):t.command==="delete_remote"&&e.set(Or(t.target),t.key);return e}function bx(r){if(r.command==="move_remote")return r.source.identity;if(r.command==="put_remote"||r.command==="delete_remote")return r.target.identity}function f2(r,e,t){if(!r.some(d=>d.command==="move_local"||d.command==="write_local"))return r;let n=[...r],i=new Set;for(let d of e)d.base.state==="exact"&&i.add(d.base.object.path),d.local.state==="exact"&&i.add(d.local.object.path),d.remote.state==="exact"&&i.add(d.remote.object.path);for(;;){let d=p2(n);if(!d)break;let f=[...d].sort()[0],p=n.findIndex(b=>b.key===f),h=n[p];if(!h||h.command!=="move_local")throw new Error("Planner invariant: local path cycle contains a non-move action.");let m=m2(h.source,h.target_path,i,t);i.add(m);let y={...h.source,path:m},g={key:`${h.source.identity}:stage-local`,depends_on_keys:[...h.depends_on_keys],command:"move_local",reason:h.reason,source:h.source,target_path:m,expected_source_owner:h.expected_source_owner,expected_target_owner:{state:"absent"}};h.source=y,h.expected_source_owner={state:"exact",object:y},h.depends_on_keys=[g.key],n.splice(p,0,g)}let s=ym(n),o=new Map(e.map(d=>[d.identity,d])),a=new Set,c=new Map(n.map(d=>[d.key,d])),l=!0;for(;l;){l=!1;for(let d of n){let f=vx(d),p=ed(d);if(f?.state!=="exact"||f.object.identity===p)continue;let h=c.get(s.get(Or(f.object))??""),m=h&&ed(h);(!h||m&&a.has(m))&&!a.has(p)&&(a.add(p),l=!0)}}if(a.size>0){n=n.filter(d=>!a.has(ed(d))||d.command!=="move_local"&&d.command!=="write_local");for(let d of[...a].sort()){let f=o.get(d);!f||f.entity==="resource"||n.push({key:`${d}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"remote_change",identity:d,entity:f.entity,local:f.local,remote:f.remote,conflict_kind:"path_occupied"})}}let u=ym(n);for(let d of n){let f=vx(d),p=ed(d);if(f?.state!=="exact"||f.object.identity===p)continue;let h=u.get(Or(f.object));!h||h===d.key||(d.depends_on_keys.includes(h)||d.depends_on_keys.push(h),h2(d,{state:"absent"}))}return xx(n)}function p2(r){let e=r.filter(i=>i.command==="move_local"),t=new Map(e.map(i=>[i.key,i])),n=ym(r);for(let i of e){let s=[],o=new Map,a=i;for(;a;){let c=o.get(a.key);if(c!==void 0)return s.slice(c);o.set(a.key,s.length),s.push(a.key);let l=a.expected_target_owner;a=l.state==="exact"?t.get(n.get(Or(l.object))??""):void 0}}}function ym(r){let e=new Map;for(let t of r)t.command==="move_local"?e.set(Or(t.source),t.key):t.command==="delete_local"&&e.set(Or(t.target),t.key);return e}function vx(r){if(r.command==="move_local")return r.expected_target_owner;if(r.command==="write_local")return r.expected_path_owner}function h2(r,e){r.command==="move_local"?r.expected_target_owner=e:r.command==="write_local"&&(r.expected_path_owner=e)}function ed(r){return r.command==="move_local"?r.source.identity:r.command==="write_local"||r.command==="delete_local"?r.target.identity:""}function Or(r){return`${r.entity}\0${r.identity}\0${r.path}`}function m2(r,e,t,n){let i=r.path.lastIndexOf("/"),s=i<0?"":r.path.slice(0,i+1),o=i<0?r.path:r.path.slice(i+1),a=o.lastIndexOf("."),c=a>0?o.slice(a):"";for(let l=0;;l+=1){let u=n(`${r.entity}\0${r.identity}\0${r.path}\0${e}\0${l}`),d=`${s}.mdbase-sync-stage-${u.slice(0,16)}${c}`;if(!t.has(d))return d}}function xx(r){let e=[...r],t=new Set,n=[];for(;e.length>0;){let i=e.findIndex(o=>o.depends_on_keys.every(a=>t.has(a)));if(i<0)throw new Error("Planner invariant: action dependency graph contains a cycle.");let[s]=e.splice(i,1);n.push(s),t.add(s.key)}return n}function y2(r,e,t,n){if(e.frozen_conflict){t.push(w2(e.frozen_conflict.local,e.frozen_conflict.remote)?{key:`${e.identity}:clear-conflict`,depends_on_keys:[],command:"clear_conflict",reason:"pending",identity:e.identity,entity:e.entity,expected_local:e.frozen_conflict.local,expected_remote:e.frozen_conflict.remote}:{key:`${e.identity}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"pending",identity:e.identity,entity:e.entity,...e.frozen_conflict});return}let i=!hm(e.local,e.base),s=!hm(e.remote,e.base);if(!(!i&&!s)){if(e.entity==="resource"){if(i)return;pm(e,t);return}if(r.mode==="read_only"){(!i||n)&&pm(e,t);return}if(i&&s){if(hm(e.local,e.remote))return;t.push(b2(e));return}i?g2(e,t):pm(e,t)}}function pm(r,e){if(r.remote.state==="absent"){r.local.state==="exact"&&e.push({key:`${r.identity}:delete-local`,depends_on_keys:[],command:"delete_local",reason:"remote_change",target:r.local.object,expected_local:r.local,expected_path_owner:r.local_target_owner});return}let t=r.remote.object;if(r.local.state==="absent"){e.push(wx(r,t,[]));return}let n=r.local.object,i;if(n.path!==t.path){let s=`${r.identity}:move-local`;e.push({key:s,depends_on_keys:[],command:"move_local",reason:"remote_change",source:n,target_path:t.path,expected_source_owner:r.local,expected_target_owner:r.local_target_owner}),i=s}n.revision!==t.revision&&e.push(wx(r,t,i?[i]:[]))}function wx(r,e,t){return{key:`${r.identity}:write-local`,depends_on_keys:t,command:"write_local",reason:"remote_change",target:e,payload_revision:e.payload_revision,expected_local:t.length>0?{state:"exact",object:{...e,revision:nn(r.local).revision,payload_revision:nn(r.local).payload_revision,...nn(r.local).size===void 0?{}:{size:nn(r.local).size}}}:r.local,expected_path_owner:t.length>0?{state:"exact",object:{...e,revision:nn(r.local).revision,payload_revision:nn(r.local).payload_revision,...nn(r.local).size===void 0?{}:{size:nn(r.local).size}}}:r.local_target_owner}}function g2(r,e){if(r.local.state==="absent"){r.remote.state==="exact"&&e.push({key:`${r.identity}:delete-remote`,depends_on_keys:[],command:"delete_remote",reason:"local_change",target:r.remote.object,expected_remote:r.remote,expected_local:r.local,idempotency_key:""});return}let t=r.local.object;if(r.remote.state==="absent"){e.push(_x(r,t,[]));return}let n=r.remote.object,i;if(t.revision!==n.revision){let s=_x(r,{...t,path:n.path},[]);e.push(s),i=s.key}t.path!==n.path&&e.push({key:`${r.identity}:move-remote`,depends_on_keys:i?[i]:[],command:"move_remote",reason:"local_change",source:i?{...n,revision:t.revision}:n,target_path:t.path,expected_source_owner:i?{state:"exact",object:{...n,revision:t.revision}}:r.remote,expected_target_owner:r.remote_target_owner,expected_local:r.local,idempotency_key:""})}function _x(r,e,t){return{key:`${r.identity}:put-remote`,depends_on_keys:t,command:"put_remote",reason:"local_change",target:e,payload_revision:nn(r.local).payload_revision,expected_remote:r.remote,expected_local:r.local,idempotency_key:""}}function b2(r){return{key:`${r.identity}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"remote_change",identity:r.identity,entity:r.entity,local:r.local,remote:r.remote,conflict_kind:r.local.state==="absent"||r.remote.state==="absent"?"delete_vs_change":"both_changed"}}function nn(r){if(r.state!=="exact")throw new Error("Planner invariant: expected exact object state.");return r.object}function ta(r){return r?{state:"exact",object:r}:{state:"absent"}}function v2(r,e,t){let n=t(`${r}\0${e.entity}\0${e.path}\0${e.revision}`);return`${n.slice(0,8)}-${n.slice(8,12)}-5${n.slice(13,16)}-8${n.slice(17,20)}-${n.slice(20,32)}`}function hm(r,e){return Zl(r)===Zl(e)}function w2(r,e){return r.state==="absent"||e.state==="absent"?r.state===e.state:r.object.entity===e.object.entity&&r.object.identity===e.object.identity&&r.object.path===e.object.path&&r.object.payload_revision===e.object.payload_revision&&r.object.size===e.object.size}function _2(r,e){return`${r.entity}\0${r.identity}`.localeCompare(`${e.entity}\0${e.identity}`)}function S2(r,e){return x2(`${r.path??""}\0${r.code}\0${r.message}`,`${e.path??""}\0${e.code}\0${e.message}`)}function x2(r,e){let t=new TextEncoder,n=t.encode(r),i=t.encode(e),s=Math.min(n.length,i.length);for(let o=0;o[c.record_id,c])),a=new Map(n.files.map(c=>[c.file_id,c]));return this.finish({kind:e,prior:t,authorityCursor:n.session.head,scopeEpoch:n.session.scope_epoch,local:s,remoteRecords:o,remoteResources:n.resources,remoteFiles:a,snapshot:n})}async inspectIncremental(e){let t=new Map;for(let[l,u]of Object.entries(e.records))u.record&&t.set(l,u.record);let n=new Map(Object.entries(e.files??{}).map(([l,u])=>[l,u.file])),i=new Map(Ex(e).map(l=>[A2(l),l])),s=e.cursor,o=e.cursor;for(;;){let l=s,u=await this.transport.changes(l,200);if(u.scope_epoch!==e.scope_epoch||u.cursoru.head||u.has_more&&u.cursor===l)throw new w("invalid_change_page","Authority returned an invalid change boundary.");if(u.reset_required)return this.inspectSnapshot("rebuild",e);for(let d of u.events){if(d.sequence<=o||d.sequence>u.cursor)throw new w("invalid_change_page","Authority change events are not strictly ordered.");o=d.sequence,this.applyRemoteObservation(i,t,n,d)}if(s=u.cursor,!u.has_more)break}let a=Object.values(e.resources??{}).map(l=>({path:l.path,kind:C2(l.path),revision:l.revision,document:""})),c=await this.inspectLocal(e,a,await this.currentRecordPathPolicy(e));return this.mode==="read_only"&&c.issues.some(l=>l.code==="invalid_frontmatter"&&l.blocking)?this.inspectSnapshot("rebuild",e):this.finish({kind:"incremental",prior:e,authorityCursor:s,scopeEpoch:e.scope_epoch,local:c,remoteRecords:t,remoteResources:[],remoteFiles:n,remoteRefs:[...i.values()]})}applyRemoteObservation(e,t,n,i){if(i.type==="put"){AS(i);let s=i.record.record_id;bi(this.selectiveSync,i.record.path)?(e.set(`record:${s}`,kx(i.record)),t.set(s,i.record)):(e.delete(`record:${s}`),t.delete(s));return}if(i.type==="remove"){e.delete(`record:${i.record_id}`),t.delete(i.record_id);return}if(i.type==="file_put"){xt(i.file);let s=i.file.file_id;Ul(this.selectiveSync,i.file)?(e.set(`file:${s}`,vm(i.file)),n.set(s,i.file)):(e.delete(`file:${s}`),n.delete(s));return}e.delete(`file:${i.file_id}`),n.delete(i.file_id)}async inspectLocal(e,t,n){let i=[],s=new Map,o=new Map,a=[],c=new Map(Object.entries(e?.records??{}).map(([h,m])=>[m.path,[h,m]])),l=new Map(Object.entries(e?.planned_conflicts??{}).filter(([,h])=>h.entity==="record"&&h.local.state==="exact").map(([h,m])=>[m.local.state==="exact"?m.local.object.path:"",h])),u=new Map(Object.entries(e?.local_bindings??{}).filter(([,h])=>h.entity==="record").map(([h,m])=>[m.path,h])),d=new Set([...Object.keys(e?.resources??{}),...t.map(h=>h.path)]);for(let h of d){let m=e?.resources?.[h],y;try{y=await this.fileSystem.read(h)}catch{a.push(Px(h)),m&&i.push({stable_identity:!0,object:On("resource",h,h,m.revision)});continue}if(y===null)continue;let g=y,b=_t(g,this.runtime);i.push({stable_identity:!0,object:On("resource",h,h,b)}),s.set(h,g);let v=t.find(S=>S.path===h);!m&&v&&v.revision!==b?a.push({code:"local_collision",message:`${h} differs locally from the exact authority document.`,path:h,blocking:!0}):m&&m.revision!==b&&a.push({code:"mirror_diverged",message:`Authority-owned resource ${h} changed locally.`,path:h,blocking:!0})}let f=new Set(Object.values(e?.records??{}).map(h=>h.path)),p=dx(await this.fileSystem.listMarkdown(d),n).filter(h=>bi(this.selectiveSync,h)||f.has(h));for(let h of p){let m=l.get(h),y=u.get(h),g=c.get(h),b=g?.[0],v=m??y??b??"",S;try{S=await this.fileSystem.readText(h)}catch{S=null}if(typeof S!="string"){a.push(S===null?Px(h):{code:"invalid_frontmatter",message:`Invalid frontmatter (${S.code}).`,path:h,blocking:!0});let x=S?.revision??g?.[1].revision;x&&i.push({stable_identity:v!=="",object:On("record",v,h,x)});continue}let _=S,E=_t(_,this.runtime);i.push({stable_identity:v!=="",object:On("record",v,h,E)}),s.set(h,_);let A=xS(_);A.outcome!=="parsed"&&a.push({code:"invalid_frontmatter",message:`Invalid frontmatter (${A.outcome}).`,path:h,blocking:!1})}if(this.selectiveSync.file_classes.length>0){if(!this.fileSystem.listBinary)throw new w("file_storage_unavailable","Selected files require binary enumeration.");let h=new Set(Object.values(e?.files??{}).map(v=>v.file.path)),m=new Map(Object.entries(e?.files??{}).map(([v,S])=>[S.file.path,[v,S]])),y=new Map(Object.entries(e?.planned_conflicts??{}).filter(([,v])=>v.entity==="file"&&v.local.state==="exact").map(([v,S])=>[S.local.state==="exact"?S.local.object.path:"",v])),g=new Map(Object.entries(e?.local_bindings??{}).filter(([,v])=>v.entity==="file").map(([v,S])=>[S.path,v])),b=(await this.fileSystem.listBinary(d)).filter(v=>US(this.selectiveSync,v)||h.has(v));for(let v of b){let S=await this.fileSystem.inspectBinary(v);if(!S)continue;let _=y.get(v),E=g.get(v),A=m.get(v),x=_??E??A?.[0]??"";i.push({stable_identity:x!=="",object:{entity:"file",identity:x,path:v,revision:A&&A[1].file.content_digest===S.content_digest?A[1].file.revision:S.content_digest,payload_revision:S.content_digest,size:S.size}}),o.set(v,S)}}try{ea([...d,...p,...o.keys()])}catch(h){let m=pi(h);a.push({code:hi(h,"sync_inspection_failed"),message:m.message,blocking:!0})}return{observations:i,documents:s,binary:o,issues:a}}async finish(e){let{prior:t,local:n}=e,i=e.remoteRefs??[...e.remoteResources.map(k2),...[...e.remoteRecords.values()].map(kx),...[...e.remoteFiles.values()].map(vm)],s=Sx({base:t?Ex(t):[],local:n.observations,remote:i},`${this.replicaId}\0${e.scopeEpoch}\0${t?.generation??0}`,this.runtime.digest);for(let d of s){let f=t?.planned_conflicts?.[d.identity];!f||f.entity!==d.entity||(d.frozen_conflict={local:d.local,remote:d.remote,conflict_kind:f.conflict_kind})}let o=[...n.issues];for(let d of s)(e.kind==="initial"||e.kind==="rebuild")&&d.base.state==="absent"&&d.local.state==="exact"&&d.remote.state==="exact"&&!Ax(d.local,d.remote)&&o.push({code:"local_collision",message:`${d.remote.object.path} differs locally from the exact authority object.`,path:d.remote.object.path,blocking:this.mode!=="read_write"||d.entity==="resource"}),d.remote.state==="exact"&&d.local_target_owner.state==="exact"&&d.remote.object.identity!==d.local_target_owner.object.identity&&o.push({code:"local_collision",message:`${d.remote.object.path} is owned by different local bytes.`,path:d.remote.object.path,blocking:!0});try{ea([...i.map(d=>d.path),...n.observations.map(({object:d})=>d.path)])}catch(d){let f=pi(d);o.push({code:hi(d,"sync_inspection_failed"),message:f.message,blocking:!0})}if(this.mode==="read_only"){for(let d of s)if(d.entity!=="resource"&&!Ax(d.local,d.base)){let f=P2(d.local,d.base);if(o.some(p=>p.blocking&&p.path===f))continue;o.push({code:"mirror_diverged",message:`${f} changed in a receive-only mirror.`,path:f,blocking:!0})}}let a=_i(gi(this.selectiveSync),this.runtime.digest),c={boundary:{engine_profile:Yl,protocol_profile:"exact_document_v1",planner_policy:Xl,projection_policy:Ql,replica_id:this.replicaId,scope_epoch:e.scopeEpoch,authority_cursor:e.authorityCursor,checkpoint:{generation:t?.generation??0,cursor:t?.cursor??null},selective_sync_fingerprint:a},mode:this.mode,kind:e.kind,selective_sync:gi(this.selectiveSync),objects:s,issues:$x(o)},l=gm(c,this.runtime.digest);if(this.fileSystem.pathKind){let d=new Map,f=p=>(d.has(p)||d.set(p,this.fileSystem.pathKind(p)),d.get(p));for(let p of l.actions){let h=p.command==="write_local"?p.target.path:p.command==="move_local"?p.target_path:null;if(h===null)continue;let m=await f(h)==="folder"?h:null,y=h.split("/");for(let g=1;m===null&&g[c.path,c]));for(let c of e.actions)if(c.command==="put_remote"){let l=c.expected_local.state==="exact"?c.expected_local.object.path:c.target.path;if(c.target.entity==="file"){let u=t.binary.get(l);if(!u)throw Si(c.action_id);await this.stageLocalBinary(l,u),o.local_files[c.action_id]={path:l,...u}}else{let u=t.documents.get(l);if(u===void 0||_t(u,this.runtime)!==c.payload_revision)throw Si(c.action_id);o.documents[c.action_id]=u}c.target.entity==="record"&&(o.mutations[c.action_id]={operation:"put",mutation_id:bm(c.action_id),replica_id:this.replicaId,scope_epoch:e.scope_epoch,record_id:c.target.identity,...c.expected_remote.state==="exact"?{base_revision:c.expected_remote.object.revision}:{},path:c.target.path,document:o.documents[c.action_id],created_at:this.runtime.now()})}else if(c.command==="write_local")if(c.target.entity==="record"){let l=n.get(c.target.identity);if(!l||l.revision!==c.target.revision)throw Si(c.action_id);o.records[c.action_id]=l}else if(c.target.entity==="resource"){let l=a.get(c.target.path);if(!l||l.revision!==c.target.revision)throw Si(c.action_id);o.resources[c.action_id]=l}else{let l=s.get(c.target.identity);if(!l||l.revision!==c.target.revision||!this.blobStore)throw Si(c.action_id);o.files[c.action_id]=l}else if(c.command==="record_conflict"&&c.remote.state==="exact")if(c.entity==="record"){let l=n.get(c.identity);if(!l||l.revision!==c.remote.object.revision)throw Si(c.action_id);o.records[c.action_id]=l}else{let l=s.get(c.identity);if(!l||l.revision!==c.remote.object.revision)throw Si(c.action_id);o.files[c.action_id]=l}else c.command==="move_remote"&&c.source.entity==="record"?o.mutations[c.action_id]={operation:"move",mutation_id:bm(c.action_id),replica_id:this.replicaId,scope_epoch:e.scope_epoch,record_id:c.source.identity,base_revision:c.expected_source_owner.state==="exact"?c.expected_source_owner.object.revision:c.source.revision,path:c.target_path,created_at:this.runtime.now()}:c.command==="delete_remote"&&c.target.entity==="record"&&(o.mutations[c.action_id]={operation:"delete",mutation_id:bm(c.action_id),replica_id:this.replicaId,scope_epoch:e.scope_epoch,record_id:c.target.identity,base_revision:c.expected_remote.state==="exact"?c.expected_remote.object.revision:c.target.revision,created_at:this.runtime.now()});return o}async stageLocalBinary(e,t){if(!this.blobStore||!this.fileSystem.readBinary)throw new w("writable_file_storage_unavailable","Writable files require streaming filesystem and blob-store adapters.");if(await this.blobStore.has(t.content_digest))return;let n=await this.fileSystem.readBinary(e);if(!n)throw new w("sync_plan_stale",`${e} disappeared during inspection.`);await this.blobStore.write(t.content_digest,zS(n,t,e))}};function $x(r){let e=new Map;for(let t of r)e.set(`${t.code}\0${t.path??""}\0${t.message}\0${t.blocking}`,t);return[...e.values()]}function Ex(r){return[...Object.entries(r.resources??{}).map(([e,t])=>On("resource",e,t.path,t.revision)),...Object.entries(r.records).map(([e,t])=>On("record",e,t.path,t.revision)),...Object.entries(r.files??{}).map(([e,t])=>vm({...t.file,file_id:e}))]}function kx(r){return On("record",r.record_id,r.path,r.revision)}function k2(r){return On("resource",r.path,r.path,r.revision)}function On(r,e,t,n){return{entity:r,identity:e,path:t,revision:n,payload_revision:n}}function vm(r){return{entity:"file",identity:r.file_id,path:r.path,revision:r.revision,payload_revision:r.content_digest,size:r.size}}function A2(r){return`${r.entity}:${r.identity}`}function Ax(r,e){return JSON.stringify(r)===JSON.stringify(e)}function P2(r,e){return r.state==="exact"?r.object.path:e.state==="exact"?e.object.path:"mirror"}function Si(r){return new w("sync_payload_incomplete",`Inspected action ${r} has no revision-bound payload.`)}function Px(r){return{code:"file_read_failed",message:"Could not read local file.",path:r,blocking:!0}}function C2(r){return r==="mdbase.yaml"?"configuration":r.endsWith("lock.yaml")?"lock":r.startsWith("_types/")?"type":r.startsWith("_contracts/")?"contract":r.startsWith("_views/")?"view":"schema"}function bm(r){let e=r.replace(/^sha256:/u,"");return`${e.slice(0,8)}-${e.slice(8,12)}-4${e.slice(13,16)}-8${e.slice(17,20)}-${e.slice(20,32)}`}var ra=class{fileSystem;runtime;constructor(e,t){this.fileSystem=e,this.runtime=t}async validate(e,t){if((t?.generation??0)!==e.checkpoint_generation||(t?.cursor??null)!==e.base_cursor||(t?.scope_epoch??e.scope_epoch)!==e.scope_epoch)throw hr("The durable checkpoint changed after inspection.");for(let n of e.actions)n.depends_on.length===0&&await this.validateAction(n)}async validateAction(e){switch(e.command){case"write_local":await this.validateExpected(e.expected_local),await this.validateExpectedAt(e.target.path,e.expected_path_owner);return;case"delete_local":await this.validateExpected(e.expected_local),await this.validateExpectedAt(e.target.path,e.expected_path_owner);return;case"move_local":await this.validateExpectedAt(e.source.path,e.expected_source_owner),await this.validateExpectedAt(e.target_path,e.expected_target_owner);return;case"put_remote":case"move_remote":await this.validateExpected(e.expected_local);return;case"delete_remote":await this.validateExpectedAt(e.target.path,e.expected_local);return;case"record_conflict":await this.validateExpected(e.local);return;case"clear_conflict":await this.validateExpected(e.expected_local);return;case"advance_checkpoint":return}}async validateExpectedAt(e,t){if(t.state==="absent"){if(await this.fileSystem.exists(e))throw hr(`${e} is no longer vacant.`);return}if(t.object.path!==e||!await rd(this.fileSystem,this.runtime,t.object,!0))throw hr(`${e} no longer has the inspected owner and bytes.`)}async validateExpected(e){if(e.state!=="absent"&&!await rd(this.fileSystem,this.runtime,e.object,!0))throw hr(`${e.object.path} no longer matches the inspected bytes.`)}};async function rd(r,e,t,n){if(t.entity==="file"){let s=await r.inspectBinary(t.path);return!!s&&s.content_digest===t.payload_revision&&(t.size===void 0||s.size===t.size)}let i;try{i=await r.readText(t.path)}catch(s){throw s instanceof w&&s.code==="file_read_failed"&&n?hr(s.message):s}return(typeof i=="string"?_t(i,e):i?.revision)===t.payload_revision}function hr(r){return new w("sync_plan_stale",r)}async function Cx(r,e,t,n){if(r?.batch){if(r.batch.plan.fingerprint!==e.fingerprint)throw new w("mirror_recovery_required","A different prepared sync batch must recover before this plan can apply.");return r}let i=r?structuredClone(r):R2(e.replica_id,e.scope_epoch,e.mode,e.selective_sync);i.scope_epoch=e.scope_epoch,i.selective_sync=e.selective_sync;let s=e.actions.at(-1);if(s?.command!=="advance_checkpoint")throw new w("invalid_sync_plan","Prepared plan has no checkpoint action.");return i.batch={phase:"prepared",plan:e,next_action:0,receipts:[],payloads:t,checkpoint_before:{generation:e.checkpoint_generation,cursor:e.base_cursor},checkpoint_after:s.next},await n.write(i),i}async function Mx(r,e){let t=lt(r);t.phase!=="effects_complete"&&(t.phase="applying",delete t.failure,await id(r,{type:"phase",plan_fingerprint:t.plan.fingerprint,phase:"applying"},e))}async function Rx(r,e,t){let n=lt(r),i=n.plan.actions[n.next_action];if(!i||i.action_id!==e.action_id)throw Ie("The durable sync receipt does not match the next prepared action.");let s={type:"receipt",plan_fingerprint:n.plan.fingerprint,receipt:structuredClone(e),delta:M2(r,i)};n.receipts.push(structuredClone(e)),n.next_action+=1,await id(r,s,t)}async function Tx(r,e){let t=lt(r),n=t.plan.actions[t.next_action];if(!n||n.command!=="advance_checkpoint")throw Ie("Sync effects cannot complete before the checkpoint action is next.");t.phase="effects_complete",await id(r,{type:"effects_complete",plan_fingerprint:t.plan.fingerprint},e)}async function nd(r,e,t,n){let i=lt(r);i.phase=e,i.failure=t,await id(r,{type:"phase",plan_fingerprint:i.plan.fingerprint,phase:e,failure:t},n)}async function id(r,e,t){t.appendJournal?await t.appendJournal(e):await t.write(r)}function M2(r,e){let t="identity"in e?e.identity:"target"in e?e.target.identity:"source"in e?e.source.identity:null;if(t===null)return{};let n="entity"in e?e.entity:"target"in e?e.target.entity:"source"in e?e.source.entity:null;if(n===null)return{};let i={planned_conflicts:{[t]:na(r.planned_conflicts?.[t])},local_bindings:{[t]:na(r.local_bindings?.[t])}};return n==="record"?i.records={[t]:na(r.records[t])}:n==="resource"?i.resources={[t]:na(r.resources?.[t])}:i.files={[t]:na(r.files?.[t])},i}function na(r){return r===void 0?null:structuredClone(r)}function lt(r){if(!r.batch)throw Ie("The mirror has no prepared sync batch.");return r.batch}async function wm(r,e){let t=lt(r);if(t.phase!=="blocked"||t.failure?.code!=="sync_plan_stale")throw new w("mirror_recovery_required","Only a stale batch at a durable action boundary can be abandoned.");delete r.batch,await e.write(r)}function R2(r,e,t,n){return{protocol_version:1,engine_version:3,generation:0,replica_id:r,scope_epoch:e,cursor:0,records:{},resources:{},files:{},selective_sync:n,mode:t,planned_conflicts:{}}}var od=class{ports;materializer;ownersByPath=new Map;pathsByOwner=new Map;constructor(e){this.ports=e,this.materializer=new $s(e.fileSystem,e.runtime,e.mode,e.blobStore)}async execute(e,t){let n=lt(e);this.indexPathOwners(e);let i=new Set(n.receipts.map(s=>s.action_id));for(await Mx(e,this.ports.store);n.next_action!i.has(a));if(o){let a={code:"invalid_mirror_state",message:`Action ${s.action_id} is missing dependency ${o}.`,action_id:s.action_id};return await nd(e,"blocked",a,this.ports.store),{status:"blocked",completed:n.next_action,failure:a}}try{let a=await this.dispatch(e,s);await Rx(e,a,this.ports.store),i.add(a.action_id),this.ports.onProgress?.(n.next_action,n.plan.actions.length-1)}catch(a){let c=t?.aborted===!0,l=c?{code:"sync_cancelled",message:"Sync paused during transfer.",action_id:s.action_id}:O2(a,s.action_id);return await nd(e,c?"cancelled":"blocked",l,this.ports.store),{status:c?"cancelled":l.code==="sync_plan_stale"?"stale":"blocked",completed:n.next_action,failure:l}}}throw Ie("Prepared plan has no checkpoint action.")}async dispatch(e,t){switch(t.command){case"write_local":return this.writeLocal(e,t);case"move_local":return this.moveLocal(e,t);case"delete_local":return this.deleteLocal(e,t);case"put_remote":return this.putRemote(e,t);case"move_remote":return this.moveRemote(e,t);case"delete_remote":return this.deleteRemote(e,t);case"record_conflict":{e.planned_conflicts??={};let n=t.identity in e.planned_conflicts?e.planned_conflicts[t.identity].ancestor_document:t.entity==="record"?e.records[t.identity]?.record?.document:void 0;return e.planned_conflicts[t.identity]={decision_id:Ix(t.entity,t.identity,t.local,t.remote,t.conflict_kind,this.ports.runtime.digest),entity:t.entity,local:t.local,remote:t.remote,conflict_kind:t.conflict_kind,...n===void 0?{}:{ancestor_document:n}},e.local_bindings??={},t.local.state==="exact"?e.local_bindings[t.identity]={entity:t.entity,path:t.local.object.path}:delete e.local_bindings[t.identity],this.rebaseConflict(e,t),{action_id:t.action_id,status:"conflicted"}}case"clear_conflict":return delete e.planned_conflicts?.[t.identity],delete e.local_bindings?.[t.identity],{action_id:t.action_id,status:"completed"};case"advance_checkpoint":throw Ie("The executor cannot dispatch checkpoint actions.")}}rebaseConflict(e,t){let n=lt(e).payloads;if(t.entity==="record"){if(t.remote.state==="absent"){delete e.records[t.identity];return}let s=n.records[t.action_id];if(!s||s.revision!==t.remote.object.revision)throw mr(t);sd(s,this.ports.runtime,s.revision),e.records[t.identity]={path:s.path,revision:s.revision,hash:t.local.state==="exact"?t.local.object.payload_revision.replace(/^sha256:/u,""):this.ports.runtime.digest(s.document),...this.ports.mode==="read_write"?{record:s}:{}};return}if(e.files??={},t.remote.state==="absent"){delete e.files[t.identity];return}let i=n.files[t.action_id];if(!i||i.revision!==t.remote.object.revision)throw mr(t);xt(i),e.files[t.identity]={file:i}}async writeLocal(e,t){let n=lt(e),i=await this.ports.fileSystem.exists(t.target.path);(!i||!await this.matchesRef(t.target))&&(await this.assertLocal(t.expected_local),await this.assertPathOwner(t.target.path,t.expected_path_owner,i));let s=n.payloads;if(t.target.entity==="record"){let a=s.records[t.action_id];if(!a||a.revision!==t.payload_revision)throw mr(t);return sd(a,this.ports.runtime,t.payload_revision),await this.materializer.put(e,a,{inspectionPreflighted:this.ports.mode==="read_only"&&n.plan.issues.some(c=>c.blocking&&c.code==="invalid_frontmatter"&&c.path===t.target.path)?1:!0}),this.installPathOwner(t.target),{action_id:t.action_id,status:"completed"}}if(t.target.entity==="resource"){let a=s.resources[t.action_id];if(!a||a.revision!==t.payload_revision||_t(a.document,this.ports.runtime)!==a.revision)throw mr(t);return await this.materializer.putResource(e,a,e),this.installPathOwner(t.target),{action_id:t.action_id,status:"completed"}}let o=s.files[t.action_id];if(!o||o.content_digest!==t.payload_revision||!this.ports.blobStore)throw mr(t);return await Vl(this.ports.transport,this.ports.blobStore,o),await this.materializer.putFile(e,o,e),this.installPathOwner(t.target),{action_id:t.action_id,status:"completed"}}async moveLocal(e,t){return await this.matchesRef({...t.source,path:t.target_path})||(await this.assertLocal(t.expected_source_owner),await this.assertPathOwner(t.target_path,t.expected_target_owner),await this.ports.fileSystem.move(t.source.path,t.target_path)),T2(e,t.source,t.target_path),this.installPathOwner({...t.source,path:t.target_path}),{action_id:t.action_id,status:"completed"}}async deleteLocal(e,t){if(await this.matchesRef(t.target))if(await this.assertLocal(t.expected_local),t.target.entity==="record")await this.materializer.remove(e,t.target.identity,t.target.path,{inspectionPreflighted:!0});else if(t.target.entity==="resource"){let i=e.resources?.[t.target.identity];if(i)await this.materializer.removeResource(e,t.target.path,i);else{let s=await this.ports.fileSystem.read(t.target.path);if(s!==null){if(_t(s,this.ports.runtime)!==t.target.payload_revision)throw hr(`${t.target.path} changed before removal.`);await this.ports.fileSystem.remove(t.target.path,s)}}}else await this.materializer.removeFile(e,t.target.identity);else I2(e,t.target);return this.removePathOwner(t.target),{action_id:t.action_id,status:"completed"}}async putRemote(e,t){let n=lt(e).payloads;if(t.target.entity==="record"){let a=n.mutations[t.action_id],c=n.documents[t.action_id];if(!a||a.operation!=="put"||c===void 0)throw mr(t);if(_t(c,this.ports.runtime)!==t.payload_revision)throw hr("Prepared local document payload no longer matches its revision.");let l=await this.ports.transport.mutate(a);return this.acceptRecordReceipt(e,t,l,c),_m(t.action_id,l)}if(t.target.entity==="resource")throw new w("invalid_sync_plan","Authority resources are not writable mirror objects.");let i=n.local_files[t.action_id];if(!i||!this.ports.blobStore||!this.ports.transport.uploadFile)throw mr(t);let s={protocol_version:1,type:"open_file_upload",transfer_id:xm(t.action_id),path:t.target.path,size:i.size,content_digest:i.content_digest,...i.media_type?{media_type:i.media_type}:{},...t.expected_remote.state==="exact"?{if_revision:t.expected_remote.object.revision}:{}},o=await this.ports.transport.uploadFile(s,this.ports.blobStore.read(i.content_digest));if(xt(o.file),o.transfer_id!==s.transfer_id||o.file.path!==t.target.path||o.file.content_digest!==i.content_digest||o.file.size!==i.size)throw Sm(t);return e.files??={},e.files[o.file.file_id]={file:o.file},delete e.local_bindings?.[t.target.identity],{action_id:t.action_id,status:"completed",file:o.file}}async moveRemote(e,t){if(t.source.entity==="record"){let s=lt(e).payloads.mutations[t.action_id];if(!s||s.operation!=="move")throw mr(t);let o=await this.ports.transport.mutate(s);return this.acceptRecordReceipt(e,t,o),_m(t.action_id,o)}if(t.source.entity==="resource"||!this.ports.transport.moveFile)throw new w("invalid_sync_plan","This remote move command is unsupported.");let n={protocol_version:1,type:"move_file",mutation_id:xm(t.action_id),file_id:t.source.identity,if_revision:this.dependencyFileRevision(e,t)??(t.expected_source_owner.state==="exact"?t.expected_source_owner.object.revision:t.source.revision),from_path:t.source.path,path:t.target_path,update_references:!1},i=await this.ports.transport.moveFile(n);if(xt(i.file),i.mutation_id!==n.mutation_id||i.file.file_id!==t.source.identity||i.file.path!==t.target_path)throw Sm(t);return e.files??={},e.files[t.source.identity]={file:i.file},delete e.local_bindings?.[t.source.identity],{action_id:t.action_id,status:"completed",file:i.file}}dependencyFileRevision(e,t){if(!t.revision_from_dependency)return;let n=lt(e).receipts.find(({action_id:i})=>i===t.revision_from_dependency);if(!n?.file||n.file.file_id!==t.source.identity)throw Ie(`Move ${t.action_id} is missing its dependency file receipt.`);return n.file.revision}async deleteRemote(e,t){if(t.target.entity==="record"){let s=lt(e).payloads.mutations[t.action_id];if(!s||s.operation!=="delete")throw mr(t);let o=await this.ports.transport.mutate(s);return this.acceptRecordReceipt(e,t,o),_m(t.action_id,o)}if(t.target.entity==="resource"||!this.ports.transport.deleteFile)throw new w("invalid_sync_plan","This remote delete command is unsupported.");let n={protocol_version:1,type:"delete_file",mutation_id:xm(t.action_id),file_id:t.target.identity,if_revision:t.expected_remote.state==="exact"?t.expected_remote.object.revision:t.target.revision,path:t.target.path},i=await this.ports.transport.deleteFile(n);if(i.mutation_id!==n.mutation_id||i.file_id!==t.target.identity||i.previous_path!==t.target.path)throw Sm(t);return delete e.files?.[t.target.identity],delete e.local_bindings?.[t.target.identity],{action_id:t.action_id,status:"completed"}}acceptRecordReceipt(e,t,n,i){let o=("target"in t?t.target:t.source).identity;if(n.status==="applied"||n.status==="previously_applied"){if(n.record){sd(n.record,this.ports.runtime,n.record.revision);let d=e.records[o];e.records[o]={path:n.record.path,revision:n.record.revision,hash:i===void 0?d?.hash??this.ports.runtime.digest(n.record.document):this.ports.runtime.digest(i),...this.ports.mode==="read_write"?{record:n.record}:{}}}else delete e.records[o];delete e.local_bindings?.[o];return}let a=n.status==="conflicted"?n.conflict.current:void 0;a&&sd(a,this.ports.runtime,a.revision);let c=a?{state:"exact",object:{entity:"record",identity:o,path:a.path,revision:a.revision,payload_revision:a.revision}}:t.command==="move_remote"?t.expected_source_owner:t.expected_remote;e.planned_conflicts??={};let l=n.status==="rejected"?"rejected":"both_changed",u=o in e.planned_conflicts?e.planned_conflicts[o].ancestor_document:e.records[o]?.record?.document;e.planned_conflicts[o]={decision_id:Ix("record",o,t.expected_local,c,l,this.ports.runtime.digest),entity:"record",local:t.expected_local,remote:c,conflict_kind:l,...u===void 0?{}:{ancestor_document:u}},e.local_bindings??={},t.expected_local.state==="exact"&&(e.local_bindings[o]={entity:"record",path:t.expected_local.object.path}),a&&(e.records[o]={path:a.path,revision:a.revision,hash:t.expected_local.state==="exact"?t.expected_local.object.payload_revision.replace(/^sha256:/u,""):this.ports.runtime.digest(a.document),...this.ports.mode==="read_write"?{record:a}:{}})}async assertLocal(e){if(e.state!=="absent"&&!await this.matchesRef(e.object))throw hr(`${e.object.path} no longer matches the inspected revision.`)}async assertPathOwner(e,t,n){let i=this.ownersByPath.get(e);if(t.state==="absent"){if(i||(n??await this.ports.fileSystem.exists(e)))throw hr(`${e} is no longer vacant.`);return}if(!i||i.entity!==t.object.entity||i.identity!==t.object.identity)throw hr(`${e} has a different path owner.`)}matchesRef(e){return rd(this.ports.fileSystem,this.ports.runtime,e,!1)}indexPathOwners(e){this.ownersByPath.clear(),this.pathsByOwner.clear();for(let[t,n]of Object.entries(e.records))this.installPathOwner({entity:"record",identity:t,path:n.path,revision:n.revision,payload_revision:`sha256:${n.hash}`});for(let[t,n]of Object.entries(e.resources??{}))this.installPathOwner({entity:"resource",identity:t,path:n.path,revision:n.revision,payload_revision:`sha256:${n.hash}`});for(let[t,n]of Object.entries(e.files??{}))this.installPathOwner({entity:"file",identity:t,path:n.file.path,revision:n.file.revision,payload_revision:n.file.content_digest,size:n.file.size})}installPathOwner(e){let t=`${e.entity}:${e.identity}`,n=this.pathsByOwner.get(t);n!==void 0&&this.ownersByPath.delete(n),this.ownersByPath.set(e.path,e),this.pathsByOwner.set(t,e.path)}removePathOwner(e){let t=`${e.entity}:${e.identity}`,n=this.pathsByOwner.get(t)??e.path;this.ownersByPath.delete(n),this.pathsByOwner.delete(t)}};function Ix(r,e,t,n,i,s){return _i({entity:r,identity:e,local:t,remote:n,conflict_kind:i},s)}function T2(r,e,t){if(e.entity==="record"){let n=r.records[e.identity];n&&(n.path=t,n.record&&(n.record.path=t))}else if(e.entity==="resource"){let n=r.resources?.[e.identity];n&&(n.path=t)}else{let n=r.files?.[e.identity];n&&(n.file.path=t)}}function I2(r,e){e.entity==="record"?delete r.records[e.identity]:e.entity==="resource"?delete r.resources?.[e.identity]:delete r.files?.[e.identity]}function sd(r,e,t){let n=Il(r);if(r.revision!==t||_t(n,e)!==t)throw new w("invalid_sync_response","Record receipt does not match its exact document revision.")}function _m(r,e){return e.status==="applied"||e.status==="previously_applied"?{action_id:r,status:"completed",...e.record?{record:e.record}:{}}:{action_id:r,status:e.status}}function mr(r){return new w("sync_payload_incomplete",`Prepared action ${r.action_id} has no exact payload capability.`)}function Sm(r){return new w("invalid_sync_response",`Authority receipt does not match prepared action ${r.action_id}.`)}function O2(r,e){let t=pi(r);return{code:hi(r,"sync_action_failed"),message:t.message,action_id:e}}function xm(r){let e=r.replace(/^sha256:/u,"");return`${e.slice(0,8)}-${e.slice(8,12)}-4${e.slice(13,16)}-8${e.slice(17,20)}-${e.slice(20,32)}`}async function Ox(r,e,t){let n=lt(r);if(n.phase!=="effects_complete")throw Ie("A checkpoint cannot advance before every prepared effect is durable.");let i=n.plan.actions[n.next_action];if(!i||i.command!=="advance_checkpoint")throw Ie("Prepared checkpoint action is missing.");if(i.expected.generation!==n.checkpoint_before.generation||i.expected.cursor!==n.checkpoint_before.cursor||i.next.generation!==n.checkpoint_after.generation||i.next.cursor!==n.checkpoint_after.cursor)throw Ie("Prepared checkpoint boundary is inconsistent.");let s=n.plan.fingerprint;return r.generation=i.next.generation,r.cursor=i.next.cursor??0,r.last_completed_plan=s,r.last_synced_at=e.now(),delete r.batch,await t.write(r),s}async function Dx(r,e,t,n){let[i]=e.actions;if(e.actions.length!==1||!i||i.command!=="advance_checkpoint"||i.expected.generation!==(r.generation??0)||i.expected.cursor!==r.cursor||i.next.generation!==(r.generation??0)+1||i.next.cursor!==e.authority_cursor||r.batch!==void 0)throw Ie("Empty checkpoint plan is inconsistent.");return r.generation=i.next.generation,r.cursor=i.next.cursor??0,r.last_completed_plan=e.fingerprint,r.last_synced_at=t.now(),await n.write(r),e.fingerprint}var xi=class{replicaId;transport;mode;stateStore;fileSystem;blobStore;selectiveSync;lease;runtime;materializer;onProgress;constructor(e,t,n,i="read_only"){this.replicaId=e,this.transport=t,this.mode=i,this.stateStore=n.stateStore,this.fileSystem=n.fileSystem,this.blobStore=n.blobStore,this.selectiveSync=gi(n.selectiveSync),this.lease=n.lease??new Qo,this.runtime=n.runtime??Zo,this.materializer=new $s(this.fileSystem,this.runtime,this.mode,this.blobStore),this.onProgress=n.onProgress}async sync(e={}){return this.lease.runExclusive(async()=>{let t=await this.readState();if(t?.batch?.phase==="blocked"&&t.batch.failure?.code==="sync_plan_stale"&&(await wm(t,this.journalStore()),t=await this.readState()),t?.batch)return this.executePrepared(t,e.signal);let n=await this.inspectDetailed(t);return this.applyInspection(n,e.signal)})}async inspect(){return this.lease.runExclusive(async()=>{let e=await this.readState();return e?.batch?.plan??(await this.inspectDetailed(e)).plan})}async apply(e,t={}){return this.lease.runExclusive(async()=>{let n=await this.readState();if(n?.batch){if(n.batch.plan.fingerprint!==e.fingerprint)throw new w("mirror_recovery_required","A different prepared plan must recover before this plan can apply.");return this.executePrepared(n,t.signal)}if(n?.last_completed_plan===e.fingerprint){let s=Wt(n,this.mode);return Ir(s.state==="attention"||e.summary.blocking_issues>0?"attention":"applied",e.summary.blocking_issues>0?e:{...e,issues:[]},s,0)}let i=await this.inspectDetailed(n);return i.plan.fingerprint!==e.fingerprint?Ir("stale",e,Wt(i.prior,this.mode),0,{code:"sync_plan_stale",message:"The local folder or authority changed. Inspect the sync plan again."}):this.applyInspection(i,t.signal)})}async applyInspection(e,t){let n=e.plan;if(n.issues.some(s=>s.blocking)&&n.actions.length===0)return Ir("attention",n,Wt(e.prior,this.mode),0);if(t?.aborted)return Ir("cancelled",n,Wt(e.prior,this.mode),0,{code:"sync_cancelled",message:"Sync cancelled before preparation."});try{await new ra(this.fileSystem,this.runtime).validate(n,e.prior)}catch(s){let o=pi(s),a=hi(s,"sync_revalidation_failed");return Ir(a==="sync_plan_stale"?"stale":"failed",n,Wt(e.prior,this.mode),0,{code:a,message:o.message})}if(n.actions.length===0)return Ir("applied",n,Wt(e.prior,this.mode),0);if(e.prior&&n.actions.length===1&&n.actions[0]?.command==="advance_checkpoint")return await Dx(e.prior,n,this.runtime,this.journalStore()),Ir("applied",n,Wt(e.prior,this.mode),0);let i=await Cx(e.prior??this.initialUnchangedState(e),n,e.durable_payloads,this.journalStore());return this.executePrepared(i,t)}async executePrepared(e,t){let n=e.batch,i=await new od({transport:this.transport,fileSystem:this.fileSystem,blobStore:this.blobStore,runtime:this.runtime,mode:this.mode,store:this.journalStore(),onProgress:(c,l)=>this.onProgress?.({phase:"applying",completed:c,total:l,done:c===l})}).execute(e,t);if(i.status!=="effects_complete"){i.status==="stale"&&await wm(e,this.journalStore());let c=Wt(e,this.mode);return Ir(i.status==="blocked"?"failed":i.status,n.plan,c,i.completed,i.failure)}let s=n.plan;await Ox(e,this.runtime,this.journalStore()),await this.pruneFileBlobs();let o=Wt(e,this.mode),a=o.conflicts.length>0||o.local_issues.length>0||s.summary.conflicts>0||s.summary.blocking_issues>0;return Ir(a?"attention":"applied",s,o,i.completed)}inspectDetailed(e){return new td(this.replicaId,this.transport,this.mode,this.fileSystem,this.blobStore,this.selectiveSync,this.runtime,()=>this.readState(),t=>this.currentRecordPathPolicy(t)).inspect(e)}initialUnchangedState(e){if(e.plan.kind!=="initial"||!e.snapshot)return null;let t=new Set(e.summary.objects.filter(o=>o.local.state==="exact"&&o.remote.state==="exact"&&JSON.stringify(o.local)===JSON.stringify(o.remote)).map(o=>`${o.entity}:${o.identity}`)),n={};for(let{record:o,hash:a}of e.snapshot.records)t.has(`record:${o.record_id}`)&&(n[o.record_id]={path:o.path,revision:o.revision,hash:a,...this.mode==="read_write"?{record:o}:{}});let i={};for(let o of e.snapshot.resources)t.has(`resource:${o.path}`)&&(i[o.path]={path:o.path,revision:o.revision,hash:this.runtime.digest(o.document)});let s={};for(let o of e.snapshot.files)t.has(`file:${o.file_id}`)&&(s[o.file_id]={file:o});return{protocol_version:1,engine_version:3,generation:0,replica_id:e.plan.replica_id,scope_epoch:e.plan.scope_epoch,cursor:0,records:n,resources:i,files:s,selective_sync:e.plan.selective_sync,mode:e.plan.mode,planned_conflicts:{}}}async review(){return this.lease.runExclusive(async()=>{let e=await this.readState(),t=Wt(e,this.mode),n=e?.batch?.plan??(await this.inspectDetailed(e)).plan,i=t.state==="not_initialized"&&!n.issues.some(s=>s.code==="invalid_frontmatter"||s.code==="file_read_failed")?t:gx(t,n);return{plan:n,status:i}})}async status(){return(await this.review()).status}async checkpointStatus(){return this.lease.runExclusive(()=>this.checkpointStatusUnlocked())}async checkpointStatusUnlocked(){return Wt(await this.readState(),this.mode)}async authorityPromotionManifest(){return this.lease.runExclusive(async()=>{if(this.mode!=="read_write")throw new w("promotion_requires_writable_mirror","Only a read-write mirror can prove an authority promotion source.");let e=await this.readState();if(!e)throw new w("mirror_not_initialized","Synchronize this mirror first.");if(e.batch||Object.keys(e.planned_conflicts??{}).length>0)throw new w("promotion_mirror_not_clean","Finish the prepared batch and resolve conflicts before promotion.");let t=await yx({state:e,selectiveSync:this.selectiveSync,fileSystem:this.fileSystem,pathPolicy:await this.currentRecordPathPolicy(e),digest:this.runtime.digest});if((await this.inspectDetailed(e)).plan.actions.some(i=>i.command!=="advance_checkpoint"))throw new w("promotion_mirror_not_clean","Synchronize this mirror immediately before promotion.");return t})}async previewInitialization(){let e=await this.inspect(),t=e.actions.filter(i=>i.command==="put_remote"||i.command==="move_remote"||i.command==="delete_remote"),n=e.actions.filter(i=>i.command==="write_local"||i.command==="move_local"||i.command==="delete_local");return{already_initialized:e.kind==="incremental",download_documents:n.filter(i=>"target"in i&&i.target.entity!=="file"||"source"in i&&i.source.entity!=="file").length,upload_documents:t.filter(i=>"target"in i&&i.target.entity==="record"||"source"in i&&i.source.entity==="record").length,unchanged_documents:0,download_files:n.filter(i=>"target"in i&&i.target.entity==="file"||"source"in i&&i.source.entity==="file").length,upload_files:t.filter(i=>"target"in i&&i.target.entity==="file"||"source"in i&&i.source.entity==="file").length,unchanged_files:0,collisions:e.issues.filter(i=>i.code==="local_collision"&&i.path).map(i=>i.path),local_issues:e.issues.filter(i=>i.code==="invalid_frontmatter"&&i.path!==void 0).map(i=>({code:"invalid_frontmatter",message:i.message,path:i.path}))}}async resolveConflict(e,t,n,i){await this.lease.runExclusive(()=>this.resolveConflictUnlocked(e,t,n,i))}async resolveConflictUnlocked(e,t,n,i){if(this.mode!=="read_write")throw new w("mirror_read_only","Receive-only mirrors have no writable conflicts.");let s=await this.readState();if(!s||s.batch)throw new w("mirror_recovery_required","Finish sync recovery before resolving conflicts.");let o=s.planned_conflicts?.[e];if(!o)throw new w("mirror_conflict_not_found","Writable mirror conflict was not found.");if((o.decision_id??"")!==t)throw ia();if(i!==void 0&&(n!=="local"||o.entity!=="record"||o.local.state!=="exact"))throw new w("invalid_conflict_resolution","A merged document requires an exact local record conflict.");let a=await Jl(this.replicaId,this.transport,this.mode,this.selectiveSync,this.runtime),c=o.entity==="record"?a.records.find(({record:f})=>f.record_id===e)?.record:void 0,l=o.entity==="file"?a.files.find(f=>f.file_id===e):void 0;if(!(o.entity==="record"?D2(o.remote,c):N2(o.remote,l)))throw ia();let d=new ra(this.fileSystem,this.runtime);if(o.local.state==="exact"?await d.validateExpected(o.local):o.remote.state==="exact"&&await d.validateExpectedAt(o.remote.object.path,o.local),n==="remote"&&(o.entity==="record"?await this.installRemoteRecord(s,e,c):await this.installRemoteFile(s,e,l)),i!==void 0){let f=o.local.object.path,p=await this.fileSystem.read(f);if(p===null||_t(p,this.runtime)!==o.local.object.payload_revision)throw ia();await this.fileSystem.write(f,i,p)}delete s.planned_conflicts?.[e],n==="remote"&&delete s.local_bindings?.[e],await this.writeState(s)}async installRemoteRecord(e,t,n){if(n){let o=e.planned_conflicts?.[t]?.local;await this.materializer.put(e,n,{...o?.state==="exact"&&o.object.path===n.path?{acceptedHash:o.object.payload_revision.replace(/^sha256:/u,"")}:{}});return}let i=e.planned_conflicts?.[t],s=i?.local.state==="exact"?i.local.object.path:e.records[t]?.path;if(s){let o=await this.fileSystem.read(s);if(o!==null){if(i?.local.state!=="exact"||_t(o,this.runtime)!==i.local.object.payload_revision)throw ia();await this.fileSystem.remove(s,o)}}delete e.records[t]}async installRemoteFile(e,t,n){if(n){if(!this.blobStore)throw new w("file_storage_unavailable","File resolution needs a blob store.");await Vl(this.transport,this.blobStore,n);let o=e.planned_conflicts?.[t],a=o?.local.state==="exact"?{content_digest:o.local.object.payload_revision,size:o.local.object.size??0}:void 0,c=e.local_bindings?.[t]?.path;await this.materializer.putFile(e,n,e,a),c&&c!==n.path&&await this.fileSystem.remove(c,a??null);return}let i=e.planned_conflicts?.[t],s=i?.local.state==="exact"?i.local.object.path:e.files?.[t]?.file.path;if(s){let o=await this.fileSystem.inspectBinary(s);if(o!==null){if(i?.local.state!=="exact"||o.content_digest!==i.local.object.payload_revision||i.local.object.size!==void 0&&o.size!==i.local.object.size)throw ia();await this.fileSystem.remove(s,o)}}delete e.files?.[t]}async readState(){let e=await this.stateStore.read();if(e===null)return null;try{return sx(e,this.replicaId,this.mode)}catch(t){throw t instanceof w?t:Ie("Mirror metadata is corrupt or belongs to another replica.")}}writeState(e){return this.stateStore.write(e)}journalStore(){let e=this.stateStore;return{write:t=>this.writeState(t),...e.appendJournal?{appendJournal:t=>e.appendJournal(t)}:{}}}async pruneFileBlobs(){if(!this.blobStore)return;let e=await this.readState();if(!e)return;let t=new Set;for(let n of Object.values(e.files??{}))t.add(n.file.content_digest);for(let n of Object.values(e.batch?.payloads.files??{}))t.add(n.content_digest);for(let n of Object.values(e.batch?.payloads.local_files??{}))t.add(n.content_digest);await this.blobStore.prune(t)}currentRecordPathPolicy(e){return this.materializer.recordPathPolicy(e)}};function D2(r,e){return r.state==="absent"?e===void 0:e!==void 0&&r.object.entity==="record"&&r.object.identity===e.record_id&&r.object.path===e.path&&r.object.revision===e.revision&&r.object.payload_revision===e.revision&&r.object.size===void 0}function N2(r,e){return r.state==="absent"?e===void 0:e!==void 0&&r.object.entity==="file"&&r.object.identity===e.file_id&&r.object.path===e.path&&r.object.revision===e.revision&&r.object.payload_revision===e.content_digest&&r.object.size===e.size}function ia(){return new w("mirror_conflict_stale","Local or hosted content changed after this conflict was recorded. Synchronize again before choosing a version.")}var sa=class extends xi{constructor(e,t,n){super(e,t,n,"read_write")}};Vt();function $m(r){let e=[...r.actions.flatMap(t=>t.command==="advance_checkpoint"?[]:[Em(t)]),...r.issues.map(t=>({kind:"document",path:t.path??"Sync engine",direction:"attention",action:t.blocking?"fix":"review",detail:t.message}))];return{plan:r,phase:r.kind,entries:e,cursor:r.base_cursor,remoteHead:r.authority_cursor,already_initialized:r.kind==="incremental",download_documents:r.actions.filter(t=>["write_local","move_local","delete_local"].includes(t.command)&&("target"in t?t.target.entity!=="file":"source"in t&&t.source.entity!=="file")).length,upload_documents:r.actions.filter(t=>["put_remote","move_remote","delete_remote"].includes(t.command)&&("target"in t?t.target.entity==="record":"source"in t&&t.source.entity==="record")).length,unchanged_documents:0,download_files:r.actions.filter(t=>["write_local","move_local","delete_local"].includes(t.command)&&("target"in t?t.target.entity==="file":"source"in t&&t.source.entity==="file")).length,upload_files:r.actions.filter(t=>["put_remote","move_remote","delete_remote"].includes(t.command)&&("target"in t?t.target.entity==="file":"source"in t&&t.source.entity==="file")).length,unchanged_files:0,collisions:r.issues.filter(t=>t.blocking&&t.code==="local_collision"&&t.path!==void 0).map(t=>t.path),local_issues:r.issues.filter(t=>["invalid_frontmatter","file_read_failed"].includes(t.code)&&t.path!==void 0).map(t=>({code:t.code,message:t.message,path:t.path}))}}function Em(r){if(r.command==="advance_checkpoint")throw new Error("Checkpoint actions are not preview entries.");if(r.command==="record_conflict"){let a=r.local.state==="exact"?r.local.object:r.remote.state==="exact"?r.remote.object:void 0;return{kind:r.entity==="file"?"file":"document",path:a?.path??r.identity,direction:"attention",action:"fix",detail:`Local and hosted ${r.entity} changes conflict (${r.conflict_kind.replace(/_/g," ")}).`,...a?.entity==="file"&&a.size!==void 0?{estimatedBytes:a.size}:{},...r.entity==="record"?{recordId:r.identity}:{fileId:r.identity}}}if(r.command==="clear_conflict"){let a=r.expected_local.state==="exact"?r.expected_local.object:r.expected_remote.state==="exact"?r.expected_remote.object:void 0;return{kind:r.entity==="file"?"file":"document",path:a?.path??r.identity,direction:"attention",action:"fix",detail:`Local and hosted ${r.entity} content now matches; clear the resolved conflict.`,...a?.entity==="file"&&a.size!==void 0?{estimatedBytes:a.size}:{},...r.entity==="record"?{recordId:r.identity}:{fileId:r.identity}}}let e=r.command.endsWith("_local"),t="target"in r?r.target:r.source,n=r.command==="move_local"||r.command==="move_remote"?r.target_path:t.path,i=r.command==="write_local"&&r.expected_local.state==="absent"||r.command==="put_remote"&&r.expected_remote.state==="absent",s=r.command.startsWith("move_")?"rename":r.command.startsWith("delete_")?"delete":i?"create":"update",o=s==="delete"?e?"Move this device's copy to trash.":"Delete from Connect.":s==="rename"?`Rename ${e?"on this device":"in Connect"} from ${t.path}.`:e?"Download from Connect.":"Upload to Connect.";return{kind:t.entity==="file"?"file":"document",path:n,direction:e?"download":"upload",action:s,detail:o,...t.entity==="file"&&t.size!==void 0?{estimatedBytes:t.size}:{},...t.entity==="record"?{recordId:t.identity}:{},...t.entity==="file"?{fileId:t.identity}:{}}}var L2={maxDeletions:20};function Nx(r,e=L2){let{plan:t}=r,n=[],i=t.actions.filter(o=>o.command!=="advance_checkpoint");t.kind==="rebuild"&&n.push("Mirror rebuild"),t.kind==="initial"&&i.some(o=>["put_remote","move_remote","delete_remote","delete_local"].includes(o.command))&&n.push("First sync"),t.summary.blocking_issues>0&&!i.length&&n.push("Blocking issues");let s=i.filter(o=>o.command==="delete_remote").length;return s>e.maxDeletions&&n.push(`${s} deletions`),{safe:n.length===0,reasons:n}}var Lx=require("obsidian");var Am=3e4,F2=64*1024;function Pm(r){return Am+Math.ceil(r/F2)*1e3}var Es=class extends w{constructor(e,t){super(e,t),this.name="NetworkError"}},Dn=class extends w{constructor(t,n,i,s){super(t,n);this.status=i;this.retryAfterMs=s;this.name="HttpStatusError"}},km=new Set([408,425,429,500,502,503,504]),j2=new Set(["network_unreachable","network_timeout","authority_unavailable","mirror_enrollment_unreachable","authority_adoption_unreachable"]);function ks(r){if(r instanceof Dn)return km.has(r.status);if(r&&typeof r=="object"){let e=r.status;if(typeof e=="number"&&km.has(e))return!0;let t=r.code;if(typeof t=="string"&&j2.has(t))return!0}return!1}function q2(r){return km.has(r)}var B2={attempts:4,baseDelayMs:500,maxDelayMs:3e4,sleep:z2,random:Math.random};function Cm(r,e,t){let n=Math.min(e.maxDelayMs,e.baseDelayMs*2**r),i=Math.round(n/2+e.random()*n/2);return t===void 0?i:Math.min(Math.max(i,t),6e4)}function Fx(r,e=B2){return async t=>{for(let n=0;;n+=1){K2(t.signal);let i;try{let s=await r(t);if(!q2(s.status)||n+1>=e.attempts)return s;i=aa(s.headers)}catch(s){if(W2(s)&&t.signal?.aborted||!ks(s)||n+1>=e.attempts)throw s}await e.sleep(Cm(n,e,i),t.signal)}}}function jx(r=U2()){return r?e=>V2(e,r.fetch,r.AbortController,r.headers):e=>H2(e)}function U2(){try{if(typeof require!="function")return null;let r=require("electron").remote,e=r?.net?.fetch,t=r?.getGlobal?.("AbortController"),n=r?.getGlobal?.("Object");return!e||!r?.net||typeof t!="function"||!n?null:{fetch:e.bind(r.net),AbortController:t,headers:i=>n.fromEntries(i)}}catch{return null}}async function V2(r,e,t=AbortController,n=i=>Object.fromEntries(i)){let{signal:i,check:s,dispose:o}=qx(r.signal,r.timeoutMs??Am),a=new t,c=()=>a.abort();i.aborted?c():i.addEventListener("abort",c,{once:!0});try{let l={...r.headers??{}};r.contentType&&!Object.keys(l).some(p=>p.toLowerCase()==="content-type")&&(l["content-type"]=r.contentType);let u,d;try{u=await e(r.url,{method:r.method,headers:l,body:r.body,signal:a.signal}),d=await u.arrayBuffer()}catch(p){throw ad(p,r.signal,i)}if(s(),i.aborted)throw ad(i.reason,r.signal,i);let f=new TextDecoder().decode(d);if(r.throw!==!1&&u.status>=400)throw new Dn(`http_${u.status}`,`Request failed with status ${u.status}`,u.status);return{status:u.status,headers:n(u.headers),arrayBuffer:d,json:G2(f),text:f}}finally{i.removeEventListener("abort",c),o()}}async function H2(r,e=t=>(0,Lx.requestUrl)(t)){let{signal:t,timeoutMs:n,...i}=r,{signal:s,check:o,dispose:a}=qx(t,n??Am),c=()=>{};try{return await new Promise((l,u)=>{let d=()=>u(ad(s.reason,t,s));if(s.aborted)return d();s.addEventListener("abort",d,{once:!0}),c=()=>s.removeEventListener("abort",d),e(i).then(f=>{o(),s.aborted?d():l(f)},f=>u(ad(f,t,s)))})}finally{c(),a()}}function aa(r){if(!r)return;let e=Object.entries(r).find(([i])=>i.toLowerCase()==="retry-after")?.[1];if(!e)return;let t=Number(e);if(Number.isFinite(t)&&t>=0)return t*1e3;let n=Date.parse(e);if(Number.isFinite(n))return Math.max(0,n-Date.now())}function z2(r,e){return new Promise((t,n)=>{if(e?.aborted)return n(oa());let i=window.setTimeout(()=>{e?.removeEventListener("abort",s),t()},r),s=()=>{window.clearTimeout(i),n(oa())};e?.addEventListener("abort",s,{once:!0})})}function K2(r){if(r?.aborted)throw oa()}function oa(){return new DOMException("Synchronization stopped.","AbortError")}function W2(r){return r instanceof DOMException&&r.name==="AbortError"}function qx(r,e){let t=new AbortController,n=Date.now()+e,i=()=>t.abort(oa());r?.aborted?i():r?.addEventListener("abort",i,{once:!0});let s=()=>t.abort(new Es("network_timeout","Connect did not respond in time.")),o=window.setTimeout(s,e);return{signal:t.signal,check:()=>{!t.signal.aborted&&Date.now()>=n&&s()},dispose:()=>{window.clearTimeout(o),r?.removeEventListener("abort",i)}}}function ad(r,e,t){if(e?.aborted)return oa();if(t.aborted)return t.reason instanceof Es?t.reason:new Es("network_timeout","Connect did not respond in time.");if(r instanceof w)return r;let n=r&&typeof r=="object"?r.status:void 0;if(typeof n=="number")return new Dn(`http_${n}`,`Request failed with status ${n}`,n);let i=r instanceof Error&&r.message?` (${r.message})`:"";return new Es("network_unreachable",`Connect could not be reached${i}.`)}function G2(r){if(!r.trim())return null;try{return JSON.parse(r)}catch{return null}}var Ux={maxAgeDays:90,maxFiles:5e3,maxRuns:1e3};function dd(r,e,t=new Date().toISOString()){return{id:crypto.randomUUID(),collectionId:r,startedAt:t,finishedAt:t,outcome:"event",files:[],...e}}function Vx(r){return r.summary!==void 0}function Hx(r,e,t){if(r.command==="advance_checkpoint")return null;let n=Em(r),i=r.command==="move_local"||r.command==="move_remote"?r.source.path:void 0;return{path:n.path,...i&&i!==n.path?{fromPath:i}:{},kind:n.kind,direction:n.direction,action:n.action,status:e.status,at:t,...e.failure?.message?{message:e.failure.message}:{}}}var cd=class{constructor(e,t){this.inner=e;this.onReceipt=t;this.seen=new Map}read(){return this.inner.read()}async write(e){await this.inner.write(e);let t=e.batch;if(!t)return;let n=t.plan.fingerprint,i=this.seen.get(n);if(i===void 0){this.seen.set(n,{receipts:t.receipts.length,actions:new Map(t.plan.actions.map(o=>[o.action_id,o]))});return}let s=i.receipts;i.receipts=t.receipts.length;for(let o of t.receipts.slice(s)){let a=i.actions.get(o.action_id);a&&this.onReceipt(a,o)}}};function zx(r){if(r.summary!==void 0)return r.summary;let e=i=>r.files.filter(s=>s.direction===i&&s.status==="completed").length;return[[e("download"),"downloaded"],[e("upload"),"uploaded"],[r.files.filter(i=>i.direction==="attention"||i.status==="conflicted").length,"conflicts"],[r.files.filter(i=>i.status==="rejected").length,"rejected"]].filter(([i])=>i>0).map(([i,s])=>`${i} ${s}`).join(" \xB7 ")||"No file changes"}function Kx(r,e){return r.flatMap(t=>t.summary!==void 0?t.path===e?[{run:t,file:J2(t)}]:[]:t.files.filter(n=>n.path===e||n.fromPath===e).map(n=>({run:t,file:n}))).sort((t,n)=>n.file.at.localeCompare(t.file.at))}function J2(r){return{path:r.path??"",kind:"document",direction:"attention",action:"review",status:"completed",at:r.finishedAt,...r.message?{message:r.message}:{}}}function Wx(r,e){let t=e.trim().toLowerCase();return t?r.flatMap(n=>{if(n.summary!==void 0)return n.path?.toLowerCase().includes(t)?[n]:[];let i=n.files.filter(s=>s.path.toLowerCase().includes(t)||s.fromPath?.toLowerCase().includes(t));return i.length?[{...n,files:i}]:[]}):[...r]}function Bx(r,e=Ux,t=Date.now()){let n=t-e.maxAgeDays*864e5,i=r.filter(a=>Date.parse(a.finishedAt)>=n),s=i.reduce((a,c)=>a+c.files.length,0),o=0;for(;(s>e.maxFiles||i.length-o>e.maxRuns)&&o0&&!r.endsWith(` +`);for(let n of r.split(` +`))if(n.trim())try{let i=JSON.parse(n);X2(i)?e.push(i):t=!0}catch{t=!0}return{runs:e.sort((n,i)=>n.finishedAt.localeCompare(i.finishedAt)),needsRepair:t}}function X2(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;return typeof e.id=="string"&&typeof e.collectionId=="string"&&typeof e.startedAt=="string"&&typeof e.finishedAt=="string"&&typeof e.outcome=="string"&&Array.isArray(e.files)&&e.files.every(t=>!!t&&typeof t.path=="string"&&typeof t.at=="string")}var ld=class{constructor(e,t,n=Ux){this.adapter=e;this.path=t;this.limits=n;this.runs=[];this.writes=Promise.resolve()}async load(){await this.enqueue(async()=>{let e=await this.adapter.exists(this.path)?await this.adapter.read(this.path):"",t=Y2(e),n=Bx(t.runs,this.limits);(t.needsRepair||n.length!==t.runs.length)&&await this.rewrite(n),this.runs=n})}list(e){return this.runs.filter(t=>e===void 0||t.collectionId===e)}append(e){return this.enqueue(async()=>{let t=Bx([...this.runs,e],this.limits);t.length!==this.runs.length+1||!await this.adapter.exists(this.path)?await this.rewrite(t):await this.adapter.append(this.path,`${JSON.stringify(e)} +`),this.runs=t})}acknowledge(e){return this.enqueue(async()=>{let t=this.runs.map(n=>n.id===e?{...n,needsAcknowledgement:!1}:n);await this.rewrite(t),this.runs=t})}clear(){return this.enqueue(async()=>{let e=this.runs.filter(t=>t.needsAcknowledgement);await this.rewrite(e),this.runs=e})}rewrite(e){return this.adapter.write(this.path,Q2(e))}enqueue(e){return this.writes=this.writes.then(e,e),this.writes}};function Q2(r){return r.map(e=>`${JSON.stringify(e)} +`).join("")}var Z2={create:"created",update:"updated",rename:"renamed",delete:"deleted",replace:"replaced",fix:"conflict",review:"needs review"};function Gx(r){let e=r.direction==="attention"?"Conflict recorded":`${r.direction==="download"?"Download":"Upload"} \xB7 ${Z2[r.action]}`;return r.status==="completed"?e:`${e} \xB7 ${r.status}`}function As(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 eF(r,e){let t=Object.create(null);for(let s=0;su));d++);if(di(c,"a")),Jx(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 Yx(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=tF(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 Xx(r,e,t,n){if(e===t||t===r)return{clean:!0,text:e};if(e===r)return{clean:!0,text:t};let i=[Mm(r),Mm(e),Mm(t)];if(i.every(d=>d===null)){let d=Im(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=Qx(s.close,o.close,a.close);if(c===null)return{clean:!1,reason:"Both versions changed the frontmatter fence."};let l=rF(s.frontmatter,o.frontmatter,a.frontmatter);if(l===null)return{clean:!1,reason:"Both versions changed the same field."};let u=Im(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 Tm(r){let e=r.split(` +`)+u}}function Mm(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 Om(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 Im(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(` -`),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(` +`),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=Yx(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 Tm(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 rF(r,e,t){let n=Tm(r),i=Tm(e),s=Tm(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)||o(i,s))return Om(r.join(` +`)};if(!n||!i||!s||o(n,i)||o(n,s)||o(i,s))return Im(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=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 +`)??null;let a=new Map;for(let l of new Set([...i.order,...s.order,...n.order])){let u=Qx(n.blocks.get(l),i.blocks.get(l),s.blocks.get(l));if(u===null)return null;u!==void 0&&a.set(l,u)}let c=i.order.filter(l=>a.has(l));for(let[l,u]of s.order.entries()){if(!a.has(u)||c.includes(u))continue;let d=s.order.slice(0,l).reverse().find(f=>c.includes(f));c.splice(d===void 0?0:c.indexOf(d)+1,0,u)}return c.flatMap(l=>(a.get(l)??"").split(` +`))}function Qx(r,e,t){return e===t?e:e===r?t:t===r?e:null}function Oe(r){return[...r.normalize("NFC")].map(e=>e.toLowerCase()).join("").normalize("NFC")}function Om(r){let e=new Map;for(let t of r){let n=Oe(t),i=e.get(n)??[];i.push(t),e.set(n,i)}return[...e.values()].filter(t=>t.length>1)}function Zx(r,e,t){let n=new Set([...e].map(Oe)),i=[],s=[];for(let o of[...r].sort((a,c)=>a[0]c[0]?1:0)){let a=[...o].sort();if(a.some(c=>t.has(c))||new Set(a).size!==a.length){s.push(a);continue}for(let c of a.slice(1)){let l=c.lastIndexOf("/"),u=c.lastIndexOf("."),d=u>l+1?c.slice(u):"",f=d?c.slice(0,-d.length):c,p=2,h;do h=`${f} (${p++})${d}`;while(n.has(Oe(h)));n.add(Oe(h)),i.push({from:c,to:h})}}return{renames:i,manual:s}}function o$(r){if(!Ze(r))return null;let e=r;if(!(e.version===1&&typeof e.syncUrl=="string"&&typeof e.controlUrl=="string"&&typeof e.collectionId=="string"&&typeof e.replicaId=="string"&&(e.mode==="read_only"||e.mode==="read_write")&&typeof e.name=="string"&&typeof e.enrollmentId=="string"&&typeof e.accessTokenExpiresAt=="string"&&(e.deviceId===void 0||typeof e.deviceId=="string")))return null;let t;try{t=Nr(e.selectiveSync)}catch{t=Nr()}return{...e,selectiveSync:t}}function nF(r){try{let e=(0,J.parseYaml)(r);return e===null||typeof e=="object"&&!Array.isArray(e)}catch{return!1}}var Nn=".mdbase/connect-role.json",ca=".mdbase/authority-adoption.json",la=".mdbase/authority-adoption-snapshot.json",iF="mdbase-obsidian-connect",Dr="mirrors",sF="mdbase-obsidian-connect-blobs",Ln="manifests",Fn="chunks",ud=1024*1024,oF=32*1024*1024,e$=2e3;function $i(r){if(!Number.isSafeInteger(r)||r<0||r>oF)throw new w("file_too_large","Binary sync supports files up to 32 MiB on this device. Exclude this file's folder to continue.")}var aF="mdbase-connect-access-",cF="mdbase-connect-refresh-",lF="mdbase-connect-adoption-",dF=300*1e3,uF=[".git",".trash",".mdbase"],fF=new Set([".git",".mdbase",".trash","node_modules","_contracts","_schemas","_types","_views"]),Dm=["image","audio","video","pdf","other"],fa=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ze(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Nr(r){let e=r?.file_classes??[];if(e.some(s=>!Dm.includes(s))||new Set(e).size!==e.length)throw new w("invalid_file_materialization","Selected file media classes must be valid and unique.");let t=[...e].sort((s,o)=>Dm.indexOf(s)-Dm.indexOf(o)),n=r?.excluded_folders??[];if(n.some(s=>typeof s!="string"||!s.trim()))throw new w("invalid_file_materialization","Excluded folders cannot be empty.");let i=n.map(s=>bn(s.trim())).sort((s,o)=>s.toLocaleLowerCase().localeCompare(o.toLocaleLowerCase()));if(i.length>100)throw new w("invalid_file_materialization","File sync supports at most 100 excluded folders.");if(new Set(i.map(s=>s.toLocaleLowerCase())).size!==i.length)throw new w("invalid_file_materialization","Excluded folders must be unique on portable filesystems.");for(let s of i)da(s,!0);return{file_classes:t,excluded_folders:i}}function a$(r){let e=r.includes(".")?r.slice(r.lastIndexOf(".")+1).toLowerCase():"";return["avif","bmp","gif","jpeg","jpg","png","svg","webp"].includes(e)?"image":["flac","m4a","mp3","oga","ogg","opus","wav"].includes(e)?"audio":["3gp","mkv","mov","mp4","webm"].includes(e)?"video":e==="pdf"?"pdf":"other"}function t$(r){if(r.conflicts.length)throw new w("authority_import_path_conflict",`${r.conflicts.length} filename conflicts prevent uploading. Review the paths in Sync and rename the conflicting files before retrying. Nothing was renamed or excluded.`)}function pF(r,e,t=a$(e)){if(!r.file_classes.includes(t))return!1;let n=(0,J.normalizePath)(e);return!r.excluded_folders.some(i=>n===i||n.startsWith(`${i}/`))}var hF=/\.(?:md|base)$/,c$=/\.(?:md|base)$/i;function da(r,e=!1){let t=bn(r),n=t.split("/");if(t.length>1024||!e&&c$.test(t)||n.some(i=>i.startsWith(".")||fF.has(i.toLowerCase())||/[<>"|?*]/u.test(i)||/^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/iu.test(i)))throw new w("invalid_file_path",`Collection file path ${t} is hidden, reserved, or non-portable.`);return t}async function pa(r){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",r));return{size:r.byteLength,content_digest:`sha256:${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}`}}async function Lm(r){let e=[],t=0;for await(let s of r){if(!(s instanceof Uint8Array))throw new w("file_integrity_failed","A binary stream returned an invalid chunk.");s.byteLength&&(t+=s.byteLength,$i(t),e.push(Uint8Array.from(s)))}let n=new Uint8Array(t),i=0;for(let s of e)n.set(s,i),i+=s.byteLength;return n.buffer}function r$(r){let e=r.includes(".")?r.slice(r.lastIndexOf(".")+1).toLowerCase():"";return{avif:"image/avif",gif:"image/gif",jpeg:"image/jpeg",jpg:"image/jpeg",png:"image/png",svg:"image/svg+xml",webp:"image/webp",flac:"audio/flac",m4a:"audio/mp4",mp3:"audio/mpeg",ogg:"audio/ogg",opus:"audio/opus",wav:"audio/wav",mov:"video/quicktime",mp4:"video/mp4",webm:"video/webm",pdf:"application/pdf"}[e]}async function mF(r,e){if(r!==void 0){if(!e)return JSON.stringify(r);if(r instanceof ArrayBuffer)return r;if(ArrayBuffer.isView(r))return Uint8Array.from(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)).buffer;if(r instanceof Blob)return r.arrayBuffer();throw new w("invalid_file_upload","The adoption upload body was not binary data.")}}function fd(r,e){if(e!=null)return e;if(!r.trim())return{};try{return JSON.parse(r)}catch{return{}}}var md=Fx(jx());function yF(){return async r=>{if(r.signal?.aborted)throw new DOMException("Enrollment cancelled.","AbortError");let e=await md({url:r.url,method:r.method,headers:r.headers,body:r.body===void 0?void 0:JSON.stringify(r.body),contentType:r.body===void 0?void 0:"application/json",throw:!1,signal:r.signal});if(r.signal?.aborted)throw new DOMException("Enrollment cancelled.","AbortError");return{status:e.status,body:fd(e.text,e.json),retryAfterMs:aa(e.headers)}}}function gF(){return async r=>{if(r.signal?.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");let e=await mF(r.body,r.rawBody),t=await md({url:r.url,method:r.method,headers:r.headers,body:e,contentType:e===void 0||r.rawBody?void 0:"application/json",throw:!1,signal:r.signal});if(r.signal?.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");return{status:t.status,body:fd(t.text,t.json),retryAfterMs:aa(t.headers),headers:t.headers}}}var Fm=class{constructor(e,t,n=md,i,s){this.send=n;this.onFileProgress=i;this.signal=s;this.credentials=typeof t=="string"?{token:()=>Promise.resolve(t)}:t;let o;try{o=new URL(e)}catch{throw new w("invalid_sync_url","Sync URL must be an absolute authority endpoint.")}if(!(o.protocol==="https:"||o.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(o.hostname))||o.username||o.password||o.search||o.hash||!/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/sync\/?$/i.test(o.pathname))throw new w("invalid_sync_url","Sync URL must identify one authority sync endpoint.");this.syncUrl=o.href.replace(/\/$/,""),this.filesUrl=this.syncUrl.replace(/\/sync$/u,"/files")}openSession(){return this.request("POST","sessions")}snapshot(e,t){let n=new URLSearchParams({snapshot_id:e});return t&&n.set("page",t),this.request("GET",`snapshot?${n.toString()}`)}fileSnapshot(e,t){let n=new URLSearchParams({snapshot_id:e});return t&&n.set("page",t),this.request("GET",`files/snapshot?${n.toString()}`)}async*downloadFile(e){$i(e.size);let t=crypto.randomUUID();try{let n=0;this.onFileProgress?.({direction:"download",path:e.path,transferredBytes:n,totalBytes:e.size});let i=await this.fileRequest("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:t,file_id:e.file_id,revision:e.revision});if(i.protocol_version!==1||i.type!=="file_transfer"||i.transfer_id!==t||i.direction!=="download"||i.protection!=="transport_tls"||i.total_size!==e.size||i.strategy.kind!=="object_ranges"||!Number.isSafeInteger(i.strategy.part_size)||i.strategy.part_size<=0)throw new w("invalid_sync_response","The authority returned an incompatible file download session.");let s=Math.ceil(e.size/i.strategy.part_size);for(let o=0;o=300)throw this.responseError(c,"file_download_failed");let l=n$(c.headers,"content-length");if(l!==void 0&&Number(l)!==a||c.arrayBuffer.byteLength!==a)throw new w("file_integrity_failed","Hosted authority returned a file part with the wrong length.");n+=a,this.onFileProgress?.({direction:"download",path:e.path,transferredBytes:n,totalBytes:e.size}),a&&(yield new Uint8Array(c.arrayBuffer))}}finally{await this.fileRequest("DELETE",`transfers/${encodeURIComponent(t)}`).catch(()=>{})}}async uploadFile(e,t){$i(e.size);let n=await this.fileRequest("POST","uploads",e);if(n.protocol_version!==1||n.type!=="file_transfer"||n.transfer_id!==e.transfer_id||n.direction!=="upload"||n.protection!=="transport_tls"||n.total_size!==e.size||!["object_put","object_multipart"].includes(n.strategy.kind))throw new w("invalid_sync_response","Authority returned an incompatible file upload session.");let i=n.strategy.kind==="object_multipart"?n.strategy.part_size:Math.max(1,e.size);if(!Number.isSafeInteger(i)||i<=0)throw new w("invalid_sync_response","Authority returned an invalid upload part size.");let s=new jm(t),o=Math.max(1,Math.ceil(e.size/i));if(n.received.some(d=>!Number.isSafeInteger(d)||d<0||d>=o)||new Set(n.received).size!==n.received.length)throw new w("invalid_sync_response","Authority returned invalid upload progress.");let a=n.uploaded_parts??[];if(a.some((d,f)=>!Number.isSafeInteger(d.part_number)||d.part_number<1||d.part_number>o||!d.etag||d.etag.length>255||f>0&&a[f-1].part_number>=d.part_number)||(n.strategy.kind==="object_multipart"?a.length!==n.received.length||a.some((d,f)=>d.part_number-1!==n.received[f]):a.length!==0))throw new w("invalid_sync_response","Authority returned invalid uploaded part receipts.");let c=n.received.reduce((d,f)=>{let p=f*i;return d+Math.min(i,Math.max(0,e.size-p))},0);if(this.onFileProgress?.({direction:"upload",path:e.path,transferredBytes:c,totalBytes:e.size}),n.received.length===o)return this.commitUpload(e.transfer_id,a);let l=new Set(n.received),u=Array.from({length:o},()=>{});for(let d of a)u[d.part_number-1]=d;for(let d=0;d=300)throw new Dn(y.status===429||y.status>=500?"authority_unavailable":"file_upload_failed",`Object storage returned HTTP ${y.status}.`,y.status);if(c+=p,this.onFileProgress?.({direction:"upload",path:e.path,transferredBytes:c,totalBytes:e.size}),n.strategy.kind==="object_multipart"){let g=n$(y.headers,"etag");if(!g)throw new w("invalid_sync_response","Object storage omitted a multipart ETag.");u[d]={part_number:d+1,etag:g}}}return await s.expectEnd(),this.commitUpload(e.transfer_id,u.filter(d=>d!==void 0))}async commitUpload(e,t){let n=await this.fileRequest("POST",`uploads/${encodeURIComponent(e)}/commit`,{protocol_version:1,type:"commit_file_upload",transfer_id:e,parts:t});if(n.protocol_version!==1||n.type!=="file_upload_committed"||n.transfer_id!==e)throw new w("invalid_sync_response","Authority returned an invalid file upload receipt.");return n}async moveFile(e){let t=await this.fileRequest("POST",`${encodeURIComponent(e.file_id)}/move`,e);if(t.protocol_version!==1||t.type!=="file_moved"||t.mutation_id!==e.mutation_id)throw new w("invalid_sync_response","Authority returned an invalid file move receipt.");return t}async deleteFile(e){let t=await this.fileRequest("POST",`${encodeURIComponent(e.file_id)}/delete`,e);if(t.protocol_version!==1||t.type!=="file_deleted"||t.mutation_id!==e.mutation_id||t.file_id!==e.file_id)throw new w("invalid_sync_response","Authority returned an invalid file delete receipt.");return t}changes(e,t=200){let n=new URLSearchParams({after:String(e),limit:String(t)});return this.request("GET",`changes?${n.toString()}`)}mutate(e){return this.request("POST","mutations",e)}async request(e,t,n){return this.requestAt(this.syncUrl,e,t,n)}async fileRequest(e,t,n){return this.requestAt(this.filesUrl,e,t,n)}async requestAt(e,t,n,i){let s=await this.authorized({url:`${e}/${n}`,method:t,body:i===void 0?void 0:JSON.stringify(i),contentType:i===void 0?void 0:"application/json",throw:!1}),o=fd(s.text,s.json);if(s.status<200||s.status>=300)throw this.responseError(s,"sync_failed");return o}async authorized(e){let t=s=>this.send({...e,headers:{authorization:`Bearer ${s}`},signal:this.signal}),n=await this.credentials.token(),i=await t(n);return i.status!==401||!this.credentials.renew?i:t(await this.credentials.renew(n))}responseError(e,t){let n=fd(e.text,e.json),i=Ze(n)&&Ze(n.error)?n.error:{},s=typeof i.code=="string"?i.code:e.status===401?"mirror_access_rejected":e.status===429||e.status>=500?"authority_unavailable":t;return new Dn(s,typeof i.message=="string"?i.message:`Sync request failed (${e.status}).`,e.status,aa(e.headers))}},jm=class{constructor(e){this.remainder=new Uint8Array;this.iterator=e[Symbol.asyncIterator]()}async read(e){let t=new Uint8Array(new ArrayBuffer(e)),n=0;for(;n!["authorization","cookie","host","proxy-authorization","content-length"].includes(e.toLowerCase())))}function n$(r,e){return Object.entries(r).find(([n])=>n.toLowerCase()===e.toLowerCase())?.[1]}function l$(r){return[r.configDir||".obsidian",...uF].map(t=>(0,J.normalizePath)(t).replace(/\/+$/,""))}function Tt(r,e){let t=bn(e),n=Oe(t);if(l$(r).some(i=>n===Oe(i)||n.startsWith(`${Oe(i)}/`)))throw new w("unsafe_mirror_path",`The collection authority attempted to write a reserved path: ${t}`);return t}function fe(r){if(r?.aborted)throw new DOMException("Synchronization cancelled.","AbortError")}function Ue(r,e){return r??new Error(`IndexedDB ${e} failed without an error detail.`)}function _F(r,e){let t=async a=>{fe(e);let c=await a();return fe(e),c},n=async function*(a){fe(e);for await(let c of a)fe(e),yield c,fe(e);fe(e)},i=r.uploadFile?.bind(r),s=r.moveFile?.bind(r),o=r.deleteFile?.bind(r);return{openSession:()=>t(()=>r.openSession()),snapshot:(a,c)=>t(()=>r.snapshot(a,c)),fileSnapshot:(a,c)=>t(()=>r.fileSnapshot(a,c)),downloadFile:a=>n(r.downloadFile(a)),...i?{uploadFile:(a,c)=>t(()=>i(a,n(c)))}:{},...s?{moveFile:a=>t(()=>s(a))}:{},...o?{deleteFile:a=>t(()=>o(a))}:{},changes:(a,c)=>t(()=>r.changes(a,c)),mutate:a=>t(()=>r.mutate(a))}}async function Ps(r,e){let t=(0,J.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let n="";for(let i of t.split("/")){n=n?`${n}/${i}`:i;let s=r.getAbstractFileByPath(n);if(!(s instanceof J.TFolder)){if(s)throw new w("mirror_path_collision",`A file blocks the mirror folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}var qm=class{constructor(e,t=s=>e.delete(s,!0),n=()=>{},i=()=>{}){this.vault=e;this.trashFile=t;this.assertActive=n;this.observeWrite=i}async cachedEntry(e){let t=this.vault.getAbstractFileByPath(e);if(t||!await this.vault.adapter.exists(e))return t;let n=e.lastIndexOf("/"),i=await this.vault.adapter.list(n<0?"":e.slice(0,n)),s=Oe(e),o=[...i.files,...i.folders].filter(l=>Oe(l)===s);if(o.length!==1)throw new w("mirror_path_collision",`More than one physical spelling blocks ${e}.`);let a=this.vault.getAbstractFileByPath(o[0]);if(a)return a;let c=this.vault.getAllLoadedFiles().filter(l=>Oe(l.path)===s);if(c.length>1)throw new w("mirror_path_collision",`More than one cached spelling blocks ${e}.`);return c[0]??null}async exists(e){let t=Tt(this.vault,e);return this.vault.getAbstractFileByPath(t)!==null||await this.vault.adapter.exists(t)}async read(e){let t=await this.readText(e);if(t===null||typeof t=="string")return t;throw new w(t.code,t.reason)}async readText(e){let t=Tt(this.vault,e);if(this.vault.getAbstractFileByPath(t)instanceof J.TFolder)throw new w("mirror_path_collision",`Expected a file at ${t}.`);let i;try{i=await this.vault.adapter.readBinary(t)}catch{try{if(!await this.vault.adapter.exists(t))return null}catch{}throw new w("file_read_failed",`Could not read ${t}.`)}try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(i)}catch{return{kind:"invalid",code:"invalid_utf8",reason:"File is not valid UTF-8.",revision:(await pa(i)).content_digest}}}async pathKind(e){let t=Tt(this.vault,e);return(await this.vault.adapter.stat(t))?.type??null}async write(e,t,n){let i=Tt(this.vault,e),s=()=>new w("sync_plan_stale",`${i} changed before it could be written. Review sync again.`),o=n;if(o===void 0){let l=await this.readText(i);if(typeof l=="string"||l===null)o=l;else{let u=await this.vault.adapter.readBinary(i);if((await pa(u)).content_digest!==l.revision)throw s();o=new TextDecoder("utf-8",{ignoreBOM:!0}).decode(u)}}let a=i.lastIndexOf("/");a>=0&&await Ps(this.vault,i.slice(0,a));let c=await this.cachedEntry(i);if(c instanceof J.TFolder)throw new w("mirror_path_collision",`A folder blocks the mirror file ${i}.`);if(this.assertActive(),c instanceof J.TFile){let l=c.path;await this.vault.process(c,u=>{if(this.assertActive(),c.path!==l||this.vault.getAbstractFileByPath(l)!==c||u!==o&&u!==t)throw s();return this.observeWrite(i),this.observeWrite(l),t})}else{if(o!==null)throw s();this.observeWrite(i),await this.vault.create(i,t)}}async move(e,t){let n=Tt(this.vault,e),i=Tt(this.vault,t),s=await this.cachedEntry(n);if(!(s instanceof J.TFile))throw new w("mirror_path_collision",`Expected a file at ${n}.`);let o=await this.cachedEntry(i);if(!(o===s&&Oe(n)===Oe(i))&&(o!==null||await this.vault.adapter.exists(i)))throw new w("mirror_path_collision",`A file or folder blocks the mirror path ${i}.`);let c=i.lastIndexOf("/");c>=0&&await Ps(this.vault,i.slice(0,c)),this.assertActive(),this.observeWrite(n),this.observeWrite(s.path),this.observeWrite(i),await this.vault.rename(s,i)}async remove(e,t){let n=Tt(this.vault,e);if(t!==void 0){let s;if(t===null)s=!await this.exists(n);else if(typeof t=="string")s=await this.read(n)===t;else{let o=await this.inspectBinary(n);s=o?.content_digest===t.content_digest&&o?.size===t.size}if(!s)throw new w("sync_plan_stale",`${n} changed before it could be removed. Review sync again.`)}let i=await this.cachedEntry(n);if(i!=null){if(!(i instanceof J.TFile))throw new w("mirror_path_collision",`Expected a file at ${n}.`);this.assertActive(),this.observeWrite(n),this.observeWrite(i.path),await this.trashFile(i)}}async listMarkdown(e){return hd(this.vault).map(t=>(0,J.normalizePath)(t.path)).filter(t=>hF.test(t)&&!e.has(t)).filter(t=>!l$(this.vault).some(n=>Oe(t)===Oe(n)||Oe(t).startsWith(`${Oe(n)}/`))).sort()}async inspectBinary(e){let t=da(Tt(this.vault,e)),n=await this.cachedEntry(t);if(n==null)return null;if(!(n instanceof J.TFile))throw new w("mirror_path_collision",`Expected a file at ${t}.`);$i(n.stat.size);let i=await this.vault.readBinary(n);return $i(i.byteLength),pa(i)}async writeBinary(e,t,n){let i=da(Tt(this.vault,e)),s=n===void 0?await this.inspectBinary(i):n,o=await Lm(t),a=i.lastIndexOf("/");a>=0&&await Ps(this.vault,i.slice(0,a));let c=await this.inspectBinary(i);if(c?.content_digest!==s?.content_digest||c?.size!==s?.size)throw new w("sync_plan_stale",`${i} changed before it could be written. Review sync again.`);let l=await this.cachedEntry(i);if(l instanceof J.TFolder)throw new w("mirror_path_collision",`A folder blocks the mirror file ${i}.`);this.assertActive(),this.observeWrite(i),l instanceof J.TFile?(this.observeWrite(l.path),await this.vault.modifyBinary(l,o)):await this.vault.createBinary(i,o)}async listBinary(e){return hd(this.vault).map(t=>(0,J.normalizePath)(t.path)).filter(t=>!c$.test(t)&&!e.has(t)).filter(t=>{try{return da(Tt(this.vault,t)),!0}catch{return!1}}).sort()}async readBinary(e){let t=da(Tt(this.vault,e)),n=await this.cachedEntry(t);if(n==null)return null;if(!(n instanceof J.TFile))throw new w("mirror_path_collision",`Expected a file at ${t}.`);$i(n.stat.size);let i=new Uint8Array(await this.vault.readBinary(n));return $i(i.byteLength),(async function*(){for(let s=0;s{}),a}n&&n.stage!==i&&await this.removeStage(n.stage,n.chunks).catch(()=>{})}async remove(e){let t=await this.manifest(e);await this.delete(Ln,this.manifestKey(e)),t&&await this.removeStage(t.stage,t.chunks)}async prune(e){let t=await this.open(),n=await new Promise((o,a)=>{let c=[],l=t.transaction(Ln,"readonly").objectStore(Ln).openCursor();l.onsuccess=()=>{let u=l.result;if(!u)return o(c);c.push([u.key,u.value]),u.continue()},l.onerror=()=>a(Ue(l.error,"manifest cursor"))}),i=new Set;for(let[o,a]of n)!Array.isArray(o)||o[0]!==this.namespace||typeof o[1]=="string"&&e.has(o[1])||(await this.delete(Ln,o),await this.removeStage(a.stage,a.chunks));for(let[o,a]of n)Array.isArray(o)&&o[0]===this.namespace&&typeof o[1]=="string"&&e.has(o[1])&&i.add(a.stage);let s=await new Promise((o,a)=>{let c=[],l=t.transaction(Fn,"readonly").objectStore(Fn).openKeyCursor();l.onsuccess=()=>{let u=l.result;if(!u)return o(c);let d=u.key,f=Array.isArray(d)&&typeof d[1]=="string"?d[1]:null;Array.isArray(d)&&d[0]===this.namespace&&(f===null||!i.has(f))&&c.push(d),u.continue()},l.onerror=()=>a(Ue(l.error,"chunk cursor"))});for(let o of s)await this.delete(Fn,o)}manifest(e){return this.get(Ln,this.manifestKey(e))}manifestKey(e){return[this.namespace,e]}chunkKey(e,t){return[this.namespace,e,t]}async removeStage(e,t){for(let n=0;n{let o=n.transaction(e,"readonly").objectStore(e).get(t);o.onsuccess=()=>i(o.result??null),o.onerror=()=>s(Ue(o.error,`read from ${e}`))})}async put(e,t,n){let i=await this.open();await new Promise((s,o)=>{let a=i.transaction(e,"readwrite");a.objectStore(e).put(n,t),a.oncomplete=()=>s(),a.onerror=()=>o(Ue(a.error,`write to ${e}`)),a.onabort=()=>o(Ue(a.error,`write to ${e}`))})}async delete(e,t){let n=await this.open();await new Promise((i,s)=>{let o=n.transaction(e,"readwrite");o.objectStore(e).delete(t),o.oncomplete=()=>i(),o.onerror=()=>s(Ue(o.error,`delete from ${e}`)),o.onabort=()=>s(Ue(o.error,`delete from ${e}`))})}close(){this.database?.then(e=>e.close(),()=>{}),this.database=null}open(){if(typeof indexedDB>"u")throw new w("storage_unavailable","IndexedDB is required for binary file sync.");if(this.database)return this.database;let e=new Promise((t,n)=>{let i=indexedDB.open(sF,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Ln)||i.result.createObjectStore(Ln),i.result.objectStoreNames.contains(Fn)||i.result.createObjectStore(Fn)},i.onerror=()=>n(Ue(i.error,"binary store open")),i.onsuccess=()=>{let s=i.result,o=()=>{this.database===e&&(this.database=null)};s.onclose=o,s.onversionchange=()=>{s.close(),o()},t(s)}});return this.database=e,e.catch(()=>{this.database===e&&(this.database=null)}),e}};function ua(r){return r?{cursor:r.cursor,scope_epoch:r.scope_epoch,recovery_required:!!r.batch}:null}var Um=class{constructor(e){this.key=e;this.database=null;this.checkpointReady=!1}get checkpointKey(){return[this.key,"checkpoint"]}async read(){let e=await this.open(),t=!this.checkpointReady;return new Promise((n,i)=>{let s=e.transaction(Dr,t?"readwrite":"readonly"),o=s.objectStore(Dr),a=o.get(this.key),c=null;a.onsuccess=()=>{c=a.result??null,t&&(c?o.put(ua(c),this.checkpointKey):o.delete(this.checkpointKey))},s.oncomplete=()=>{t&&(this.checkpointReady=!0),n(c)},s.onerror=()=>i(Ue(s.error,"mirror state read")),s.onabort=()=>i(Ue(s.error,"mirror state read"))})}async readCheckpoint(){if(!this.checkpointReady)return ua(await this.read());let e=await this.open(),t=await new Promise((n,i)=>{let s=e.transaction(Dr,"readonly"),o=s.objectStore(Dr),a=o.get(this.checkpointKey),c=o.getKey(this.key);s.oncomplete=()=>n({exists:c.result!==void 0,checkpoint:a.result??null}),s.onerror=()=>i(Ue(s.error,"mirror checkpoint read")),s.onabort=()=>i(Ue(s.error,"mirror checkpoint read"))});return t.exists?t.checkpoint?t.checkpoint:(this.checkpointReady=!1,ua(await this.read())):null}async write(e){let t=await this.open();await new Promise((n,i)=>{let s=t.transaction(Dr,"readwrite"),o=s.objectStore(Dr);o.put(e,this.key),o.put(ua(e),this.checkpointKey),s.oncomplete=()=>n(),s.onerror=()=>i(Ue(s.error,"mirror state write")),s.onabort=()=>i(Ue(s.error,"mirror state write"))}),this.checkpointReady=!0}async clear(){let e=await this.open();await new Promise((t,n)=>{let i=e.transaction(Dr,"readwrite"),s=i.objectStore(Dr);s.delete(this.key),s.delete(this.checkpointKey),i.oncomplete=()=>t(),i.onerror=()=>n(Ue(i.error,"mirror state clear")),i.onabort=()=>n(Ue(i.error,"mirror state clear"))}),this.checkpointReady=!0}close(){this.database?.then(e=>e.close(),()=>{}),this.database=null,this.checkpointReady=!1}open(){if(typeof indexedDB>"u")throw new w("storage_unavailable","IndexedDB is required for persistent mirror state.");if(this.database)return this.database;let e=new Promise((t,n)=>{let i=indexedDB.open(iF,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Dr)||i.result.createObjectStore(Dr)},i.onerror=()=>n(Ue(i.error,"mirror state store open")),i.onsuccess=()=>{let s=i.result,o=()=>{this.database===e&&(this.database=null)};s.onclose=o,s.onversionchange=()=>{s.close(),o()},t(s)}});return this.database=e,e.catch(()=>{this.database===e&&(this.database=null)}),e}},Vm=class r{constructor(e){this.key=e}static{this.active=new Set}async runExclusive(e){let t=typeof navigator>"u"?null:navigator.locks;if(t)return t.request(`mdbase-mirror:${this.key}`,{ifAvailable:!0},async n=>{if(!n)throw new w("mirror_busy","Another window is synchronizing this vault.");return e()});if(r.active.has(this.key))throw new w("mirror_busy","A mirror operation is already running for this vault.");r.active.add(this.key);try{return await e()}finally{r.active.delete(this.key)}}},pd=class{constructor(e,t,n={}){this.app=e;this.settingsHost=t;this.options=n;this.disposed=!1;this.lifetime=new AbortController;this.stateStores=new Map;this.blobStores=new Map;this.progress=null;this.fileProgress=null;this.syncAbort=null;this.statusRequest=null;this.mirrorOperationTail=Promise.resolve();this.adoptionMarker=null;this.adoptionBusy=!1;this.engineWrites=new Map;this.renewal=null;this.fileSystem=n.fileSystem??new qm(e.vault,i=>e.fileManager.trashFile(i),()=>this.assertActive(),i=>this.noteEngineWrite(i)),this.enrollmentClient=n.enrollmentClient??new jl({request:yF()}),this.adoptionClient=n.adoptionClient??new Kl({request:gF()})}dispose(){this.disposed=!0,this.lifetime.abort(),this.cancelSync();for(let e of this.stateStores.values())e.close();for(let e of this.blobStores.values())e.close();this.stateStores.clear(),this.blobStores.clear()}async withLifetime(e,t){this.assertActive();let n=new AbortController,i=()=>n.abort();this.lifetime.signal.addEventListener("abort",i,{once:!0}),e?.addEventListener("abort",i,{once:!0}),e?.aborted&&n.abort();try{return fe(n.signal),await t(n.signal)}finally{this.lifetime.signal.removeEventListener("abort",i),e?.removeEventListener("abort",i)}}assertActive(){if(this.disposed)throw new DOMException("Plugin unloaded.","AbortError")}async withAdoptionOperation(e,t){if(this.adoptionBusy)throw new w("authority_adoption_busy","Stop the current move before changing its setup.");this.adoptionBusy=!0;try{return await this.withLifetime(e,t)}finally{this.adoptionBusy=!1}}async initialize(){this.adoptionMarker=await this.readAdoptionMarker();let e=this.settingsHost.getMirrorProfile();if(this.adoptionMarker&&e){if(this.adoptionMarker.phase==="adopted"&&this.adoptionMarker.session.requested.collectionId===e.collectionId){await this.assertMirror(e.collectionId),await this.clearAdoptionCheckpoint(this.adoptionMarker.session.adoptionId);return}throw new w("authority_adoption_state_conflict","This vault contains both an authority-adoption checkpoint and a mirror profile.")}}getProgress(){return this.progress?{...this.progress}:null}getFileProgress(){return this.fileProgress?{...this.fileProgress}:null}getAdoptionMarker(){return this.adoptionMarker?JSON.parse(JSON.stringify(this.adoptionMarker)):null}getAdoptionRecovery(){let e=this.adoptionMarker;if(!e)return null;try{if(this.app.secretStorage.getSecret(this.adoptionSecretId(e.session.adoptionId)))return null}catch{}let t=["waiting_for_approval","uploading"].includes(e.phase);return{canReset:t&&Date.parse(e.session.expiresAt)<=Date.now(),canReconnect:!t}}async resetExpiredAdoption(){return this.withAdoptionOperation(void 0,async()=>{let e=await this.readAdoptionMarker();if(e?.session.adoptionId!==this.adoptionMarker?.session.adoptionId)throw new w("authority_adoption_state_conflict","Move setup changed. Reopen Sync before recovering it.");if(this.adoptionMarker=e,!e||this.settingsHost.getMirrorProfile()||await this.app.vault.adapter.exists(Nn)||!this.getAdoptionRecovery()?.canReset)throw new w("authority_adoption_reset_unsafe","Only an expired move that never froze this vault can be reset locally.");await this.clearAdoptionCheckpoint(e.session.adoptionId)})}async reconnectAdoption(e){return this.withAdoptionOperation(e.signal,async t=>{let n=this.adoptionMarker;if(!n||!this.getAdoptionRecovery()?.canReconnect||this.settingsHost.getMirrorProfile())throw new w("authority_adoption_reconnect_unsafe","This move does not require hosted recovery.");let i=await this.enrollmentClient.enroll({controlUrl:n.session.controlUrl,collectionId:n.session.requested.collectionId,mirrorName:n.session.requested.mirrorName??n.session.requested.sourceName,mode:"read_write"},{...e,signal:t});if(i.collectionId!==n.session.requested.collectionId||i.mode!=="read_write")throw new w("authority_adoption_state_conflict","Connect approved a different collection or access mode; this vault remains protected.");return fe(t),await this.updateAdoptionPhase("adopted"),this.persistAdoptedMirror(n.session,i)})}getSelectiveSync(){return Nr(this.settingsHost.getMirrorProfile()?.selectiveSync??this.adoptionMarker?.selective_sync)}async configureSelectiveSync(e){let t=this.requireProfile();await this.settingsHost.saveMirrorProfile({...t,selectiveSync:Nr(e)})}assertLocalAuthorityWritable(){if(this.assertActive(),this.adoptionMarker&&["fenced","activating","adopted"].includes(this.adoptionMarker.phase))throw new w("local_authority_fenced",this.adoptionMarker.phase==="adopted"?"Hosted mdbase is now authoritative. Finish reconnecting this vault as its mirror before editing.":"This local authority is frozen while its exact snapshot is adopted by hosted mdbase.")}async adoptLocalCollection(e,t){return this.withAdoptionOperation(t.signal,n=>this.adoptLocalCollectionActive(e,{...t,signal:n}))}async adoptLocalCollectionActive(e,t){if(this.settingsHost.getMirrorProfile())throw new w("mirror_already_configured","This vault already mirrors a collection authority.");if(this.adoptionMarker)return this.resumeAdoptionActive(t);t.onProgress?.({stage:"checking"}),t$(await this.previewAdoption(e.selectiveSync,t.signal));let n=await this.ensurePortableCollectionIdentity(),i=await this.adoptionClient.begin({controlUrl:e.controlUrl,collectionId:n.collectionId,displayName:n.displayName,sourceName:e.mirrorName,retainMirror:!0,mirrorName:e.mirrorName},t);try{await this.storeAdoptionSecret(i)}catch(s){throw await this.adoptionClient.cancel(i,t).catch(()=>{}),s}return await this.writeAdoptionMarker({version:1,phase:"waiting_for_approval",session:Nm(i),selective_sync:Nr(e.selectiveSync),manifest_digest:null,source_revision:null,source_head:null}),await t.onVerification(Nm(i)),this.runAdoptionWithRecovery(i,t)}async resumeAdoption(e={}){return this.withAdoptionOperation(e.signal,t=>this.resumeAdoptionActive({...e,signal:t}))}async resumeAdoptionActive(e){let t=this.adoptionMarker??await this.readAdoptionMarker();if(!t)throw new w("authority_adoption_not_found","This vault has no collection-adoption checkpoint.");this.adoptionMarker=t;let n=this.app.secretStorage.getSecret(this.adoptionSecretId(t.session.adoptionId));if(!n)throw new w("authority_adoption_credentials_missing","The collection-adoption credential is missing from Obsidian's secret store.");let i={...t.session,credential:n};return t.phase==="waiting_for_approval"&&await e.onVerification?.(Nm(i)),this.runAdoptionWithRecovery(i,{...e,onVerification:s=>e.onVerification?.(s)})}async cancelAdoption(e){return this.withAdoptionOperation(e,t=>this.cancelAdoptionActive(t))}async cancelAdoptionActive(e){let t=this.adoptionMarker??await this.readAdoptionMarker();if(!t)return;if(["activating","adopted"].includes(t.phase))throw new w("authority_adoption_activation_started","Hosted activation has started and must be resumed; it can no longer be cancelled.");let n=this.app.secretStorage.getSecret(this.adoptionSecretId(t.session.adoptionId));if(!n)throw new w("authority_adoption_credentials_missing","The collection-adoption credential is missing from Obsidian's secret store.");await this.adoptionClient.cancel({...t.session,credential:n},{signal:e}),await this.clearAdoptionCheckpoint(t.session.adoptionId)}async enroll(e,t){return this.withLifetime(t.signal,n=>this.enrollActive(e,{...t,signal:n}))}async enrollActive(e,t){let n=await this.assertCanBecomeMirror(e.collectionId),i=await this.enrollmentClient.enroll({controlUrl:e.controlUrl,mirrorName:e.mirrorName,mode:e.mode,...n?{collectionId:n}:{}},t),s=await this.markMirror(i.collectionId);try{await this.persistEnrollment(i,e.selectiveSync)}catch(o){if(s)try{await this.app.vault.adapter.remove(Nn)}catch{throw new w("enrollment_recovery_required",`Enrollment settings could not be saved and the temporary role marker could not be removed: ${o instanceof Error?o.message:String(o)}`)}throw o}return this.requireProfile()}async inspect(){return this.withMirrorOperation(async()=>{let e=this.requireProfile();await this.assertMirror(e.collectionId);let t=await this.createMirror(),{plan:n,status:i}=await t.review();return{preview:$m(n),status:i}})}async preview(){return this.withMirrorOperation(async()=>{let e=this.requireProfile();await this.assertMirror(e.collectionId);let t=await this.createMirror();return $m(await t.inspect())})}async status(){if(this.statusRequest)return this.statusRequest;let e=this.readStatus();this.statusRequest=e;try{return await e}finally{this.statusRequest===e&&(this.statusRequest=null)}}async readStatus(){return this.withMirrorOperation(async()=>{let e=this.settingsHost.getMirrorProfile();return e?(await this.assertMirror(e.collectionId),(await this.createMirror()).status()):null})}async remoteChangesWaiting(){let e=this.requireProfile(),t=this.stateStoreFor(e),n=t.readCheckpoint?await t.readCheckpoint():ua(await t.read());if(!n||n.recovery_required)return!0;let s=await(await this.transportFor(e)).changes(n.cursor,1);return s.reset_required||s.scope_epoch!==n.scope_epoch||s.head>n.cursor}async checkpointSummary(){let e=this.settingsHost.getMirrorProfile();if(!e)return null;let t=await this.stateStoreFor(e).read();return t?{cursor:t.cursor,generation:t.generation??0,batch:t.batch?`${t.batch.phase} at action ${t.batch.next_action}/${t.batch.plan.actions.length}`:null,failure:t.batch?.failure?`${t.batch.failure.code}: ${t.batch.failure.message}`:null}:null}async reconnect(){let e=this.requireProfile();this.assertThisDevice(e),await this.renewAccessToken(e);let t=await this.status();if(!t)throw new w("mirror_not_configured","The renewed mirror profile could not be loaded.");return t}async reauthorize(e){return this.withLifetime(e.signal,t=>this.reauthorizeActive({...e,signal:t}))}async reauthorizeActive(e){let t=this.requireProfile(),n=this.isOtherDevice(t),i=this.stateStoreFor(t);if((n?null:await i.read())?.batch)throw new w("mirror_recovery_required","Resume the durable synchronization checkpoint before approving this vault again.");let o=await this.enrollmentClient.enroll({controlUrl:t.controlUrl,mirrorName:t.name,mode:t.mode,collectionId:t.collectionId},e);if(o.collectionId!==t.collectionId)throw new w("mirror_identity_conflict","Connect approved a different collection. The existing mirror was not changed.");return this.withMirrorOperation(async()=>{let a=this.requireProfile();if(a.collectionId!==t.collectionId||a.replicaId!==t.replicaId||a.enrollmentId!==t.enrollmentId)throw new w("mirror_identity_conflict","The connection changed during approval. The current mirror was not changed.");let c=n?null:await i.read();if(c?.batch)throw new w("mirror_recovery_required","Resume the durable synchronization checkpoint before approving this vault again.");let l=i$(o,a.selectiveSync);return c&&o.replicaId!==t.replicaId&&await this.stateStoreFor(l).write({...c,replica_id:o.replicaId}),await this.persistEnrollment(o,a.selectiveSync),!n&&o.replicaId!==t.replicaId&&(this.clearCredentials(t),"clear"in i&&typeof i.clear=="function"&&await i.clear()),(await this.createMirror()).status()})}async conflictComparison(e){let t=this.requireProfile(),n=await this.transportFor(t),i=await n.openSession(),s={state:"absent"};if(e.entity==="record"){let l;do{let u=await n.snapshot(i.snapshot_id,l),d=u.records.find(f=>f.record_id===e.object_id);if(d){s={state:"exact",path:d.path,revision:d.revision,size:new TextEncoder().encode(d.document).byteLength,document:d.document};break}l=u.next_page}while(l)}else{let l;do{let u=await n.fileSnapshot(i.snapshot_id,l),d=u.files.find(f=>f.file_id===e.object_id);if(d){s={state:"exact",path:d.path,revision:d.content_digest,size:d.size,modifiedAt:d.modified_at};break}l=u.next_page}while(l)}let o=e.path??s.path,a={state:"absent"};if(o){let l=this.app.vault.getAbstractFileByPath(o);if(l instanceof J.TFile)if(e.entity==="record"){let u=await this.app.vault.cachedRead(l);a={state:"exact",path:o,size:new TextEncoder().encode(u).byteLength,modifiedAt:l.stat?.mtime?new Date(l.stat.mtime).toISOString():void 0,document:u}}else{let u=await this.fileSystem.inspectBinary(o);u&&(a={state:"exact",path:o,revision:u.content_digest,size:u.size,modifiedAt:l.stat?.mtime?new Date(l.stat.mtime).toISOString():void 0,resourceUrl:this.app.vault.getResourcePath(l)})}}if(!(await this.status())?.conflicts.some(l=>l.object_id===e.object_id&&l.decision_id===e.decision_id))throw new w("conflict_decision_stale","This file changed again while its versions were loading.");return{entity:e.entity,objectId:e.object_id,decisionId:e.decision_id,local:a,remote:s}}async recordComparison(e,t){let n=this.requireProfile(),i=await this.transportFor(n),s=await i.openSession(),o={state:"absent"},a;do{let u=await i.snapshot(s.snapshot_id,a),d=u.records.find(f=>f.record_id===e);if(d){o={state:"exact",path:d.path,revision:d.revision,size:new TextEncoder().encode(d.document).byteLength,document:d.document};break}a=u.next_page}while(a);let c={state:"absent"},l=this.app.vault.getAbstractFileByPath(Tt(this.app.vault,t));if(l instanceof J.TFile){let u=await this.app.vault.cachedRead(l);c={state:"exact",path:l.path,size:new TextEncoder().encode(u).byteLength,document:u}}return{entity:"record",objectId:e,decisionId:"",local:c,remote:o}}async autoResolveConflicts(){return this.withMirrorOperation(()=>this.autoResolveConflictsActive())}async autoResolveConflictsActive(){if(!this.settingsHost.getMirrorProfile())return[];let e=await this.createMirror(),t=await e.status();if(!t?.conflicts.length||t.recovery_required)return[];let n=this.requireProfile(),i=await this.stateStoreFor(n).read();if(!i||i.batch)return[];let s=t.conflicts.filter(c=>c.entity==="record"&&i.planned_conflicts?.[c.object_id]?.conflict_kind==="both_changed").map(c=>c.object_id),o=s.length?await this.remoteRecords(new Set(s)):new Map,a=[];for(let c of t.conflicts){let l=i.planned_conflicts?.[c.object_id];if(l)try{a.push(await this.autoResolve(e,c,l,o.get(c.object_id)))}catch(u){if(u instanceof w&&["conflict_decision_stale","sync_plan_stale"].includes(u.code))continue;a.push({path:c.path??c.object_id,outcome:"unresolved",reason:u instanceof Error?u.message:String(u)})}}return a}async autoResolve(e,t,n,i){let{object_id:s,decision_id:o}=t,a=n.local.state==="exact"?n.local.object.path:null,c=n.remote.state==="exact"?n.remote.object.path:null,l=t.path??a??c??s;if(n.conflict_kind==="rejected")return{path:l,outcome:"unresolved",reason:t.message};if(a===null)return await e.resolveConflict(s,o,"remote"),{path:l,outcome:c?"restored":"took_hosted"};if(c===null)return await e.resolveConflict(s,o,"local"),{path:l,outcome:"kept_local"};if(t.entity==="record"&&n.conflict_kind==="both_changed"&&i&&i.path===a&&n.remote.state==="exact"&&i.revision===n.remote.object.revision){let d=n.ancestor_document,f=await this.fileSystem.read(a);if(d!==void 0&&f!==null){let p=Xx(d,f,i.document,nF);if(p.clean)return await e.resolveConflict(s,o,"local",p.text),{path:l,outcome:"merged"}}}let u=await this.preserveConflictCopy(a);return await e.resolveConflict(s,o,"remote"),{path:l,outcome:"kept_both",copyPath:u}}async remoteRecords(e){let t=await this.transportFor(this.requireProfile()),n=await t.openSession(),i=new Map,s;do{let o=await t.snapshot(n.snapshot_id,s);for(let a of o.records)e.has(a.record_id)&&i.set(a.record_id,{path:a.path,revision:a.revision,document:a.document});s=i.size===e.size?void 0:o.next_page}while(s);return i}async createConflictCopy(e,t,n){let i=e.lastIndexOf("/"),s=e.lastIndexOf("."),o=s>i?e.slice(s):"",c=(o?e.slice(0,-o.length):e).replace(/(?: \((?:local|hosted) conflict copy(?: \d+)?\))+$/,""),l=new Uint8Array(t),u=1;for(;;){let d=`${c} (${n}${u===1?"":` ${u}`})${o}`;if(d===e){u+=1;continue}if(this.app.vault.getAbstractFileByPath(d)||await this.app.vault.adapter.exists(d)){try{let f=new Uint8Array(await this.app.vault.adapter.readBinary(d));if(f.length===l.length&&f.every((p,h)=>p===l[h]))return d}catch{}u+=1;continue}try{return await this.app.vault.createBinary(d,t),d}catch(f){if(!await this.app.vault.adapter.exists(d))throw f}}}async preserveConflictCopy(e){let t=Tt(this.app.vault,e);if(!(this.app.vault.getAbstractFileByPath(t)instanceof J.TFile))throw new w("mirror_conflict_copy_missing",`No local file exists at ${t}.`);let i=await this.app.vault.adapter.readBinary(t);return this.createConflictCopy(t,i,"local conflict copy")}async disconnect(e){if(this.isSyncing())throw new w("mirror_busy","Stop the current synchronization before disconnecting.");return this.withMirrorOperation(async()=>{let t=this.requireProfile();return this.leaseFor(t).runExclusive(()=>this.disconnectActive(e))})}async disconnectActive(e){if(this.isSyncing())throw new w("mirror_busy","Stop the current synchronization before disconnecting.");let t=this.requireProfile(),n=this.stateStoreFor(t),i=await n.read();if(i?.batch)throw new w("mirror_recovery_required","Resume the durable synchronization checkpoint before disconnecting.");let s={removed:[],preserved:[]},o=await this.readMarker();o&&await this.app.vault.adapter.remove(Nn);try{await this.settingsHost.saveMirrorProfile(null)}catch(a){throw o&&await this.markMirror(t.collectionId),a}return this.isOtherDevice(t)||(this.clearCredentials(t),"clear"in n&&typeof n.clear=="function"&&await n.clear(),await this.blobStoreFor(t).prune(new Set)),e&&i&&await this.removeExactMirrorFiles(i,s),s}async sync(e,t,n,i){if(this.syncAbort)throw new w("mirror_busy","Synchronization is already running for this vault.");let s=new AbortController;this.syncAbort=s;try{return await this.withMirrorOperation(async()=>{let a=await(await this.createMirror(c=>{fe(s.signal),this.progress=c,t?.({...c})},s.signal,c=>{fe(s.signal),this.fileProgress=c,n?.({...c})},i)).apply(e.plan,{signal:s.signal});return fe(s.signal),a})}finally{this.progress=null,this.fileProgress=null,this.syncAbort=null}}cancelSync(){this.syncAbort?.abort()}noteEngineWrite(e){let t=Date.now();for(let[n,i]of this.engineWrites)t-i>e$&&this.engineWrites.delete(n);this.engineWrites.set((0,J.normalizePath)(e),t)}consumeEngineWrite(e){let t=(0,J.normalizePath)(e),n=this.engineWrites.get(t);this.engineWrites.delete(t);let i=n===void 0?-1:Date.now()-n;return i>=0&&i<=e$}isSyncing(){return this.syncAbort!==null}async resolveConflict(e,t,n){return this.withMirrorOperation(async()=>{let i=await this.createMirror();return await i.resolveConflict(e,t,n),i.status()})}async withMirrorOperation(e){let t=this.mirrorOperationTail,n;this.mirrorOperationTail=new Promise(i=>{n=i}),await t;try{return this.assertActive(),await e()}finally{n()}}async runAdoption(e,t){let n=this.requireAdoptionMarker(e.adoptionId),i=null;if(n.phase==="adopted"){let s=await this.adoptionClient.exchange(e,t);if(s.status!=="completed")throw new w("authority_adoption_state_conflict","The local checkpoint says adoption completed, but Connect does not.");i=s}else if(n.phase==="activating"){t.onProgress?.({stage:"activating"});let s=await this.readAdoptionSnapshot(n),o=await this.adoptionClient.exchange(e,t);i=o.status==="completed"?o:await this.adoptionClient.complete(e,s,t)}else if(n.phase==="fenced"){let s=await this.readAdoptionSnapshot(n),o=await this.adoptionClient.exchange(e,t);o.status==="completed"?i=o:(o.status==="ready"&&(t.onProgress?.({stage:"uploading",records:s.records.length}),await this.adoptionClient.uploadSnapshot(e,o,s,this.adoptionUploadOptions(e,t))),await this.updateAdoptionPhase("activating",s),t.onProgress?.({stage:"activating"}),i=await this.adoptionClient.complete(e,s,t))}else{let s=n.phase==="waiting_for_approval"?await this.adoptionClient.waitForApproval(e,t):await this.requirePreparedAdoption(e,t);await this.updateAdoptionPhase("uploading",void 0,s.adoption.expires_at),t.onProgress?.({stage:"checking"});let o=await this.captureAuthoritySnapshot(e.requested.collectionId,t.signal);t.onProgress?.({stage:"uploading",records:o.records.length}),await this.adoptionClient.uploadSnapshot(e,s,o,this.adoptionUploadOptions(e,t)),t.onProgress?.({stage:"checking"});let a=await this.captureAuthoritySnapshot(e.requested.collectionId,t.signal);await this.writeAdoptionSnapshot(a),await this.updateAdoptionPhase("fenced",a);let c=await this.requirePreparedAdoption(e,t);t.onProgress?.({stage:"uploading",records:a.records.length}),await this.adoptionClient.uploadSnapshot(e,c,a,this.adoptionUploadOptions(e,t)),await this.updateAdoptionPhase("activating",a),t.onProgress?.({stage:"activating"}),i=await this.adoptionClient.complete(e,a,t)}return await this.updateAdoptionPhase("adopted"),t.onProgress?.({stage:"connecting"}),this.finishRetainedMirror(e,i,t)}async runAdoptionWithRecovery(e,t){try{return await this.runAdoption(e,t)}catch(n){throw t.signal?.aborted?new DOMException("Adoption paused.","AbortError"):SF(n)?(await this.adoptionClient.cancel(e,{signal:t.signal}).catch(()=>{}),await this.clearAdoptionCheckpoint(e.adoptionId),new w(n.code,"This adoption ended before hosted activation. The vault remains the writable local authority; start a new adoption to try again.")):n}}async requirePreparedAdoption(e,t){let n=await this.adoptionClient.exchange(e,t);if(n.status==="ready")return n;throw n.status==="activating"?new Qr("Hosted authority activation has already started. Resume using the saved fenced snapshot."):new w("authority_adoption_already_completed","Hosted authority has already adopted this collection.")}async finishRetainedMirror(e,t,n){let i,s=this.adoptionClient.mirrorEnrollmentSession(e,t);if(!s)throw new w("authority_adoption_mirror_missing","Hosted authority activated without retaining this vault as a mirror.");try{i=await this.enrollmentClient.waitForApproval(s,{signal:n.signal,onStatus:o=>n.onStatus?.({...o,state:o.state})})}catch(o){if(n.signal?.aborted)throw o;i=await this.enrollmentClient.enroll({controlUrl:e.controlUrl,collectionId:e.requested.collectionId,mirrorName:e.requested.mirrorName??e.requested.sourceName,mode:"read_write"},{signal:n.signal,onVerification:a=>n.onVerification(a)})}return this.persistAdoptedMirror(e,i)}async persistAdoptedMirror(e,t){let n=await this.markMirror(t.collectionId);try{await this.persistEnrollment(t,this.adoptionMarker?.selective_sync)}catch(i){throw n&&await this.app.vault.adapter.remove(Nn),i}return await this.clearAdoptionCheckpoint(e.adoptionId),this.requireProfile()}async adoptionSources(e,t){fe(t);let n=await ci(this.app.vault);if(fe(t),!n)throw new w("invalid_collection_configuration","A valid mdbase.yaml is required.");let i=await this.app.vault.adapter.read("mdbase.yaml");fe(t);let s=(0,J.parseYaml)(i),o=`${(0,J.normalizePath)(n.settings.types_folder)}/`,a=this.app.vault.getMarkdownFiles().filter(h=>(0,J.normalizePath)(h.path).startsWith(o)).sort((h,m)=>h.path.localeCompare(m.path)),c=xF(s).map(h=>(0,s$.default)(h,{dot:!0})),l=hd(this.app.vault).filter(h=>h.extension==="base"&&c.some(m=>m((0,J.normalizePath)(h.path)))).sort((h,m)=>h.path.localeCompare(m.path)),u=this.app.vault.getMarkdownFiles().filter(h=>!bt((0,J.normalizePath)(h.path),n)).sort((h,m)=>h.path.localeCompare(m.path)),d=["mdbase.yaml",...a.map(h=>h.path),...l.map(h=>h.path)],f=e.file_classes.length?(await this.fileSystem.listBinary?.(new Set(d))??[]).filter(h=>pF(e,h)&&!bt(h,n)):[];fe(t);let p={records:u.length,resources:d.length,files:f.length,conflicts:Om([...d,...u.map(h=>h.path),...f])};return{config:n,configuration:i,typeFiles:a,baseFiles:l,recordFiles:u,binaryPaths:f,resourcePaths:d,preview:p}}renameNamespace(){return this.app.vault.getAllLoadedFiles?.()??hd(this.app.vault)}async planAdoptionRenames(e=this.getSelectiveSync()){this.assertActive();let{preview:t,resourcePaths:n}=await this.adoptionSources(Nr(e)),i=this.renameNamespace().map(c=>c.path).sort(),s=Zx(t.conflicts,i,new Set(n)),o=s.renames.map(({from:c})=>{let l=this.app.vault.getAbstractFileByPath(c);return[c,l instanceof J.TFile?l.stat:null]}),a=(await pa(new TextEncoder().encode(JSON.stringify({paths:i,sources:o,proposed:s,policy:e})).buffer)).content_digest;return{...s,revision:a}}async applyAdoptionRenames(e,t=this.getSelectiveSync(),n){return this.withAdoptionOperation(void 0,async i=>{if(this.assertLocalAuthorityWritable(),this.settingsHost.getMirrorProfile()||await this.app.vault.adapter.exists(Nn))throw new w("adoption_rename_unsafe","Automatic rename review is only available before this vault becomes a mirror.");let s=await this.planAdoptionRenames(t);if(JSON.stringify(s)!==JSON.stringify(e))throw new w("adoption_rename_stale","Files changed since the rename review. Review the new suggestions before renaming.");let o=e.renames.map(c=>this.app.vault.getAbstractFileByPath(c.from)),a=0;n?.(0,e.renames.length);for(let[c,l]of e.renames.entries()){let u=o[c];try{if(fe(i),this.assertLocalAuthorityWritable(),!(u instanceof J.TFile)||u.path!==l.from||this.app.vault.getAbstractFileByPath(l.from)!==u)throw new Error("The source file changed. Review again.");if(this.renameNamespace().some(d=>Oe(d.path)===Oe(l.to))||await this.app.vault.adapter.exists(l.to))throw new Error("The destination is now occupied. Review again.");fe(i),await this.app.fileManager.renameFile(u,l.to),a++}catch(d){throw u?.path===l.to&&a++,new w("adoption_rename_failed",`Rename stopped after ${a} of ${e.renames.length} files. Check filenames and links before retrying. ${d instanceof Error?d.message:String(d)}`)}n?.(a,e.renames.length)}return a})}async previewAdoption(e=this.getSelectiveSync(),t){return this.assertActive(),(await this.adoptionSources(Nr(e),t)).preview}async captureAuthoritySnapshot(e,t){let{config:n,configuration:i,typeFiles:s,baseFiles:o,recordFiles:a,binaryPaths:c,preview:l}=await this.adoptionSources(this.getSelectiveSync(),t);t$(l);let u=[{path:"mdbase.yaml",kind:"configuration",document:i}];for(let[p,h]of[["type",s],["view",o]])for(let m of h)fe(t),u.push({path:(0,J.normalizePath)(m.path),kind:p,document:await this.app.vault.cachedRead(m)});let d=[];for(let p of a){fe(t);let h=(0,J.normalizePath)(p.path),m=await this.app.vault.cachedRead(p);fe(t),d.push({path:h,document:m})}let f=[];if(c.length){let p=this.adoptionBlobStore(e);for(let h of c){fe(t);let m=await this.fileSystem.readBinary?.(h);if(fe(t),!m)continue;let y=await Lm(m);fe(t);let g=await pa(y);fe(t),await p.write(g.content_digest,(async function*(){yield new Uint8Array(y)})()),fe(t);let b=this.app.vault.getAbstractFileByPath(h);f.push({file_id:zl(e,`file:${h}`),path:h,revision:g.content_digest,...g,...r$(h)?{media_type:r$(h)}:{},media_class:a$(h),modified_at:new Date(b instanceof J.TFile&&b.stat?.mtime?b.stat.mtime:Date.now()).toISOString()})}}return fe(t),sm({collectionId:e,sourceHead:0,specVersion:n.spec_version,resources:u,records:d,files:f})}adoptionBlobStore(e){return this.options.adoptionBlobStoreFactory?.(e)??this.cachedBlobStore(`adoption:${e}`)}adoptionUploadOptions(e,t){let n=this.adoptionBlobStore(e.requested.collectionId);return{signal:t.signal,fileSource:async i=>Lm(n.read(i.content_digest)),onFileProgress:({file:i,transferredBytes:s,totalBytes:o})=>t.onFileProgress?.(i.path,s,o)}}async ensurePortableCollectionIdentity(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))throw new w("collection_not_initialized","Initialize an mdbase collection before hosting it.");let e=await this.app.vault.adapter.read("mdbase.yaml"),t;try{t=(0,J.parseYaml)(e)}catch{throw new w("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!Ze(t))throw new w("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let n=Ze(t["x-mdbase-connect"])?t["x-mdbase-connect"].collection_id:void 0,i;if(n===void 0){i=crypto.randomUUID();let o=Ze(t["x-mdbase-connect"])?t["x-mdbase-connect"]:{};t["x-mdbase-connect"]={...o,collection_id:i},this.assertActive(),await this.app.vault.adapter.write("mdbase.yaml",(0,J.stringifyYaml)(t))}else if(typeof n=="string"&&fa.test(n))i=n;else throw new w("invalid_collection_configuration","x-mdbase-connect.collection_id must be a UUID string.");let s=typeof t.name=="string"&&t.name.trim()?t.name.trim():this.app.vault.getName();return{collectionId:i,displayName:s}}stateStoreFor(e){if(this.assertActive(),this.options.stateStoreFactory)return this.options.stateStoreFactory(e);let t=`${e.collectionId}:${e.replicaId}`,n=this.stateStores.get(t);return n||(n=new Um(t),this.stateStores.set(t,n)),n}cachedBlobStore(e){this.assertActive();let t=this.blobStores.get(e);return t||(t=new Bm(e),this.blobStores.set(e,t)),t}blobStoreFor(e){return this.options.blobStoreFactory?.(e)??this.cachedBlobStore(`${e.collectionId}:${e.replicaId}`)}async transportFor(e,t,n){this.assertActive(),this.assertThisDevice(e),await this.claimLegacyProfile(e);let i=await this.freshAccessToken(e);this.assertActive();let s=this.options.transportFactory?.(e,i)??new Fm(e.syncUrl,this.transportCredentials(e),md,n,t);return _F(s,t)}async createMirror(e,t,n,i){let s=this.requireProfile();await this.assertMirror(s.collectionId);let o=await this.transportFor(s,t,n),a=this.stateStoreFor(s),c={stateStore:i?new cd(a,i):a,fileSystem:this.fileSystem,blobStore:this.blobStoreFor(s),selectiveSync:Nr(s.selectiveSync),lease:this.leaseFor(s),onProgress:e};return s.mode==="read_write"?new sa(s.replicaId,o,c):new xi(s.replicaId,o,c)}leaseFor(e){return this.options.leaseFactory?.(e)??new Vm(`${e.collectionId}:${e.replicaId}`)}requireProfile(){this.assertActive();let e=this.settingsHost.getMirrorProfile();if(!e)throw new w("mirror_not_configured","This vault is not connected to a collection authority.");return e}secretIds(e,t){let n=e==="access"?aF:cF;return{current:`${n}${t.replicaId.toLowerCase()}`,legacy:`${n}${t.collectionId.toLowerCase()}`}}readSecret(e,t){let n=this.secretIds(e,t),i=this.app.secretStorage.getSecret(n.current);if(i)return i;let s=this.app.secretStorage.getSecret(n.legacy);if(!s)return null;try{this.app.secretStorage.setSecret(n.current,s)}catch{}return s}clearCredentials(e){for(let t of["access","refresh"]){let n=this.secretIds(t,e),i=this.app.secretStorage.getSecret(n.current);i&&this.app.secretStorage.getSecret(n.legacy)===i&&this.app.secretStorage.setSecret(n.legacy,""),this.app.secretStorage.setSecret(n.current,"")}}currentDeviceId(){return this.settingsHost.deviceId?.()}isOtherDevice(e=this.settingsHost.getMirrorProfile()){let t=this.currentDeviceId();return!!(e?.deviceId&&t&&e.deviceId!==t)}async claimLegacyProfile(e){let t=this.currentDeviceId();e.deviceId||!t||await this.settingsHost.saveMirrorProfile({...e,deviceId:t})}assertThisDevice(e){if(this.isOtherDevice(e))throw new w("mirror_other_device","This vault's sync settings were copied from another device or vault. Set up sync here to give this copy its own connection.")}adoptionSecretId(e){return`${lF}${e.toLowerCase()}`}async storeAdoptionSecret(e){try{let t=this.adoptionSecretId(e.adoptionId);if(this.app.secretStorage.setSecret(t,e.credential),this.app.secretStorage.getSecret(t)!==e.credential)throw new Error("Secret was not retained")}catch{throw new w("authority_adoption_credentials_unavailable","Obsidian could not save this device's authorization. Unlock or repair Obsidian's secret storage before starting the move. Nothing was uploaded.")}}async persistEnrollment(e,t){this.assertActive();try{let n=this.secretIds("access",e).current,i=this.secretIds("refresh",e).current;if(this.app.secretStorage.setSecret(n,e.accessToken),this.app.secretStorage.setSecret(i,e.refreshCredential),this.app.secretStorage.getSecret(n)!==e.accessToken||this.app.secretStorage.getSecret(i)!==e.refreshCredential)throw new Error("Secret was not retained")}catch{throw new w("mirror_credentials_unavailable","Obsidian could not save this device's authorization. Unlock or repair Obsidian's secret storage, then reconnect. Your files were not changed.")}await this.settingsHost.saveMirrorProfile(i$(e,t??this.settingsHost.getMirrorProfile()?.selectiveSync,this.currentDeviceId()))}async removeExactMirrorFiles(e,t){let n=new Map;for(let[i,s]of Object.entries(e.records)){let o=e.local_bindings?.[i]?.path??s.path;n.set(o,{entity:"document",document:s.record?.document,revision:s.revision})}for(let[i,s]of Object.entries(e.resources??{})){let o=e.local_bindings?.[i]?.path??s.path;n.set(o,{entity:"document",document:s.record?.document,revision:s.revision})}for(let[i,s]of Object.entries(e.files??{})){let o=e.local_bindings?.[i]?.path??s.file.path;n.set(o,{entity:"file",digest:s.file.content_digest,size:s.file.size})}for(let[i,s]of[...n.entries()].sort(([o],[a])=>a.localeCompare(o))){let o=!1;if(s.entity==="document"){let a=await this.fileSystem.read(i);o=a!==null&&(s.document!==void 0?a===s.document:await kF(a,s.revision))}else if(s.entity==="file"){let a=await this.fileSystem.inspectBinary(i);o=a!==null&&a.content_digest===s.digest&&a.size===s.size}if(!o){await this.fileSystem.exists(i)&&t.preserved.push(i);continue}try{await this.fileSystem.remove(i),t.removed.push(i)}catch{t.preserved.push(i)}}}async freshAccessToken(e){if(this.renewal)return this.renewal;let t=this.readSecret("access",e),n=Date.parse(e.accessTokenExpiresAt);return t&&Number.isFinite(n)&&n-Date.now()>dF?t:this.renewAccessToken(e)}renewAccessToken(e){return this.renewal??=this.renewAccessTokenOnce(e).finally(()=>{this.renewal=null}),this.renewal}async renewAccessTokenOnce(e){let t=this.readSecret("refresh",e);if(!t)throw new w("mirror_credentials_missing","The mirror refresh credential is missing. Approve this vault again.");let n=await this.enrollmentClient.renew({controlUrl:e.controlUrl,syncUrl:e.syncUrl,collectionId:e.collectionId,replicaId:e.replicaId,mode:e.mode,name:e.name,enrollmentId:e.enrollmentId,accessToken:this.readSecret("access",e)??"",refreshCredential:t,accessTokenExpiresAt:e.accessTokenExpiresAt},{signal:this.lifetime.signal}),i=this.requireProfile();if(i.collectionId!==e.collectionId||i.replicaId!==e.replicaId||i.enrollmentId!==e.enrollmentId)throw new w("mirror_identity_conflict","The connection changed while credentials were renewing. Retry with the current connection.");return await this.persistEnrollment(n,i.selectiveSync),n.accessToken}transportCredentials(e){return{token:()=>this.freshAccessToken(this.requireProfile()),renew:async t=>{let n=this.readSecret("access",e);return n&&n!==t?n:this.renewAccessToken(this.requireProfile())}}}async assertCanBecomeMirror(e){let t=await this.readMarker(),n=await this.readPortableCollectionId();if(n&&!t)throw new w("local_authority_requires_transfer","This vault has a local Connect identity. Transfer authority explicitly before using it as a mirror.");if(n&&t?.collection_id!==n)throw new w("mirror_identity_conflict","The vault identity and mirror role marker identify different collections.");let i=this.settingsHost.getMirrorProfile(),s=i?.collectionId??e;if(t&&s&&t.collection_id!==s)throw new w("mirror_identity_conflict","This vault is already marked as a different mirror.");if(!t&&!i&&await this.app.vault.adapter.exists("mdbase.yaml"))throw new w("existing_collection_requires_transfer","This vault already contains an mdbase collection. Connect an empty vault, or transfer collection authority explicitly.");return s??t?.collection_id}async readPortableCollectionId(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))return null;let e;try{e=(0,J.parseYaml)(await this.app.vault.adapter.read("mdbase.yaml"))}catch{throw new w("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!Ze(e))throw new w("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let t=e["x-mdbase-connect"];if(t===void 0)return null;if(!Ze(t))throw new w("invalid_collection_configuration","x-mdbase-connect must be a YAML mapping.");let n=t.collection_id;if(n===void 0)return null;if(typeof n!="string"||!fa.test(n))throw new w("invalid_collection_configuration","x-mdbase-connect.collection_id must be a UUID string.");return n}async markMirror(e){this.assertActive();let t=await this.readMarker();if(t){if(t.collection_id!==e)throw new w("mirror_identity_conflict","This vault already mirrors a different collection authority.");return!1}return await Ps(this.app.vault,".mdbase"),this.assertActive(),await this.app.vault.adapter.write(Nn,`${JSON.stringify({version:1,role:"mirror",collection_id:e},null,2)} +`),!0}async assertMirror(e){let t=await this.readMarker();if(!t||t.collection_id!==e)throw new w("mirror_marker_missing","The vault's mirror role marker is missing or does not match this connection.")}async readMarker(){if(!await this.app.vault.adapter.exists(Nn))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(Nn))}catch{throw new w("invalid_mirror_marker","The mirror role marker is corrupt.")}if(!Ze(e)||e.version!==1||e.role!=="mirror"||typeof e.collection_id!="string"||!fa.test(e.collection_id))throw new w("invalid_mirror_marker","The mirror role marker is invalid.");return e}requireAdoptionMarker(e){if(!this.adoptionMarker||this.adoptionMarker.session.adoptionId!==e)throw new w("authority_adoption_state_conflict","The collection-adoption checkpoint does not match this approval.");return this.adoptionMarker}async updateAdoptionPhase(e,t,n){if(!this.adoptionMarker)throw new w("authority_adoption_not_found","Collection-adoption checkpoint is missing.");await this.writeAdoptionMarker({...this.adoptionMarker,phase:e,...n?{session:{...this.adoptionMarker.session,expiresAt:n}}:{},...t?{manifest_digest:t.manifest_digest,source_revision:t.source_revision,source_head:t.source_head}:{}})}async writeAdoptionMarker(e){await Ps(this.app.vault,".mdbase"),this.assertActive(),await this.app.vault.adapter.write(ca,`${JSON.stringify(e,null,2)} +`),this.adoptionMarker=e}async readAdoptionMarker(){if(!await this.app.vault.adapter.exists(ca))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(ca))}catch{throw new w("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is corrupt.")}if(!$F(e))throw new w("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is invalid.");return e}async writeAdoptionSnapshot(e){this.assertActive(),await Ps(this.app.vault,".mdbase"),this.assertActive(),await this.app.vault.adapter.write(la,JSON.stringify(e))}async readAdoptionSnapshot(e){if(!await this.app.vault.adapter.exists(la))throw new w("authority_adoption_snapshot_missing","The fenced authority snapshot is missing; hosted activation cannot be resumed safely.");let t;try{t=JSON.parse(await this.app.vault.adapter.read(la))}catch{throw new w("invalid_authority_adoption_snapshot","The fenced authority snapshot is corrupt.")}if(t.collection_id!==e.session.requested.collectionId||t.manifest_digest!==e.manifest_digest||t.source_revision!==e.source_revision||t.source_head!==e.source_head)throw new w("authority_adoption_snapshot_mismatch","The fenced authority snapshot does not match its durable checkpoint.");return t}async clearAdoptionCheckpoint(e){let t=this.adoptionMarker?.session.requested.collectionId;await this.app.vault.adapter.exists(la)&&await this.app.vault.adapter.remove(la),await this.app.vault.adapter.exists(ca)&&await this.app.vault.adapter.remove(ca),this.adoptionMarker=null;try{this.app.secretStorage.setSecret(this.adoptionSecretId(e),"")}catch{}t&&await this.adoptionBlobStore(t).prune(new Set).catch(()=>{})}};function Nm(r){let{credential:e,...t}=r;return t}function SF(r){return r instanceof G&&["authority_adoption_expired","authority_adoption_cancelled"].includes(r.code)}function xF(r){if(!Ze(r))return[];let e=r["x-obsidian"];return!Ze(e)||!Ze(e.bases)||!Array.isArray(e.bases.include)?[]:e.bases.include.filter(t=>typeof t=="string")}function hd(r){let e=r.getFiles?.();if(e)return e;let t=[],n=i=>{for(let s of i.children)s instanceof J.TFile?t.push(s):s instanceof J.TFolder&&n(s)};return n(r.getRoot()),t}function $F(r){if(!Ze(r)||r.version!==1||!["waiting_for_approval","uploading","fenced","activating","adopted"].includes(String(r.phase))||!Ze(r.session))return!1;let e=r.session;return typeof e.controlUrl=="string"&&typeof e.adoptionId=="string"&&fa.test(e.adoptionId)&&typeof e.verificationUri=="string"&&typeof e.expiresAt=="string"&&Ze(e.requested)&&typeof e.requested.collectionId=="string"&&fa.test(e.requested.collectionId)&&typeof e.requested.displayName=="string"&&typeof e.requested.sourceName=="string"&&e.requested.retainMirror===!0&&(r.selective_sync===void 0||EF(r.selective_sync))&&(r.manifest_digest===null||typeof r.manifest_digest=="string")&&(r.source_revision===null||typeof r.source_revision=="string")&&(r.source_head===null||Number.isSafeInteger(r.source_head))}function EF(r){if(!Ze(r)||!Array.isArray(r.file_classes)||!Array.isArray(r.excluded_folders))return!1;try{let e=Nr(r);return e.file_classes.length===r.file_classes.length&&e.excluded_folders.length===r.excluded_folders.length}catch{return!1}}function i$(r,e,t){return{version:1,syncUrl:r.syncUrl,controlUrl:r.controlUrl,collectionId:r.collectionId,replicaId:r.replicaId,mode:r.mode,name:r.name,enrollmentId:r.enrollmentId,accessTokenExpiresAt:r.accessTokenExpiresAt,selectiveSync:Nr(e),...t?{deviceId:t}:{}}}async function kF(r,e){if(!e?.startsWith("sha256:"))return!1;let t=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r)));return`sha256:${Array.from(t,i=>i.toString(16).padStart(2,"0")).join("")}`===e}var et=require("obsidian");Vt();var ga="0.3.0",AF=new Set(["name","description","display_name_key","strict","path_pattern","filename_pattern","match","fields","extends"]),PF=new Set(["type","required","default","description","values","items","fields","min","max","min_length","max_length","pattern","unique","deprecated","generated","computed","target","validate_exists","tn_role","tn_completed_values"]);function pe(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function ke(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}function sn(r){return Zo.digest(r)}function Ei(r){return Array.isArray(r)?`[${r.map(Ei).join(",")}]`:pe(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${Ei(r[e])}`).join(",")}}`:JSON.stringify(r)}function Hm(r){if(Array.isArray(r))return r.map(Hm);if(!pe(r))return r;let e={};for(let[t,n]of Object.entries(r)){let i=Hm(n);i!=null&&(Array.isArray(i)&&i.length===0||pe(i)&&Object.keys(i).length===0||(e[t]=i))}return e}function Cs(r){return[...new Set(r)]}function CF(r){return pe(r.fields)?Object.values(r.fields).some(e=>pe(e)&&(typeof e.tn_role=="string"||Array.isArray(e.tn_completed_values))):!1}function zm(r,e,t){let n=pe(e)?e:{},i={},s={},o=[],a;switch(n.type){case"any":a={};break;case"string":case"integer":case"number":case"boolean":a={type:n.type};break;case"date":case"datetime":case"time":a={type:"string",format:n.type==="datetime"?"date-time":n.type};break;case"enum":a={enum:Array.isArray(n.values)?ke(n.values):[]};break;case"link":a={type:"string"},i[r]={target_type:typeof n.target=="string"?n.target:r.endsWith("Parent")||r.endsWith("uid")?"task":"any",validate_exists:n.validate_exists===!0};break;case"list":{let c=zm(`${r}[]`,n.items,t);a={type:"array",items:c.schema},Object.assign(i,c.links),Object.assign(s,c.legacy),o.push(...c.unsupported);break}case"object":{let c={},l=[];for(let[u,d]of Object.entries(pe(n.fields)?n.fields:{})){let f=zm(`${r}.${u}`,d,t);c[u]=f.schema,Object.assign(i,f.links),Object.assign(s,f.legacy),o.push(...f.unsupported),pe(d)&&d.required===!0&&l.push(u)}t&&r==="blockedBy[]"&&l.push("uid"),a={type:"object",additionalProperties:Object.keys(c).length===0,properties:c,...l.length?{required:Cs(l)}:{}};break}default:a={},o.push(`${r}.type`);break}t&&r==="title"&&(a.minLength=1,a.description="Short summary of the task."),typeof n.description=="string"&&(a.description=n.description),typeof n.min=="number"&&(n.type==="string"?a.minLength=n.min:n.type==="list"?a.minItems=n.min:a.minimum=n.min),typeof n.max=="number"&&(n.type==="string"?a.maxLength=n.max:n.type==="list"?a.maxItems=n.max:a.maximum=n.max),typeof n.min_length=="number"&&(n.type==="list"?a.minItems=n.min_length:a.minLength=n.min_length),typeof n.max_length=="number"&&(n.type==="list"?a.maxItems=n.max_length:a.maxLength=n.max_length),typeof n.pattern=="string"&&(a.pattern=n.pattern),n.deprecated===!0&&(a.deprecated=!0),n.default!==void 0&&(a.default=ke(n.default)),n.computed!==void 0&&o.push(`${r}.computed`);for(let[c,l]of Object.entries(n)){let u=t&&(c==="tn_role"||c==="tn_completed_values");(!PF.has(c)||(c==="tn_role"||c==="tn_completed_values")&&!u)&&(s[`${r}.${c}`]=ke(l))}return{schema:a,links:i,legacy:s,unsupported:o}}function ha(r,e,t,n){let i=pe(r[e])?r[e]:{},s=pe(i.set)?i.set:{};s[t]=n,i.set=s,r[e]=i}function MF(r,e,t){if(t==="now")ha(r,"on_create",e,{now:!0});else if(t==="now_on_write")ha(r,"on_update",e,{now:!0});else if(t==="uuid")ha(r,"on_create",e,{uuid:!0});else if(t==="ulid")ha(r,"on_create",e,{ulid:!0});else if(pe(t)&&t.transform==="slugify"&&typeof t.from=="string")ha(r,"on_create",e,{slugify:t.from});else return!1;return!0}function RF(r){let e=r.match(/^(.*\/)?\{title\}\.md$/);return e?{runtime:"tasknotes",template:"{{title}}",folder:(e[1]??"").replace(/\/$/,""),generated_by:"tasknotes.filename.create"}:{runtime:"tasknotes",template:r,generated_by:"tasknotes.filename.create"}}function TF(r,e,t){if(t.kind==="mdbase.type"||t.schema!==void 0)throw new Error(`${r} already looks like a v0.3 type.`);if(typeof t.name!="string"||!pe(t.fields))throw new Error(`${r} is not a v0.2 type with a name and fields.`);let n=CF(t),i=t.name.trim().toLowerCase(),s={type:{const:i}},o=[],a={},c={},l=[],u={},d={},f=[],p=[],h={},m={},y={};for(let[E,A]of Object.entries(t.fields)){let x=pe(A)?A:{},R=zm(E,x,n);s[E]=R.schema,Object.assign(c,R.links),Object.assign(d,R.legacy),f.push(...R.unsupported),x.required===!0&&o.push(E),x.default!==void 0&&(a[E]=ke(x.default)),x.unique===!0&&l.push({field:E,scope:"collection"}),x.generated!==void 0&&(MF(u,E,x.generated)?p.push(E):(d[`${E}.generated`]=ke(x.generated),f.push(`${E}.generated`))),typeof x.tn_role=="string"&&(h[x.tn_role]=E),Array.isArray(x.tn_completed_values)&&(m.completed_values=ke(x.tn_completed_values))}a.status!==void 0&&(m.default=ke(a.status)),a.priority!==void 0&&(y.default=ke(a.priority));let g=typeof t.display_name_key=="string"&&Object.prototype.hasOwnProperty.call(t.fields,t.display_name_key)?t.display_name_key:void 0,b={...g?{display:{name_field:g}}:{},read_defaults:a,links:c,unique:l};typeof t.path_pattern=="string"&&(b.path=n?RF(t.path_pattern):{pattern:t.path_pattern});let v={};for(let[E,A]of Object.entries(t))AF.has(E)||(v[E]=ke(A));Object.keys(d).length&&(v.fields=d);let S=Hm({kind:"mdbase.type",name:i,version:1,description:typeof t.description=="string"?t.description:void 0,match:pe(t.match)?ke(t.match):void 0,schema:{dialect:"json-schema-2020-12",value:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",additionalProperties:t.strict!==!0,properties:s,...o.length?{required:Cs(o)}:{}}},collection:b,lifecycle:u,...n?{"x-tasknotes":{contract:"tasknotes.task",version:1,field_roles:h,status:m,priority:y,archive:{tags_field:h.tags??"tags",archived_tag:"archived"}}}:{},...Object.keys(v).length?{"x-legacy-v0.2":v}:{}}),_=[];t.extends!==void 0&&f.push("extends");for(let E of Cs(f).sort())_.push({path:r,code:"migration_lossy",message:`${E} cannot be expressed as canonical v0.3 write behavior and was retained as legacy metadata where possible.`,severity:"lossy"});return n&&_.push({path:r,code:"path_policy_runtime_owned",message:"TaskNotes filename behavior is recorded as TaskNotes runtime metadata.",severity:"warning"}),t.strict!==!0&&_.push({path:r,code:"additional_properties_true",message:"The migrated schema allows additional properties because the source type was not strict.",severity:"warning"}),typeof t.display_name_key=="string"&&!g&&_.push({path:r,code:"display_field_missing",message:`The display field '${t.display_name_key}' is not declared, so collection.display was omitted.`,severity:"warning"}),{target:S,summary:{path:r,name:i,fieldsConverted:Object.keys(t.fields).length,requiredFields:Cs(o),defaultsMoved:Object.keys(a),generatedFieldsMoved:Cs(p),linksMoved:Object.keys(c),taskNotes:n},diagnostics:_}}var IF=["default_strict","write_nulls","write_empty_lists","write_defaults","rename_update_refs","cache_folder","migrations_folder","extensions"];function OF(r,e){let t=ke(r);t.spec_version=ga;let n=pe(t.settings)?t.settings:{};if(t.settings=n,!Array.isArray(n.record_extensions)){let a=Array.isArray(n.extensions)?n.extensions.map(String).map(c=>c.replace(/^\./,"")):[];n.record_extensions=Cs(["md",...a])}Array.isArray(n.explicit_type_keys)||(n.explicit_type_keys=["type","types"]),n.validation===void 0&&typeof n.default_validation=="string"&&(n.validation=n.default_validation),n.validation===void 0&&typeof t.default_validation=="string"&&(n.validation=t.default_validation),n.validation??="warn",n.id_field===void 0&&(n.id_field=typeof t.id_field=="string"?t.id_field:"id");let i=typeof n.types_folder=="string"?(0,et.normalizePath)(n.types_folder):"_types",s=(Array.isArray(n.exclude)?n.exclude:[]).map(String).flatMap(a=>DF(a,i)??[]);for(let a of s)NF(a)||e.push({path:"mdbase.yaml",code:"non_portable_exclude",message:`Exclude pattern "${a}" is not a portable v0.3 glob; review it.`,severity:"warning"});n.include_subfolders===!1&&s.push("*/**"),s.length>0?n.exclude=s:delete n.exclude;let o={};for(let a of IF)n[a]!==void 0&&(o[a]=n[a]),delete n[a];if(Object.keys(o).length>0){let a=pe(t["x-legacy-v0.2"])?t["x-legacy-v0.2"]:{};t["x-legacy-v0.2"]={...a,settings:o}}return delete n.include_subfolders,delete n.default_validation,delete t.default_validation,delete t.id_field,t}function DF(r,e){return/[/*?[]/.test(r)?r.includes("/")?r:`**/${r}`:r.startsWith(".")||r==="node_modules"||r===e?null:`${r}/**`}function NF(r){return r!==""&&!r.startsWith("/")&&!/[{}\\]/.test(r)&&r.split("/").every(e=>e==="**"||!e.includes("**"))}function d$(r,e){let t=pe(r.settings)?r.settings:{};return{spec_version:e,name:typeof r.name=="string"?r.name:void 0,description:typeof r.description=="string"?r.description:void 0,settings:{types_folder:typeof t.types_folder=="string"?t.types_folder:"_types",explicit_type_keys:Array.isArray(t.explicit_type_keys)?t.explicit_type_keys.filter(n=>typeof n=="string"):["type","types"],default_strict:t.default_strict===!0,include_subfolders:t.include_subfolders!==!1,exclude:Array.isArray(t.exclude)?t.exclude.filter(n=>typeof n=="string"):["_types",".obsidian",".git",".mdbase"]}}}function LF(r,e){let t={};for(let[n,i]of Object.entries(pe(e.fields)?e.fields:{}))pe(i)&&(t[n]=ke(i));return{name:typeof e.name=="string"?e.name:r.split("/").pop()?.replace(/\.md$/,"")??"type",fields:t,match:pe(e.match)?ke(e.match):void 0,filePath:r,specProfile:"v0.2"}}function FF(r,e){let t=pe(e.schema)?e.schema:{},n=pe(t.value)?t.value:{};return{name:typeof e.name=="string"?e.name:r.split("/").pop()?.replace(/\.md$/,"")??"type",fields:vn(n),match:pe(e.match)?ke(e.match):void 0,collection:pe(e.collection)?ke(e.collection):void 0,schema:ke(n),filePath:r,specProfile:"v0.3"}}function jF(r,e,t){let n=ke(r);for(let i of e){let s=t.get(i);if(s)for(let[o,a]of Object.entries(s.fields))!(o in n)&&a.default!==void 0&&(n[o]=ke(a.default))}return n}function qF(r,e,t){let n=ke(r);for(let i of e){let s=t.get(i);if(s)for(let[o,a]of Object.entries(s.collection?.read_defaults??{}))o in n||(n[o]=ke(a))}return n}async function BF(r,e){let t=(0,et.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let n="";for(let i of t.split("/")){n=n?`${n}/${i}`:i;let s=r.getAbstractFileByPath(n);if(!(s instanceof et.TFolder)){if(s)throw new Error(`A file blocks folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}async function yd(r,e,t){let n=(0,et.normalizePath)(e),i=n.lastIndexOf("/");if(i>=0&&await BF(r,n.slice(0,i)),n.startsWith(".mdbase/")){await r.adapter.write(n,t);return}let s=r.getAbstractFileByPath(n);if(s instanceof et.TFolder)throw new Error(`A folder blocks file ${n}.`);s instanceof et.TFile?await r.modify(s,t):await r.create(n,t)}async function ya(r,e){let t=(0,et.normalizePath)(e),n=r.getAbstractFileByPath(t);if(n instanceof et.TFile)return r.cachedRead(n);if(await r.adapter.exists(t))return r.adapter.read(t);throw new Error(`File not found: ${e}`)}async function u$(r){let e=await ya(r,"mdbase.yaml"),t=(0,et.parseYaml)(e);if(!pe(t))throw new Error("mdbase.yaml must contain a YAML mapping.");let n=typeof t.spec_version=="string"?t.spec_version:"";if(!/^0\.2(?:\.\d+)?$/.test(n))throw new Error(n===ga?"This collection is already mdbase v0.3.":`Expected an mdbase v0.2.x collection, found ${JSON.stringify(n)}.`);let i=pe(t.settings)?t.settings:{},s=typeof i.types_folder=="string"?(0,et.normalizePath)(i.types_folder):"_types",o=`${s}/`,a=[],c=[],l=[],u=OF(t,l),d=`${(0,et.stringifyYaml)(u).trimEnd()} +`;a.push({path:"mdbase.yaml",sourceDigest:sn(e),targetDigest:sn(d),source:e,target:d});let f=new Map,p=new Map;for(let S of r.getMarkdownFiles().filter(_=>_.path.startsWith(o)).sort((_,E)=>_.path.localeCompare(E.path))){let _=await r.cachedRead(S),E=Me(_);if(!E.hasFrontmatter||E.error)throw new Error(`Cannot migrate ${S.path}: ${E.error??"frontmatter is missing"}.`);let A=TF(S.path,n,E.frontmatter),x=LF(S.path,E.frontmatter),R=FF(S.path,A.target);f.set(x.name,x),p.set(R.name,R);let $=`${gt(A.target,E.body)} +`;a.push({path:S.path,sourceDigest:sn(_),targetDigest:sn($),source:_,target:$}),c.push(A.summary),l.push(...A.diagnostics)}if(!c.length)throw new Error(`No v0.2 type files were found in ${s}.`);let h=0,m=0,y=d$(t,n),g=d$(u,ga),b=r.getMarkdownFiles().filter(S=>!S.path.startsWith(o)).filter(S=>!S.path.startsWith(".mdbase/")).sort((S,_)=>S.path.localeCompare(_.path));for(let[S,_]of b.entries()){let E=Me(await r.cachedRead(_));if(E.error){m+=1;continue}let A=Ge(_.path,E.frontmatter,y,f),x=Ge(_.path,E.frontmatter,g,p),R=jF(E.frontmatter,A,f),$=qF(E.frontmatter,x,p);(Ei(A.slice().sort())!==Ei(x.slice().sort())||Ei(R)!==Ei($))&&l.push({path:_.path,code:"effective_read_changed",message:"The proposed v0.3 types would change this record's resolved types or effective default values.",severity:"lossy"}),h+=1,S>0&&S%250===0&&await new Promise(q=>window.setTimeout(q,0))}let v=sn(Ei({sourceVersion:n,operations:a.map(({path:S,sourceDigest:_,targetDigest:E})=>({path:S,sourceDigest:_,targetDigest:E})),diagnostics:l}));return{planVersion:1,analysisId:v,sourceVersion:n,targetVersion:ga,createdAt:new Date().toISOString(),backupLocation:`.mdbase/migrations/v02-to-v03-${v.slice(0,12)}`,operations:a,typeSummaries:c,diagnostics:l,applicable:!l.some(S=>S.severity==="lossy"),recordFilesRewritten:0,recordsVerified:h,recordsSkipped:m}}async function ma(r,e,t){await yd(r,e,`${JSON.stringify(t,null,2)} +`)}async function f$(r,e,t={}){if(e.planVersion!==1||e.targetVersion!==ga)throw new Error("Unsupported migration plan.");if(!e.applicable&&!t.allowLossy)throw new Error("This migration has lossy diagnostics. Review them and explicitly allow lossy migration.");for(let s of e.operations){let o=await ya(r,s.path);if(sn(o)!==s.sourceDigest)throw new Error(`${s.path} changed after migration analysis. Run the review again.`)}let n=`${e.backupLocation}/manifest.json`,i={manifest_version:1,analysis_id:e.analysisId,source_version:e.sourceVersion,target_version:e.targetVersion,status:"prepared",created_at:new Date().toISOString(),written:[],files:e.operations.map(s=>({path:s.path,source_digest:s.sourceDigest,target_digest:s.targetDigest,backup_path:`${e.backupLocation}/files/${s.path}`}))};for(let s of e.operations)await yd(r,`${e.backupLocation}/files/${s.path}`,s.source);await ma(r,n,i),i.status="applying",await ma(r,n,i);try{for(let s of e.operations){let o=await ya(r,s.path);if(sn(o)!==s.sourceDigest)throw new Error(`${s.path} changed during migration.`);i.written.push(s.path),await ma(r,n,i),await yd(r,s.path,s.target);let a=await ya(r,s.path);if(sn(a)!==s.targetDigest)throw new Error(`${s.path} did not verify after write.`)}return i.status="applied",i.completed_at=new Date().toISOString(),await ma(r,n,i),{applied:!0,restored:!1,manifestPath:n,written:[...i.written]}}catch(s){let o=[];for(let a of[...i.written].reverse()){let c=e.operations.find(l=>l.path===a);if(!c){o.push(a);continue}try{await yd(r,a,c.source),sn(await ya(r,a))!==c.sourceDigest&&o.push(a)}catch{o.push(a)}}i.status=o.length?"recovery_required":"rolled_back",i.error=s instanceof Error?s.message:String(s),i.manual_recovery_paths=o.length?o:void 0,i.completed_at=new Date().toISOString();try{await ma(r,n,i)}catch{}return{applied:!1,restored:o.length===0,manifestPath:n,written:[...i.written],error:i.error}}}var gd=require("obsidian");Vt();function we(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function It(r){return JSON.parse(JSON.stringify(r))}var UF=new Set(["file","formula","this"]);function VF(r){let e=r.trim();if(!e)throw new Error("Type name is required.");if(!/^[A-Za-z]/.test(e))throw new Error("Type name must start with a letter.");if(e.length>=64)throw new Error("Type name must be shorter than 64 characters.");if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(e))throw new Error("Type name may contain only letters, numbers, hyphens, and underscores.");if(UF.has(e.toLowerCase()))throw new Error(`Type name '${e}' is reserved.`);return e}function Km(){return{specProfile:"v0.3",originalFrontmatter:{},name:"",description:"",extendsType:"",displayNameKey:"",strictMode:!1,pathPattern:"",filenamePattern:"",matchPathGlob:"",matchFieldsPresent:"",matchWhere:"",fields:[{name:"title",definition:{type:"string",required:!0}}],implementations:[],body:`# Type -Describe the type and intended usage.`,extraFrontmatter:{}}}function 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} +Describe the type and intended usage.`,extraFrontmatter:{}}}function HF(r){return we(r)?Object.entries(r).filter(e=>we(e[1])).map(([e,t])=>({name:e,definition:It(t)})):[]}function zF(r){return Array.isArray(r)?r.flatMap(e=>{if(!we(e)||typeof e.contract!="string"||typeof e.version!="string")return[];let t=we(e.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,i])=>typeof i=="string")):{},n=we(e.binding)?It(e.binding):void 0;return[{contract:e.contract,version:e.version,fields:t,...n?{binding:n}:{}}]}):[]}function KF(r){return Object.fromEntries(r.map(e=>[e.name,e.definition]))}function WF(r,e){let t=e.split("."),n=r,i;for(let[s,o]of t.entries()){let a=o.match(/^([^[]+)((?:\[\])*)$/);if(!a||(i=n[a[1]],!i))return null;let c=a[2].length/2;for(let l=0;l{if(e.selectors.add(i),n.type==="link"&&e.links.set(i,{target_type:typeof n.target=="string"&&n.target.trim()?n.target.trim():"any",validate_exists:n.validate_exists===!0}),n.type==="list"&&n.items&&t(n.items,`${i}[]`),n.type==="object"&&n.fields)for(let[s,o]of Object.entries(n.fields))t(o,`${i}.${s}`)};for(let[n,i]of Object.entries(r))t(i,n);return e}function bd(r,e,t){let n=r.kind==="mdbase.type",i=n&&we(r.schema)?r.schema:{},s=we(i.value)?i.value:{},o=typeof i.ref=="string"?i.ref:"",a=n&&we(r.collection)?r.collection:{},c=we(a.display)?a.display:{},l=we(a.path)?a.path:{},u=HF(n?vn(s):r.fields);n&&GF(u,a.links);let d=we(r.match)?r.match:{},f=n?s.additionalProperties===!1:r.strict,p=new Set(["name","description","extends","display_name_key","strict","path_pattern","filename_pattern","match","fields"]),h={};for(let[y,g]of Object.entries(r))p.has(y)||(h[y]=It(g));let m="";if(d.where!==void 0)try{m=(0,gd.stringifyYaml)(d.where).trim()}catch{m=""}return{specProfile:n?"v0.3":"v0.2",originalFrontmatter:It(r),name:typeof r.name=="string"&&r.name.trim()?r.name:t,description:typeof r.description=="string"?r.description:"",extendsType:typeof r.extends=="string"?r.extends:"",displayNameKey:n?typeof c.name_field=="string"?c.name_field:"":typeof r.display_name_key=="string"?r.display_name_key:"",strictMode:f==="warn"?"warn":f===!0,pathPattern:n?typeof l.pattern=="string"?l.pattern:"":typeof r.path_pattern=="string"?r.path_pattern:"",filenamePattern:n?"":typeof r.filename_pattern=="string"?r.filename_pattern:"",matchPathGlob:typeof d.path_glob=="string"?d.path_glob:"",matchFieldsPresent:Array.isArray(d.fields_present)?d.fields_present.map(String).join(", "):"",matchWhere:m,fields:u.length||o?u:Km().fields,implementations:zF(r.implements),body:e.trim()||`# ${t} -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",$$=` +Type definition for ${t}.`,extraFrontmatter:h,...o?{readOnlyReason:`This type uses schema.ref (${o}). Edit the referenced JSON Schema file directly.`}:{}}}function jn(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?It(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]=It(m.definition)}let s=VF(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:Zi(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)?It(o.match):{};r.matchPathGlob.trim()?a.path_glob=r.matchPathGlob.trim():delete a.path_glob;let c=r.matchFieldsPresent.split(",").map(m=>m.trim()).filter(Boolean);if(c.length?a.fields_present=c:delete a.fields_present,r.matchWhere.trim()){let m=(0,gd.parseYaml)(r.matchWhere);if(!we(m))throw new Error("Match where must be a YAML mapping.");a.where=m}else delete a.where;Object.keys(a).length?o.match=a:delete o.match;let l=we(o.collection)?It(o.collection):{},u=we(l.display)?It(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)?It(l.links):{},f=It(d),p=p$(i),h=p$(vn(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:It(m.fields),...m.binding&&Object.keys(m.binding).length?{binding:It(m.binding)}:{}})):delete o.implements;for(let m of["fields","strict","extends","display_name_key","path_pattern","filename_pattern"])delete o[m];return o}Vt();function on(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function h$(r){return JSON.parse(JSON.stringify(r))}function Ms(r){return`${r.id}@${r.version}`}function ba(r){let e=on(r.schema)?r.schema:{},t=on(e.properties)?e.properties:{},n=new Set(Array.isArray(e.required)?e.required.map(String):[]);return Object.entries(t).filter(i=>on(i[1])).map(([i,s])=>({name:i,reference:i,required:n.has(i),schema:s,...typeof s.description=="string"?{description:s.description}:{}}))}function va(r){let e=Object.fromEntries(r.fields.map(s=>[s.name,s.definition])),t=Zi(e),n=on(t.properties)?t.properties:{},i=new Set(Array.isArray(t.required)?t.required.map(String):[]);return Object.entries(n).filter(s=>on(s[1])).map(([s,o])=>({label:s,reference:s,required:i.has(s),type:qn(o),schema:o}))}function Rs(r,e){return r.fields[e.reference]??r.fields[e.name]??""}function wa(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=qn(r.schema);return v$(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 m$(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=va(r),n=Object.fromEntries(ba(e).flatMap(i=>{let s=t.find(o=>o.reference.toLowerCase()===i.reference.toLowerCase()&&v$(qn(i.schema),o.type));return s?[[i.reference,s.reference]]:[]}));r.implementations.push({contract:e.id,version:e.version,fields:n})}function y$(r,e,t){r.implementations=r.implementations.filter(n=>n.contract!==e||n.version!==t)}function g$(r,e,t){t?r.fields[e]=t:delete r.fields[e]}function Wm(r,e){r.binding=Object.keys(e).length?h$(e):void 0}function _a(r){if(!r)return"";if(Array.isArray(r.enum)&&r.enum.length)return h$(r.enum[0]);let e=qn(r);if(e==="object"){let t={},n=on(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)&&on(o)&&(t[s]=_a(o));return t}return e==="array"?[]:e==="boolean"?!1:e==="number"||e==="integer"?0:""}function qn(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":on(r.properties)||on(r.additionalProperties)?"object":"any"}function b$(r){let e=qn(r);return e==="array"?"List":e==="boolean"?"Boolean":e==="integer"?"Integer":e==="number"?"Number":e==="object"?"Object":e==="any"?"Any value":"Text"}function v$(r,e){return r==="any"||e==="any"||r===e?!0:r==="number"&&e==="integer"}function Gm(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function JF(r){return JSON.parse(JSON.stringify(r))}function Xm(r){let e=2166136261,t=2654435769;for(let n=0;n>>0).toString(36)}-${(t>>>0).toString(36)}`}function w$(r){let e=JF(r);return delete e.sourceRevision,e}function vd(r,e){return r===null||e===null?r===e:JSON.stringify(w$(r))===JSON.stringify(w$(e))}function _$(r){return new Map(r.fields.map(e=>[e.name,e]))}function Jm(r){return typeof r.type=="string"?r.type:"any"}function Ym(r,e,t,n){let i=Jm(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"&&(Gm(r.items)?Ym(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(!Gm(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),Gm(a)&&Ym(a,c,t,n)}}}function Sa(r,e={}){let t=[],n=new Set(e.knownTypes??[]);try{jn(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),Ym(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=va(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 ba(l)){let d=Rs(a,u),f=o.find(h=>h.reference===d),p=wa(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 xa(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=_$(r),i=_$(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=Jm(d.definition),p=Jm(u.definition);f!==p&&t.push({code:"change_field_type",risk:"high",summary:`Change '${l}' from ${f} to ${p}.`}),d.definition.required!==!0&&u.definition.required===!0&&t.push({code:"require_field",risk:"high",summary:`Make '${l}' required. Existing records may become invalid.`}),f===p&&JSON.stringify(d.definition)!==JSON.stringify(u.definition)&&d.definition.required===u.definition.required&&t.push({code:"field_rules",risk:"review",summary:`Update validation or documentation for '${l}'.`})}let a=[...n.keys()].filter(l=>i.has(l)),c=[...i.keys()].filter(l=>n.has(l));return a.join("\0")!==c.join("\0")&&t.push({code:"reorder_fields",risk:"safe",summary:"Reorder fields."}),JSON.stringify(r.implementations)!==JSON.stringify(e.implementations)&&t.push({code:"application_compatibility",risk:"review",summary:"Update application contract mappings or settings."}),!t.length&&!vd(r,e)&&t.push({code:"type_document",risk:"review",summary:"Update advanced type metadata or documentation."}),t}var Ds=require("obsidian");var $a="mdbase-frontmatter",S$=` @@ -209,17 +210,17 @@ Type definition for ${t}.`,extraFrontmatter:h,...o?{readOnlyReason:`This type us -`;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(` +`;var P$=require("obsidian");var YF={schema_required:"missing",missing_required:"missing",schema_additional_properties:"not declared",unknown_field:"not declared",schema_type:"wrong type",invalid_type:"wrong type",schema_enum:"not an allowed value",invalid_enum:"not an allowed value",schema_maximum:"above maximum",above_max:"above maximum",schema_minimum:"below minimum",below_min:"below minimum",schema_max_length:"too long",above_max_length:"too long",schema_min_length:"too short",below_min_length:"too short",schema_max_items:"too many items",schema_min_items:"too few items",schema_pattern:"pattern mismatch",pattern_mismatch:"pattern mismatch",format_invalid:"invalid format",duplicate_value:"duplicate value",duplicate_unique:"duplicate value",link_not_found:"missing link target",missing_link_target:"missing link target",link_wrong_type:"link to wrong type",no_matching_type:"no matching type",unknown_type:"unknown type",invalid_frontmatter:"invalid frontmatter"};function XF(r){return YF[r]??r.replace(/^schema_/,"").replace(/_/g," ")}function QF(r){return[r.type??"",r.field??"",r.code].join("\0")}function Qm(r){return[r.type,r.field,XF(r.code)].filter(Boolean).join(" \xB7 ")}function x$(r){let e=new Map;for(let t of r){let n=QF(t),i=e.get(n);i||(i={key:n,label:Qm(t),issues:[]},e.set(n,i)),i.issues.push(t)}return[...e.values()].sort((t,n)=>n.issues.length-t.issues.length||t.label.localeCompare(n.label))}Vt();function $$(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function E$(r,e,t){let n=new Map;for(let i of r){let s=Ge(i.path,i.frontmatter,e,t);s.length&&n.set(i.path,s)}return n}function k$(r,e){let t=new Map,n=i=>{let s=t.get(i);return s||(s={notes:0,issues:0},t.set(i,s)),s};for(let i of r.values())for(let s of i)n(s).notes+=1;for(let i of e)for(let s of Zm(i,r))n(s).issues+=1;return t}function Zm(r,e){return r.type?[r.type]:e.get(r.path)??[]}function ZF(r,e){let t=jn(r),n=$$(t.schema)?t.schema:{},i=$$(n.value)?n.value:{};return _c(t,e??`${r.name||"new"}.md`,i)}function ej(){return new Promise(r=>window.setTimeout(r,0))}async function A$(r){let e;try{e=ZF(r.draft,r.filePath)}catch(s){return{error:s instanceof Error?s.message:String(s)}}let t=r.savedName?r.types.get(r.savedName)??null:null,n=new Map(r.types);r.savedName&&n.delete(r.savedName),n.set(e.name,e);let i={matched:[],added:[],removed:[],failing:[],fixed:0};for(let[s,o]of r.records.entries()){if(s>0&&s%400===0&&(await ej(),r.isCurrent&&!r.isCurrent()))return null;let a=t!==null&&Ge(o.path,o.frontmatter,r.config,r.types).includes(t.name),c=Ge(o.path,o.frontmatter,r.config,n).includes(e.name);if(c&&i.matched.push(o.path),c&&!a&&i.added.push(o.path),a&&!c&&i.removed.push(o.path),!c&&!a)continue;let l=a&&t?es(o.path,o.frontmatter,t).length:0,u=c?es(o.path,o.frontmatter,e):[];u.length?i.failing.push({path:o.path,issues:u,isNew:l===0}):l>0&&c&&(i.fixed+=1)}return{impact:i}}var wd=class{constructor(e){this.ctx=e;this.issueQuery="";this.issueSeverity="all";this.issueLimit=250;this.issueGroupBy="file"}getState(){return{issueQuery:this.issueQuery,issueSeverity:this.issueSeverity,issueGroupBy:this.issueGroupBy}}setState(e){typeof e.issueQuery=="string"&&(this.issueQuery=e.issueQuery.slice(0,2e3)),["all","error","warn"].includes(String(e.issueSeverity))&&(this.issueSeverity=e.issueSeverity),(e.issueGroupBy==="rule"||e.issueGroupBy==="file")&&(this.issueGroupBy=e.issueGroupBy)}updateValidationProgress(){let e=this.ctx.containerEl.querySelector("[data-validation-summary]");e&&(e.textContent=this.ctx.host.getValidationSummary())}filterToPath(e){this.issueQuery=e,this.issueLimit=250}render(e){let t=e.createDiv({cls:"mdbase-issues-document"}),n=this.ctx.host.getIssues(),i=new Set(n.map(b=>b.path)).size,s=t.createDiv({cls:"mdbase-document-header"}),o=s.createDiv(),a=this.ctx.host.getValidationSummary();o.createEl("h2",{text:n.length?`${n.length.toLocaleString()} ${n.length===1?"issue":"issues"} \xB7 ${i.toLocaleString()} ${i===1?"file":"files"}`:a==="Not checked yet"?"Validation":"No known issues"});let c=o.createDiv({cls:"mdbase-muted",text:a});if(c.setAttr("role","status"),c.setAttr("data-validation-summary","true"),this.ctx.host.isValidating()){let b=s.createEl("button",{text:"Stop validation"});b.onclick=()=>this.ctx.host.cancelValidation()}let l=s.createEl("button",{text:"Validate"});if(l.disabled=this.ctx.busy||this.ctx.host.isValidating(),l.onclick=()=>void this.ctx.perform(async()=>{await this.ctx.host.validateCollection(),this.ctx.render()}),!n.length)return;let u=t.createDiv({cls:"mdbase-issue-controls"}),d=u.createEl("select");d.setAttr("aria-label","Issue severity"),d.createEl("option",{value:"all",text:"All severities"}),d.createEl("option",{value:"error",text:"Errors"}),d.createEl("option",{value:"warn",text:"Warnings"}),d.value=this.issueSeverity,d.onchange=()=>{this.issueSeverity=d.value==="error"||d.value==="warn"?d.value:"all",this.issueLimit=250,this.ctx.render()};let f=u.createEl("select");f.setAttr("aria-label","Group issues"),f.createEl("option",{value:"file",text:"By file"}),f.createEl("option",{value:"rule",text:"By rule"}),f.value=this.issueGroupBy,f.onchange=()=>{this.issueGroupBy=f.value==="rule"?"rule":"file",this.ctx.render()};let p=u.createEl("input",{type:"search"});p.setAttr("aria-label","Filter issues"),p.setAttr("data-focus-key","issue-search"),p.placeholder="Filter issues",p.value=this.issueQuery,p.oninput=()=>{this.issueQuery=p.value,this.issueLimit=250,this.ctx.render();let b=this.ctx.containerEl.querySelector(".mdbase-issue-controls input[type='search']");b?.focus(),b?.setSelectionRange(b.value.length,b.value.length)};let h=this.issueQuery.trim().toLowerCase(),m=n.filter(b=>this.issueSeverity!=="all"&&b.severity!==this.issueSeverity?!1:h?`${b.path} ${b.code} ${b.type??""} ${b.field??""} ${b.message}`.toLowerCase().includes(h):!0),y=new Set(m.map(b=>b.path)).size;if((m.length!==n.length||m.length>this.issueLimit)&&t.createDiv({cls:"mdbase-issues-summary",text:`${Math.min(m.length,this.issueLimit).toLocaleString()} of ${m.length.toLocaleString()} issues \xB7 ${y.toLocaleString()} files`}),!m.length){t.createDiv({cls:"mdbase-empty-state",text:"No issues match these filters."});return}let g=m.slice(0,this.issueLimit);if(this.issueGroupBy==="rule"?this.renderIssuesByRule(t,g):this.renderIssuesByFile(t,g),m.length>g.length){let b=t.createEl("button",{cls:"mdbase-load-more",text:`Load ${Math.min(250,m.length-g.length)} more`});b.onclick=()=>{this.issueLimit+=250,this.ctx.render()}}}renderIssuesByFile(e,t){let n=new Map;for(let i of t)n.set(i.path,[...n.get(i.path)??[],i]);for(let[i,s]of n){let o=e.createEl("section",{cls:"mdbase-issue-group"}),a=o.createDiv({cls:"mdbase-issue-group-header"}),c=a.createEl("button",{cls:"mdbase-issue-file-button"});(0,P$.setIcon)(c.createSpan({cls:"mdbase-issue-file-icon"}),"file-text"),c.createSpan({cls:"mdbase-issue-file-path",text:i}),c.setAttr("title",`Open ${i}`),c.onclick=()=>void this.ctx.host.openFileByPath(i),a.createSpan({cls:"mdbase-issue-file-count",text:`${s.length} ${s.length===1?"issue":"issues"}`});for(let l of s){let u=o.createDiv({cls:"mdbase-issue-row"});this.fillIssueRow(u,l,`${l.severity==="warn"?"Warning":"Error"}${l.field?` \xB7 ${l.field}`:""}`)}}}renderIssuesByRule(e,t){for(let n of x$(t)){let i=n.issues[0],s=e.createEl("section",{cls:"mdbase-issue-group"}),o=s.createDiv({cls:"mdbase-issue-group-header"}),a=o.createDiv({cls:"mdbase-issue-rule-title"});a.createSpan({cls:"mdbase-issue-indicator",attr:{"data-severity":i.severity,"aria-hidden":"true"}}),a.createSpan({cls:"mdbase-issue-file-path",text:Qm(i)});let c=new Set(n.issues.map(p=>p.path)).size;o.createSpan({cls:"mdbase-issue-file-count",text:`${c.toLocaleString()} ${c===1?"note":"notes"}`});let l=o.createDiv({cls:"mdbase-issue-row-actions"});this.renderEditRuleButton(l,i);let u=this.ctx.host.getQuickFixLabel(i),d=u?n.issues.filter(p=>this.ctx.host.getQuickFixLabel(p)===u):[],f=new Set(d.map(p=>p.path)).size;if(u&&f>1){let p=l.createEl("button",{text:`${u} \xB7 ${f} notes`});p.disabled=this.ctx.busy,p.onclick=()=>void this.applyBulkQuickFix(u,d)}for(let p of n.issues){let h=s.createDiv({cls:"mdbase-issue-row"});this.fillIssueRow(h,p,p.path,!0)}}}fillIssueRow(e,t,n,i=!1){e.setAttr("data-severity",t.severity),e.createSpan({cls:"mdbase-issue-indicator"}).setAttr("aria-hidden","true");let s=typeof t.details?.technical_message=="string"?t.details.technical_message:"";e.setAttr("title",s?`${t.code}: ${s}`:t.code);let o=e.createDiv({cls:"mdbase-issue-metadata"});if(i){let l=o.createEl("button",{cls:"mdbase-link-button mdbase-issue-context",text:n});l.setAttr("title",`Open ${t.path}${t.field?` at ${t.field}`:""}`),l.onclick=()=>void this.ctx.host.openFileByPath(t.path,t.field)}else o.createDiv({cls:"mdbase-issue-context",text:n});e.createDiv({cls:"mdbase-issue-row-message",text:t.message});let a=e.createDiv({cls:"mdbase-issue-row-actions"});if(!i&&t.field){let l=this.ctx.iconButton(a,"arrow-up-right",`Open ${t.path} at ${t.field}`);l.onclick=()=>void this.ctx.host.openFileByPath(t.path,t.field)}i||this.renderEditRuleButton(a,t);let c=this.ctx.host.getQuickFixLabel(t);if(c){let l=a.createEl("button",{text:c});l.disabled=this.ctx.busy,l.onclick=()=>void this.ctx.perform(async()=>{await this.ctx.host.applyQuickFix(t)})}}renderEditRuleButton(e,t){let n=Zm(t,this.ctx.recordTypes())[0],i=n?this.ctx.schema?.types.get(n):void 0;if(!i)return;let s=this.ctx.iconButton(e,"pencil",t.field?`Edit ${t.field} in ${i.name}`:`Edit type ${i.name}`);s.onclick=()=>void this.ctx.openTypeField(i.filePath,t.field)}async applyBulkQuickFix(e,t){let n=new Set(t.map(s=>s.path)).size;await new kc(this.ctx.app).confirm(e,t)&&await this.ctx.perform(async()=>{let s=await this.ctx.host.applyQuickFixes(t);this.ctx.message=s.skipped?`${e}: updated ${s.changed} of ${n} ${n===1?"note":"notes"}. ${s.skipped} changed since validation and were left as they are.`:`${e}: updated ${s.changed} ${s.changed===1?"note":"notes"}.`})}};var Ts=require("obsidian"),_d="https://connect.mdbase.dev",C$=["string","integer","number","boolean","date","datetime","time","enum","link","list","object","any"];function Se(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Bn(r){return JSON.parse(JSON.stringify(r))}function M$(r){let e=Ts.Platform.isIosApp?"iOS":Ts.Platform.isAndroidApp?"Android":Ts.Platform.isMacOS?"Mac":Ts.Platform.isWin?"Windows":Ts.Platform.isLinux?"Linux":"Obsidian";return`${r} \xB7 ${e}`}function ey(r){return r==="any"?"Any value":r==="datetime"?"Date and time":r&&r[0].toUpperCase()+r.slice(1)}function Ea(r){return typeof r.type=="string"?r.type:"any"}function R$(r){if(!Object.prototype.hasOwnProperty.call(r,"field"))return"field";let e=2;for(;Object.prototype.hasOwnProperty.call(r,`field${e}`);)e+=1;return`field${e}`}function Sd(r,e,t){Object.defineProperty(r,e,{configurable:!0,enumerable:!0,writable:!0,value:t})}function Ot(r,e,t,n,i={}){let s=r.createDiv({cls:"mdbase-form-row"}),o=s.createEl("label",{text:e}),a=`mdbase-${Math.random().toString(36).slice(2)}`;o.htmlFor=a,i.description&&s.createDiv({cls:"mdbase-form-description",text:i.description});let c=i.multiline?s.createEl("textarea"):s.createEl("input",{type:"text"});return c.id=a,c.setAttr("data-focus-key",`form-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`),c.value=t,c.placeholder=i.placeholder??"",c.addEventListener("input",()=>n(c.value)),c}function Gt(r,e,t){let n=r.createDiv({cls:"mdbase-status-row"});n.createSpan({cls:"mdbase-status-label",text:e}),n.createSpan({cls:"mdbase-status-value",text:t})}function ty(r){if(r<1e3)return String(r);let e=r<1e4?1:0;return`${(r/1e3).toFixed(e)}k`}var ka=10,T$={cancelled:"Paused",stale:"Stopped: changes detected",attention:"Needs attention",blocked:"Stopped",failed:"Failed"};function ry(r){return r.charAt(0).toUpperCase()+r.slice(1)}function I$(r){if(!r)return"Never synced";let e=Date.parse(r);if(!Number.isFinite(e))return r;let t=Math.round((e-Date.now())/1e3),n=Math.abs(t),i=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"});if(n<60)return i.format(t,"second");let s=Math.round(t/60);if(Math.abs(s)<60)return i.format(s,"minute");let o=Math.round(s/60);return Math.abs(o)<24?i.format(o,"hour"):i.format(Math.round(o/24),"day")}function O$(r){return r?r.state==="up_to_date"?"Up to date":r.state==="changes_waiting"?"Changes waiting":["attention","blocked","failed","stale"].includes(r.state)||r.recovery_required?"Needs attention":r.state==="cancelled"?"Paused safely":r.state==="applying"?"Synchronizing":r.state==="planned"?"Review ready":"Ready for first sync":"Checking connection"}function xd(r){return r instanceof Error&&r.name==="AbortError"}var D$=require("obsidian"),$d="Attachments are limited to 32 MiB per file on desktop and mobile. Exclusions apply to both notes and attachments. Previously synced files remain in this vault; excluded paths no longer transfer. Excluding a folder does not delete hosted copies.";function Ed(r,e,t,n){let i=[...t],s=e.createDiv({cls:"mdbase-folder-exclusions"}),o=s.createDiv({cls:"mdbase-folder-chips"}),a=s.createEl("input",{type:"text",placeholder:"Choose or enter a folder"});a.id="mdbase-excluded-folder",a.setAttr("aria-label","Excluded folder"),a.setAttr("data-focus-key","excluded-folder-input");let c=s.createEl("datalist");c.id="mdbase-folder-options",a.setAttr("list",c.id);for(let f of r.vault.getAllLoadedFiles())f instanceof D$.TFolder&&f.path&&f.path!=="/"&&c.createEl("option",{value:f.path});let l=s.createDiv({cls:"mdbase-inline-error",attr:{role:"alert"}}),u=()=>{o.empty();for(let f of i){let p=o.createEl("button",{text:`${f} \xD7`});p.setAttr("aria-label",`Remove exclusion ${f}`),p.onclick=()=>{i.splice(i.indexOf(f),1),n([...i]),u()}}},d=()=>{let f=a.value.trim().replace(/\/+$/,"");if(!f||f.startsWith("/")||f.includes("\\")||f.split("/").some(p=>!p||p==="."||p==="..")){l.textContent="Choose a vault-relative folder without parent traversal or empty segments.";return}l.textContent="",i.includes(f)||(i.push(f),n([...i]),u()),a.value="",a.focus()};s.createEl("button",{text:"Exclude folder"}).onclick=d,a.onkeydown=f=>{f.key==="Enter"&&(f.preventDefault(),d())},u()}var Is=require("obsidian");function N$(r,e){let t=r.split(` `),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 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(` +`),i=t.length>200||n.length>200,s=t.slice(0,200),o=n.slice(0,200),a=Array.from({length:s.length+1},()=>new Uint16Array(o.length+1));for(let d=s.length-1;d>=0;d-=1)for(let f=o.length-1;f>=0;f-=1)a[d][f]=s[d]===o[f]?a[d+1][f+1]+1:Math.max(a[d+1][f],a[d][f+1]);let c=[],l=0,u=0;for(;(l=300);)l=o.length||l=a[l][u+1]?(c.push({kind:"local",value:s[l]}),l+=1):(c.push({kind:"remote",value:o[u]}),u+=1);return{lines:c,truncated:i||l0&&!r.actions.some(o=>o.command!=="advance_checkpoint"))return{actionLabel:"Resolve issues",actionDisabled:!0,message:"Synchronization is paused. Resolve the blocking issues, then refresh the review."};let n=r.actions.filter(o=>o.command!=="advance_checkpoint").length,i=r.actions.some(o=>o.command==="advance_checkpoint"),s=r.issues.some(o=>o.code==="invalid_frontmatter"&&!o.blocking);return{actionLabel:n?`Sync ${n}${r.summary.blocking_issues?" available":""} ${n===1?"change":"changes"}`:i?"Confirm sync":"Up to date",actionDisabled:t||r.actions.length===0,message:r.summary.blocking_issues>0?"Sync available changes. Unresolved items are isolated and remain for the next review; they do not stop independent transfers.":s?"Frontmatter warnings do not block this sync. Document bytes are preserved; synchronization does not repair YAML.":e?"Review each transfer below, then sync when ready.":"This vault and the hosted collection are already aligned."}}function yr(r){return r<1024?`${r} B`:r<1024*1024?`${(r/1024).toFixed(r<10*1024?1:0)} KB`:r<1024*1024*1024?`${(r/(1024*1024)).toFixed(r<10*1024*1024?1:0)} MB`:`${(r/(1024*1024*1024)).toFixed(1)} GB`}function L$(r){let{connected:e,status:t,progress:n,fileProgress:i,problem:s,validationIssues:o,localChangeObserved:a}=r,c=r.reviewChanges??0;if(!e)return o?{state:"attention",label:`mdbase: ${o} ${o===1?"issue":"issues"}`,detail:"Open validation issues",destination:"issues"}:{state:"local",label:"mdbase: Local",detail:"This vault is not connected",destination:"sync"};if(i){let u=i.totalBytes>0?Math.min(100,Math.round(i.transferredBytes/i.totalBytes*100)):100;return{state:"syncing",label:`mdbase: ${i.direction==="upload"?"Uploading":"Downloading"} ${u}%`,detail:`${i.path} \xB7 ${yr(i.transferredBytes)} of ${yr(i.totalBytes)}`,destination:"sync"}}if(n)return{state:"syncing",label:`mdbase: Syncing${n.total==null?"":` ${n.completed}/${n.total}`}`,detail:"Open synchronization progress",destination:"sync"};if(r.paused&&!s)return{state:"paused",label:"mdbase: Paused",detail:"Changes wait until you resume sync",destination:"sync"};if(s&&s.kind!=="busy")return{state:s.kind==="paused"?"paused":s.kind==="offline"?"offline":"attention",label:s.kind==="paused"?"mdbase: Paused":s.kind==="offline"?"mdbase: Offline":s.kind==="device"?"mdbase: Set up sync":"mdbase: Needs attention",detail:s.kind==="offline"?`${s.title}. Changes will sync when it's back.`:s.title,destination:"sync"};if(c>0)return{state:"attention",label:`mdbase: Review ${c} ${c===1?"change":"changes"}`,detail:"Some changes need review before syncing",destination:"sync"};if(t?.recovery_required||t?.conflicts.length||t?.local_issues.length||["attention","blocked","failed","stale"].includes(t?.state??""))return{state:"attention",label:"mdbase: Needs attention",detail:"Review synchronization",destination:"sync"};if(t?.state==="cancelled")return{state:"paused",label:"mdbase: Paused",detail:"Review and resume synchronization",destination:"sync"};let l=t?.pending??0;return a||l>0||t?.state==="changes_waiting"||t?.state==="planned"?{state:"waiting",label:l>0?`mdbase: ${l} ${l===1?"change":"changes"}`:"mdbase: Changes waiting",detail:"Review local and hosted changes",destination:"sync"}:t?.state==="up_to_date"?{state:"synced",label:"mdbase: Synced",detail:"Local and hosted collections are aligned",destination:"sync"}:{state:"waiting",label:"mdbase: Ready to sync",detail:"Review the first synchronization",destination:"sync"}}var rj=new Set(["mirror_credentials_missing","invalid_mirror_enrollment","mirror_enrollment_expired","mirror_pairing_not_found","invalid_mirror_pairing","mirror_access_rejected","replica_revoked"]);function Dt(r){let e=ij(r);return e==="mirror_busy"?{code:e,kind:"busy",title:"Synchronization is already running",message:"The active transfer is still using this vault. Its progress is shown below.",action:"resume",actionLabel:"Show progress"}:e==="mirror_other_device"?{code:e,kind:"device",title:"Set up sync on this device",message:"This vault's sync settings came from another device or another copy of the vault, probably through a different sync service. Approve this copy to give it its own connection. Your files stay as they are.",action:"reauthorize",actionLabel:"Set up this device"}:rj.has(e)?{code:e,kind:"auth",title:"Connect approval is required again",message:"Your local files and mirror checkpoint are safe. Approve this vault again to restore access.",action:"reauthorize",actionLabel:"Sign in again"}:["operation_cancelled","cancelled","sync_cancelled","AbortError"].includes(e)?{code:e,kind:"paused",title:"Synchronization paused",message:"Completed changes are saved. Sync resumes from the same point when you continue.",action:"resume",actionLabel:"Resume sync"}:["stale","stale_mirror_plan","mirror_plan_stale","sync_plan_stale","conflict_decision_stale","mirror_conflict_copy_missing"].includes(e)?{code:e,kind:"decision",title:"The collection changed again",message:"No stale decision was applied. Review the newest local and hosted versions.",action:"review",actionLabel:"Review newest changes"}:["enrollment_recovery_required","mirror_recovery_required","pending_mirror_recovery"].includes(e)?{code:e,kind:"recovery",title:"Synchronization needs recovery",message:"Your original files are safe. Resume from the durable checkpoint before disconnecting this vault.",action:"resume",actionLabel:"Resume recovery"}:ks(r)?{code:e,kind:"offline",title:"Can't reach mdbase Connect",message:"Your changes are saved on this device and sync automatically when the connection returns.",action:"retry",actionLabel:"Retry now"}:{code:e,kind:"internal",title:"Sync stopped unexpectedly",message:`${sj(r,"An unexpected error stopped synchronization.")} Your files are safe. Sync tries again automatically; if this keeps happening, copy the diagnostics and report it.`,action:"retry",actionLabel:"Try again"}}function F$(r){return Dt(Object.assign(new Error(r.message),{code:r.code}))}function j$(r){return Array.isArray(r)?r.filter(nj).slice(-tj):[]}function nj(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;return typeof e.id=="string"&&typeof e.occurredAt=="string"&&typeof e.summary=="string"&&(e.detail===void 0||typeof e.detail=="string")&&(e.path===void 0||typeof e.path=="string")&&["success","info","attention","error"].includes(e.tone??"")&&typeof e.requiresAcknowledgement=="boolean"}function ij(r){return r instanceof DOMException?r.name:r&&typeof r=="object"&&"code"in r&&typeof r.code=="string"?r.code:r instanceof Error&&r.name?r.name:"sync_failed"}function sj(r,e){return r instanceof Error&&r.message?r.message:e}var kd=class{constructor(e){this.ctx=e;this.conflictComparisons=new Map;this.loadingConflictComparisons=new Set;this.pendingSyncFocus=null;this.historyQuery="";this.transferQuery="";this.transferFilter="all";this.transferPages=new Map;this.historyLimit=ka;this.previewComparisons=new Map;this.comparedPreview=null;this.loadingPreviewComparisons=new Set;this.enrollmentVerification="";this.enrollmentAbort=null;this.enrollmentControlUrl=_d;this.enrollmentMirrorName=M$(this.ctx.app.vault.getName());this.enrollmentCollectionId="";this.enrollmentMode="read_write";this.filePolicyDraft=null;this.adoptionFileProgress="";this.adoptionPreview=null;this.adoptionRenamePlan=null;this.adoptionStage="";this.adoptionFailed=!1}getState(){return{historyQuery:this.historyQuery}}setState(e){typeof e.historyQuery=="string"&&(this.historyQuery=e.historyQuery.slice(0,2e3))}get session(){return this.ctx.host.sync}dispose(){this.enrollmentAbort?.abort(),this.enrollmentAbort=null}focusSection(e){this.ctx.destination="sync",this.pendingSyncFocus=e,this.ctx.render(),window.setTimeout(()=>this.focusPendingSyncSection(),0)}async reconnectCollection(){await this.session.reconnect()==="reauthorize"&&await this.ctx.perform(()=>this.reauthorizeCollection())}render(e){let t=e.createDiv({cls:"mdbase-sync-document"}),n=this.ctx.host.getMirrorProfile();if(!n){this.renderEnrollment(t);return}let i=this.session.state,s=!!(i.fileProgress||i.progress),a=(i.problem?.kind==="busy"?null:i.problem)??(i.paused&&!s?{code:"sync_paused",kind:"paused",title:"Sync is paused",message:"Changes on this device and in Connect wait until you resume.",action:"resume",actionLabel:"Resume sync"}:i.status?.recovery_required?{code:"mirror_recovery_required",kind:"recovery",title:"Synchronization needs recovery",message:"Your original files are safe. Resume from the durable checkpoint before disconnecting this vault.",action:"resume",actionLabel:"Resume recovery"}:null),c=!!this.enrollmentAbort,l=i.preview,u=this.session.safety(),d=!!(l?.plan.actions.length||l?.entries.length),f=c?"Waiting for approval":s?"Syncing":i.busy?"Checking\u2026":a?.kind==="paused"?"Paused":a?.kind==="offline"?"Offline":a?.kind==="auth"?"Approval needed":a?.kind==="device"?"Set up this device":a?"Needs attention":d&&u&&!u.safe?"Review needed":l?.plan.actions.length?"Changes waiting":O$(i.status),p=t.createEl("section",{cls:"mdbase-sync-status"});p.setAttr("data-state",i.status?.state??"checking");let h=p.createDiv({cls:"mdbase-sync-heading"});h.createEl("h2",{text:n.name}),h.createDiv({cls:"mdbase-muted",text:`${f} \xB7 ${I$(i.status?.last_synced_at)}`});let m=h.createDiv({cls:"mdbase-muted mdbase-sync-scope"});m.createSpan({text:this.syncScopeText(n.mode)});let y=m.createEl("button",{cls:"mdbase-link-button",text:"Settings"});if(y.setAttr("aria-label","Open sync settings"),y.onclick=()=>this.ctx.host.openSettings(),i.message&&!i.problem){let v=p.createDiv({cls:"mdbase-inline-message mdbase-notice"});v.createSpan({text:i.message}).setAttr("role","status");let S=this.ctx.iconButton(v,"x","Dismiss sync message");S.onclick=()=>this.session.clearMessage()}if(s){let v=p.createDiv({cls:"mdbase-sync-progress",attr:{"aria-live":"polite"}}),S=i.fileProgress?.totalBytes??i.progress?.total??null,_=i.fileProgress?.transferredBytes??i.progress?.completed??0,E=v.createEl("progress");E.setAttr("aria-label","Sync progress"),E.max=S??1,E.value=S==null?0:_,S==null&&E.removeAttribute("value"),v.createDiv({cls:"mdbase-progress-label",text:i.fileProgress?`${i.fileProgress.direction==="upload"?"Uploading":"Downloading"} ${i.fileProgress.path} \xB7 ${yr(_)} of ${yr(S??0)}`:`${i.progress?.phase==="uploading"?"Uploading local changes":i.progress?.phase==="downloading"?"Downloading collection files":"Applying changes"} \xB7 ${_}${S==null?"":` of ${S}`}`});let A=v.createEl("button",{text:"Stop"});A.setAttr("data-focus-key","sync-stop"),A.onclick=()=>this.session.cancel()}let g=this.ctx.host.otherSyncServices();g.length&&p.createDiv({cls:"mdbase-inline-message mdbase-sync-coexistence",text:`${g.join(" and ")} also ${g.length===1?"syncs":"sync"} this vault. Two services syncing the same notes can duplicate them or bring deleted ones back; let only one of them sync this vault's notes.`}),c?this.renderApproval(p,!1):a&&this.renderRecoveryCard(p,a);let b=this.ctx.busy||i.busy||s;if(l!==this.comparedPreview&&(this.previewComparisons.clear(),this.comparedPreview=l,this.transferPages.clear()),d&&u&&!u.safe&&l?.plan.actions.length&&p.createDiv({cls:"mdbase-muted mdbase-review-reasons",text:`${u.reasons.join(", ")}.`}),!s&&!a&&!c){let v=p.createDiv({cls:"mdbase-sync-actions"});if(d&&l){let S=ny(l.plan,l.entries.length,b);if(l.plan.actions.length&&!S.actionDisabled){let E=v.createEl("button",{text:S.actionLabel,cls:"mod-cta"});E.setAttr("data-focus-key","sync-apply"),E.disabled=S.actionDisabled,E.onclick=()=>void this.session.apply()}let _=this.ctx.iconButton(v,"refresh-cw","Refresh review");_.disabled=b,_.onclick=()=>void this.session.review()}else{let S=v.createEl("button",{text:i.busy?"Checking\u2026":"Sync now",cls:"mod-cta"});S.setAttr("data-focus-key","sync-now"),S.disabled=b,S.onclick=()=>void this.session.syncNow()}}l&&d&&this.renderMirrorPreview(t,l),i.status?.conflicts.length&&this.renderConflicts(t,i.status),i.status?.local_issues.length&&!d&&this.renderLocalMirrorIssues(t,i.status),this.renderHistory(t),window.setTimeout(()=>this.focusPendingSyncSection(),0)}syncScopeText(e){let t=this.ctx.host.connectSync.getSelectiveSync().excluded_folders,n=t.length?`Whole vault except ${t.length>2?`${t.slice(0,2).join(", ")} +${t.length-2}`:t.join(", ")}`:"Whole vault";return`${e==="read_only"?"Read only":"Read and write"} \xB7 ${n}`}renderRecoveryCard(e,t){let n=e.createDiv({cls:"mdbase-recovery-card"});n.setAttr("data-kind",t.kind);let i=n.createDiv();i.createEl("strong",{text:t.title}),i.createDiv({text:t.message});let s=this.session.state.retryAt;if(s&&(t.kind==="offline"||t.kind==="internal")){let c=Math.max(0,Math.round((s-Date.now())/1e3));i.createDiv({cls:"mdbase-muted",text:c<=1?"Trying again now\u2026":c<60?`Trying again in ${c}s.`:`Trying again in ${Math.round(c/60)} min.`})}let o=n.createDiv({cls:"mdbase-recovery-actions"}),a=o.createEl("button",{text:t.actionLabel,cls:"mod-cta"});if(a.setAttr("data-focus-key","sync-recovery"),a.disabled=this.ctx.busy||this.session.state.busy,a.onclick=()=>{t.kind==="auth"?this.reconnectCollection():t.action==="reauthorize"?this.ctx.perform(()=>this.reauthorizeCollection()):t.action==="review"?this.session.review():this.session.syncNow()},t.kind==="internal"||t.kind==="recovery"){let c=o.createEl("button",{text:"Copy diagnostics"});c.setAttr("data-focus-key","sync-diagnostics"),c.disabled=this.ctx.busy,c.onclick=()=>void this.ctx.perform(async()=>{try{await this.ctx.host.copySyncDiagnostics()}finally{this.ctx.pendingFocusKey="sync-diagnostics"}})}}renderApproval(e,t=!0){let n=e.createDiv({cls:"mdbase-approval-link"});if(t&&n.createSpan({text:this.enrollmentVerification?"Waiting for approval \xB7 ":"Connecting\u2026 "}).setAttr("role","status"),this.enrollmentVerification){let s=n.createEl("a",{text:"Open Connect",href:this.enrollmentVerification});s.setAttr("target","_blank"),s.setAttr("rel","noopener noreferrer"),s.setAttr("data-focus-key","approval-link")}let i=n.createEl("button",{text:"Stop waiting"});i.setAttr("data-focus-key","stop-approval"),i.onclick=()=>{this.enrollmentAbort?.abort(),this.enrollmentVerification="",this.ctx.render()}}async reauthorizeCollection(){this.enrollmentAbort?.abort();let e=new AbortController;this.enrollmentAbort=e,this.ctx.pendingFocusKey="stop-approval",this.ctx.render();try{await this.session.reauthorize({signal:e.signal,onVerification:t=>{this.enrollmentVerification=t.verificationUri,this.ctx.message="",window.open(t.verificationUri,"_blank","noopener,noreferrer"),this.ctx.render()},onStatus:t=>{this.ctx.message=t.state==="waiting_for_approval"?"":`Connect is retrying approval (attempt ${t.attempt}).`,this.ctx.render()}}),this.ctx.message=""}catch(t){if(!xd(t))throw t;this.ctx.message="Cancelled. Your files and connection are unchanged.",this.ctx.pendingFocusKey="sync-recovery"}finally{this.enrollmentAbort===e&&(this.enrollmentAbort=null,this.enrollmentVerification="")}}renderHistory(e){let t=this.session.historyRuns();if(!t.length)return;let n=t.filter(d=>d.needsAcknowledgement),i=this.ctx.disclosure(e,"sync-activity","History",n.length>0);i.addClass("mdbase-activity"),i.id="mdbase-sync-activity";let s=i.parentElement;if(this.renderHistoryOnToggle(s),!s.open)return;for(let d of[...n].reverse())this.renderEventRow(i,d);let o=t.filter(d=>!d.needsAcknowledgement);if(!o.length)return;let a=i.createDiv({cls:"mdbase-section-header mdbase-history-controls"}),c=a.createEl("input",{type:"search"});if(c.setAttr("aria-label","Filter history by path"),c.setAttr("data-focus-key","history-search"),c.placeholder="Filter by path",c.value=this.historyQuery,c.oninput=()=>{this.historyQuery=c.value,this.historyLimit=ka,this.ctx.render()},t.length>n.length){let d=a.createEl("button",{text:"Clear history"});d.setAttr("data-focus-key","history-clear"),d.disabled=this.ctx.busy,d.onclick=()=>void this.ctx.perform(async()=>{await this.session.clearHistory(),this.ctx.pendingFocusKey=this.session.historyRuns().length?"disclosure-sync-activity":"destination-sync"})}let l=this.historyQuery.trim().toLowerCase(),u=Wx(o,l).sort((d,f)=>f.finishedAt.localeCompare(d.finishedAt));if(!u.length){i.createDiv({cls:"mdbase-muted",text:l?"No synced files match.":"No completed syncs."});return}for(let d of u.slice(0,this.historyLimit))Vx(d)?this.renderEventRow(i,d):this.renderHistoryRun(i,d,l!=="");if(u.length>this.historyLimit){let d=i.createEl("button",{cls:"mdbase-link-button",text:`Show ${Math.min(ka,u.length-this.historyLimit)} more`});d.setAttr("data-focus-key","history-more"),d.onclick=()=>{this.historyLimit+=ka,this.ctx.render()}}}renderHistoryOnToggle(e){let t=e.open;e.addEventListener("toggle",()=>{this.ctx.containerEl.contains(e)&&e.open!==t&&this.ctx.render()})}renderHistoryRun(e,t,n){let i=e.createEl("details",{cls:"mdbase-history-run"}),s=`history-run-${t.id}`;n?i.open=!0:(i.dataset.disclosure=s,i.open=this.ctx.disclosures.get(s)??!1);let o=i.createEl("summary",{cls:"mdbase-activity-row"});o.setAttr("data-focus-key",`disclosure-${s}`);let a=t.outcome==="applied"?"success":t.outcome==="failed"?"error":"attention";o.setAttr("data-tone",a),(0,Is.setIcon)(o.createSpan(),a==="success"?"check":"circle-alert");let c=o.createDiv();c.createEl("strong",{text:zx(t)});let l=T$[t.outcome];if(c.createSpan({cls:"mdbase-muted",text:l?`${As(t.finishedAt)} \xB7 ${l}`:As(t.finishedAt)}),t.message&&t.outcome!=="applied"&&c.createDiv({text:t.message}),(0,Is.setIcon)(o.createSpan({cls:"mdbase-history-chevron"}),"chevron-right"),this.renderHistoryOnToggle(i),!i.open)return;let u=i.createDiv({cls:"mdbase-transfer-ledger mdbase-history-files"});for(let d of t.files.slice(0,250)){let f=u.createDiv({cls:"mdbase-transfer-row"});f.setAttr("title",new Date(d.at).toLocaleString()),f.createSpan({cls:"mdbase-transfer-action",text:d.action}).setAttr("data-action",d.status==="completed"?d.action:"fix");let h=f.createDiv({cls:"mdbase-transfer-body"}),m=h.createDiv({cls:"mdbase-transfer-path"}),y=m.createSpan({cls:"mdbase-history-direction"}),g=d.direction==="download"?"Downloaded":d.direction==="upload"?"Uploaded":"Needs attention";if(y.setAttr("aria-label",g),y.setAttr("title",g),(0,Is.setIcon)(y,d.direction==="download"?"download":d.direction==="upload"?"upload":"circle-alert"),d.action!=="delete"&&this.ctx.app.vault.getAbstractFileByPath(d.path)){let b=m.createEl("button",{cls:"mdbase-link-button mdbase-transfer-open"});b.createEl("code",{text:d.path}),b.setAttr("title",`Open ${d.path}`),b.setAttr("data-focus-key",`history-open-${t.id}-${d.path}`),b.onclick=()=>void this.ctx.host.openFileByPath(d.path)}else m.createEl("code",{text:d.path});d.fromPath&&h.createDiv({cls:"mdbase-muted",text:`From ${d.fromPath}`}),d.status!=="completed"&&h.createDiv({text:d.message?`${ry(d.status)}: ${d.message}`:ry(d.status)})}t.files.length>250&&u.createDiv({cls:"mdbase-transfer-more",text:`${t.files.length-250} more files are recorded in this sync.`})}renderEventRow(e,t){let n=t.tone??"info",i=e.createDiv({cls:"mdbase-activity-row"});i.setAttr("data-tone",n),(0,Is.setIcon)(i.createSpan(),n==="success"?"check":n==="info"?"info":"circle-alert");let s=i.createDiv(),o=t.summary??"";if(t.message&&t.message!==o){let a=s.createEl("details"),c=`history-event-${t.id}`;a.dataset.disclosure=c,a.open=this.ctx.disclosures.get(c)??!!t.needsAcknowledgement,a.createEl("summary",{text:o}).setAttr("data-focus-key",`disclosure-${c}`),a.createDiv({text:t.message})}else s.createEl("strong",{text:o});if(s.createSpan({cls:"mdbase-muted",text:As(t.finishedAt)}),t.path&&this.ctx.app.vault.getAbstractFileByPath(t.path)){let a=t.path,c=s.createEl("button",{cls:"mdbase-link-button mdbase-transfer-open",text:a});c.setAttr("title",`Open ${a}`),c.setAttr("data-focus-key",`event-open-${t.id}`),c.onclick=()=>void this.ctx.host.openFileByPath(a)}if(t.needsAcknowledgement){let a=i.createEl("button",{text:"Dismiss"});a.setAttr("data-focus-key",`event-dismiss-${t.id}`),a.disabled=this.ctx.busy,a.onclick=()=>void this.ctx.perform(async()=>{await this.session.dismissEvent(t.id),this.ctx.pendingFocusKey=t.message&&t.message!==o?`disclosure-history-event-${t.id}`:"disclosure-sync-activity"})}}focusPendingSyncSection(){if(!this.pendingSyncFocus)return;let e=this.pendingSyncFocus==="activity"?"mdbase-sync-activity":"mdbase-sync-conflicts",t=this.ctx.containerEl.querySelector(`#${e}`);if(!t)return;this.pendingSyncFocus=null;let n=t.closest("details");n&&(n.open=!0),t.scrollIntoView({block:"nearest"})}filePolicy(){return this.filePolicyDraft??=JSON.parse(JSON.stringify(this.ctx.host.connectSync.getSelectiveSync())),this.filePolicyDraft}renderFilePolicyControls(e){let t=this.filePolicy(),n=e.createEl("section",{cls:"mdbase-editor-section mdbase-file-policy"});n.createEl("h3",{text:"Attachments"});let i=n.createDiv({cls:"mdbase-file-class-grid"}),s=[["image","Images"],["audio","Audio"],["video","Video"],["pdf","PDFs"],["other","Other files"]];for(let[o,a]of s){let c=i.createEl("label"),l=c.createEl("input",{type:"checkbox"});l.setAttr("data-focus-key",`file-class-${o}`),l.checked=t.file_classes.includes(o),l.onchange=()=>{t.file_classes=l.checked?[...new Set([...t.file_classes,o])]:t.file_classes.filter(u=>u!==o),this.ctx.render()},c.createSpan({text:a})}n.createDiv({cls:"mdbase-form-description",text:$d}),n.createEl("h4",{text:"Excluded folders"}),Ed(this.ctx.app,n,t.excluded_folders,o=>{t.excluded_folders=o}),t.file_classes.includes("other")&&n.createDiv({cls:"mdbase-inline-message",text:"Other files includes all remaining visible file formats."})}renderEnrollment(e){if(this.ctx.schema||this.ctx.host.connectSync.getAdoptionMarker()){this.renderLocalAdoption(e);return}let t=e.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});if(t.createEl("h3",{text:"Copy a collection from Connect"}),t.createEl("p",{cls:"mdbase-muted",text:"Connect holds the collection; this vault syncs a copy. Choose a collection in Connect, then review the first sync."}),this.enrollmentAbort){this.renderApproval(t);return}Ot(t,"Device name",this.enrollmentMirrorName,p=>{this.enrollmentMirrorName=p});let n=t.createDiv({cls:"mdbase-form-row"}),i=n.createEl("label",{text:"Access"}),s=n.createEl("select");i.htmlFor=s.id="mdbase-enrollment-access",s.setAttr("data-focus-key","enrollment-access"),s.createEl("option",{value:"read_write",text:"Read and write"}),s.createEl("option",{value:"read_only",text:"Read only"}),s.value=this.enrollmentMode,s.onchange=()=>{this.enrollmentMode=s.value==="read_only"?"read_only":"read_write",this.ctx.render()};let o=t.createDiv({cls:"mdbase-form-row mdbase-sync-target"});o.createEl("label",{text:"Syncs"});let a=o.createDiv({cls:"mdbase-sync-target-value"}),c=this.filePolicy().excluded_folders;a.createSpan({text:`Whole vault \u201C${this.ctx.app.vault.getName()}\u201D${c.length?` except ${c.join(", ")}`:""}`});let l=a.createEl("button",{cls:"mdbase-link-button",text:"Exclude folders"});l.onclick=()=>{this.ctx.disclosures.set("enrollment-options",!0),this.ctx.render()},t.createEl("p",{cls:"mdbase-form-description",text:this.enrollmentMode==="read_write"?"Existing notes may upload. Nothing moves until you review and sync.":"Downloads only. Existing local changes must be resolved or excluded."});let u=this.ctx.disclosure(t,"enrollment-options","Advanced");Ot(u,"Connect URL",this.enrollmentControlUrl,p=>{this.enrollmentControlUrl=p},{placeholder:_d}),Ot(u,"Collection ID",this.enrollmentCollectionId,p=>{this.enrollmentCollectionId=p},{placeholder:"Choose during approval"}),this.renderFilePolicyControls(u);let f=t.createDiv({cls:"mdbase-actions mdbase-enrollment-actions"}).createEl("button",{text:"Connect"});f.setAttr("title","Opens Connect in your browser to choose a collection"),f.setAttr("data-focus-key","enrollment-connect"),f.addClass("mod-cta"),f.disabled=this.ctx.busy,f.onclick=()=>void this.ctx.perform(async()=>{this.enrollmentAbort?.abort();let p=new AbortController;this.enrollmentAbort=p,this.ctx.pendingFocusKey="stop-approval",this.ctx.render();try{await this.ctx.host.connectSync.enroll({controlUrl:this.enrollmentControlUrl,mirrorName:this.enrollmentMirrorName,mode:this.enrollmentMode,selectiveSync:this.filePolicy(),...this.enrollmentCollectionId.trim()?{collectionId:this.enrollmentCollectionId.trim()}:{}},{signal:p.signal,onVerification:y=>{this.enrollmentVerification=y.verificationUri,this.ctx.message="",window.open(y.verificationUri,"_blank","noopener,noreferrer"),this.ctx.render()},onStatus:y=>{this.ctx.message=y.state==="waiting_for_approval"?"":`Connect is retrying enrollment (attempt ${y.attempt}).`,this.ctx.render()}}),this.enrollmentVerification="",this.enrollmentAbort===p&&(this.enrollmentAbort=null);let h=await this.session.syncNow(),m=this.session.state.preview;if(h==="needs_review"&&m){let y=m.entries.reduce((b,v)=>b+(v.estimatedBytes??0),0),g=m.entries.length;this.ctx.message=`Connected. Review ${g} ${g===1?"item":"items"}${y?` \xB7 ${yr(y)}`:""} before syncing.`,this.ctx.pendingFocusKey="sync-apply"}else this.ctx.message="",this.ctx.pendingFocusKey=this.session.state.problem?"sync-recovery":h==="busy"?"sync-stop":"sync-now"}catch(h){if(this.ctx.pendingFocusKey="enrollment-connect",!xd(h))throw h;this.enrollmentVerification="",this.ctx.message="Cancelled. No files synced."}finally{this.enrollmentAbort===p&&(this.enrollmentAbort=null,this.enrollmentVerification="")}})}renderLocalAdoption(e){let t=this.ctx.host.connectSync.getAdoptionMarker(),n=t?this.ctx.host.connectSync.getAdoptionRecovery():null,i=!t||["waiting_for_approval","uploading"].includes(t.phase),s=i?this.adoptionPreview?.conflicts??[]:[],o=e.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});o.createEl("h3",{text:"Upload to Connect"}),o.createEl("p",{cls:"mdbase-muted",text:n?n.canReset?"This upload expired and its device authorization is missing. Reset setup to start again. Your files stay local.":n.canReconnect?"Device authorization is unavailable. Reconnect to the hosted collection through Connect. This vault stays protected until approval succeeds.":`Device authorization is unavailable. Restore Obsidian's secret storage, or reset setup after ${new Date(t?.session.expiresAt??"").toLocaleString()}.`:this.ctx.busy&&this.adoptionStage?this.adoptionStage:t?t.phase==="waiting_for_approval"?"Not connected yet. Approval is pending in Connect.":t.phase==="adopted"?"Collection is hosted. Finish connecting this device.":t.phase==="activating"?"Activation outcome is pending. Resume to check it safely.":s.length||this.adoptionFailed?"Approval received. Upload stopped; this vault is not connected yet.":"Approval received. Transfer is not running; resume to continue.":"This vault holds the collection. Upload it to Connect to sync it with other devices; Connect then holds the collection and this vault syncs a copy.",attr:{role:"status","aria-live":"polite"}});let a=this.enrollmentVerification||(!n&&t?.phase==="waiting_for_approval"?t.session.verificationUri:void 0);if(a){let u=o.createDiv({cls:"mdbase-approval-link"});u.createSpan({text:"Approval page: "});let d=u.createEl("a",{text:"Open Connect",href:a});d.setAttr("target","_blank"),d.setAttr("rel","noopener noreferrer")}if(t&&(this.enrollmentControlUrl=t.session.controlUrl,this.enrollmentMirrorName=t.session.requested.mirrorName??"Obsidian"),t){let u=this.ctx.disclosure(o,"adoption-details","Details");Gt(u,"Collection",t.session.requested.collectionId),Gt(u,"Phase",t.phase.replace(/_/g," ")),Gt(u,"Connect",t.session.controlUrl);let d=this.ctx.host.connectSync.getSelectiveSync();Gt(u,"Files",d.file_classes.length?d.file_classes.join(", "):"Markdown only")}else{Ot(o,"Device name",this.enrollmentMirrorName,d=>{this.enrollmentMirrorName=d});let u=this.ctx.disclosure(o,"adoption-options","Advanced");Ot(u,"Connect URL",this.enrollmentControlUrl,d=>{this.enrollmentControlUrl=d},{placeholder:_d}),this.renderFilePolicyControls(u)}!n&&i&&(this.adoptionPreview&&o.createEl("p",{cls:"mdbase-muted",text:`${this.adoptionPreview.records.toLocaleString()} notes \xB7 ${this.adoptionPreview.files.toLocaleString()} attachments`}),s.length&&(o.createEl("h4",{text:`${s.length} filename conflicts`}),this.renderAdoptionRenameReview(o,s))),n||o.createEl("p",{cls:"mdbase-form-description",text:"Sync starts only after the upload completes."});let c=o.createDiv({cls:"mdbase-actions mdbase-enrollment-actions"});if(!n&&i){let u=c.createEl("button",{text:"Check files"});u.disabled=this.ctx.busy,u.onclick=()=>void this.ctx.perform(async()=>{this.adoptionRenamePlan=null,this.adoptionPreview=await this.ctx.host.connectSync.previewAdoption(this.filePolicy()),this.ctx.message=this.adoptionPreview.conflicts.length?"Resolve the listed filename conflicts before continuing.":"Files checked. No filename conflicts."})}if(n&&!n.canReconnect){if(n.canReset){let u=c.createEl("button",{text:"Reset setup",cls:"mod-cta"});u.disabled=this.ctx.busy,u.onclick=()=>void this.ctx.perform(async()=>{this.filePolicyDraft=this.ctx.host.connectSync.getSelectiveSync(),await this.ctx.host.connectSync.resetExpiredAdoption(),this.enrollmentVerification="",this.ctx.message="Expired setup cleared. Your files and collection identity are unchanged. Start a new upload to approve this device again.",await this.ctx.refresh(!0)})}else{let u=c.createEl("button",{text:"Check again"});u.disabled=this.ctx.busy,u.onclick=()=>this.ctx.render()}return}if(t&&!n&&!["activating","adopted"].includes(t.phase)){let u=c.createEl("button",{text:"Cancel upload"});u.disabled=this.ctx.busy,u.onclick=()=>void this.ctx.perform(async()=>{await this.ctx.host.connectSync.cancelAdoption(),this.enrollmentVerification="",this.ctx.message="Upload cancelled. The collection is still local.",await this.ctx.refresh(!0)})}if(this.enrollmentAbort){let u=c.createEl("button",{text:t?.phase==="waiting_for_approval"?"Stop waiting":"Pause upload"});u.onclick=()=>{this.enrollmentAbort?.abort(),this.ctx.message="Upload paused. Resume when ready.",this.ctx.render()}}let l=c.createEl("button",{text:n?"Reconnect collection":t?"Resume upload":"Upload to Connect"});l.addClass("mod-cta"),l.disabled=this.ctx.busy||!n&&s.length>0,l.onclick=()=>void this.ctx.perform(async()=>{this.adoptionFailed=!1,this.adoptionStage="Checking files\u2026",this.enrollmentAbort?.abort();let u=new AbortController;this.enrollmentAbort=u;let d=y=>{this.enrollmentVerification=y.verificationUri,this.adoptionStage="Waiting for approval in Connect\u2026",this.ctx.message="Approve the upload in Connect.",this.ctx.render()},f=y=>{this.ctx.message=y.state==="waiting_for_approval"?"Waiting for upload approval in Connect\u2026":`Connect is retrying (attempt ${y.attempt}).`,this.ctx.render()},p=y=>{this.adoptionStage=y.stage==="checking"?"Checking files\u2026":y.stage==="uploading"?`Approval received. Uploading ${y.records?.toLocaleString()??""} notes\u2026`:y.stage==="activating"?"Activating hosted collection. Keep this vault open\u2026":"Finishing this device's connection\u2026",this.enrollmentVerification="",this.ctx.message="",this.ctx.render()},h=(y,g,b)=>{this.adoptionFileProgress=`${y} \xB7 ${yr(g)} of ${yr(b)}`,this.adoptionStage=`Uploading ${this.adoptionFileProgress}`,this.ctx.render()},m={signal:u.signal,onVerification:d,onStatus:f,onFileProgress:h,onProgress:p};try{n?await this.ctx.host.connectSync.reconnectAdoption(m):t?await this.ctx.host.connectSync.resumeAdoption(m):await this.ctx.host.connectSync.adoptLocalCollection({controlUrl:this.enrollmentControlUrl,mirrorName:this.enrollmentMirrorName,selectiveSync:this.filePolicy()},m),this.enrollmentVerification="",this.ctx.message="Collection hosted. This vault is now connected.",await this.ctx.refresh(!0)}catch(y){if(this.ctx.host.connectSync.getAdoptionMarker()?.phase!=="waiting_for_approval"&&(this.enrollmentVerification=""),!xd(y))throw this.adoptionFailed=!0,await this.ctx.host.connectSync.previewAdoption(this.filePolicy()).then(g=>{this.adoptionPreview=g}).catch(()=>{}),y;this.ctx.message="Upload paused. Resume when ready."}finally{this.adoptionStage="",this.enrollmentAbort===u&&(this.enrollmentAbort=null)}})}renderAdoptionRenameReview(e,t){let n=this.adoptionRenamePlan;e.createEl("p",{text:n?"Keep both files with distinct names. Nothing is merged or deleted. Link updates follow your Obsidian settings.":"Names must also be distinct on case-insensitive devices. Review suggested names, or rename the files yourself."});let i=e.createEl("ul",{cls:"mdbase-adoption-conflicts"}),s=n?n.renames.map(l=>[l.from,l.to]):t;for(let l of s){let u=i.createEl("li");l.forEach((d,f)=>{f&&u.appendText(n?" \u2192 ":" \u2194 "),u.createEl("code",{text:d})})}n?.manual.length&&e.createEl("p",{text:"Collection-resource conflicts need manual review: "+n.manual.map(l=>l.join(" \u2194 ")).join("; ")});let o=e.createDiv({cls:"mdbase-actions"});if(!n){let l=o.createEl("button",{text:"Review renames\u2026"});l.disabled=this.ctx.busy,l.onclick=()=>void this.ctx.perform(async()=>{this.adoptionRenamePlan=await this.ctx.host.connectSync.planAdoptionRenames(this.filePolicy())});return}let a=o.createEl("button",{text:`Rename ${n.renames.length} ${n.renames.length===1?"file":"files"}`,cls:"mod-cta"});a.disabled=this.ctx.busy||!n.renames.length,a.onclick=()=>void this.ctx.perform(async()=>{try{let l=await this.ctx.host.connectSync.applyAdoptionRenames(n,this.filePolicy(),(u,d)=>{this.adoptionStage=`Renaming ${u} of ${d} files\u2026`,this.ctx.render()});this.ctx.message=`Renamed ${l} ${l===1?"file":"files"}. Review the file check, then resume the upload.`}finally{this.adoptionStage="",this.adoptionRenamePlan=null,await this.ctx.host.connectSync.previewAdoption(this.filePolicy()).then(l=>{this.adoptionPreview=l}).catch(()=>{})}});let c=o.createEl("button",{text:"Cancel"});c.disabled=this.ctx.busy,c.onclick=()=>{this.adoptionRenamePlan=null,this.ctx.render()}}renderMirrorPreview(e,t){let n=e.createEl("section",{cls:"mdbase-transfer-review"}),i=n.createDiv({cls:"mdbase-transfer-heading"});i.createDiv().createEl("h3",{text:t.phase==="initial"?"First sync":"Changes"});let o=t.entries.reduce((p,h)=>p+(h.estimatedBytes??0),0);i.createSpan({cls:"mdbase-transfer-total",text:t.entries.length?`${t.entries.length} ${t.entries.length===1?"item":"items"}${o?` \xB7 ${yr(o)}`:""}`:"No changes"});let a=n.createDiv({cls:"mdbase-issue-controls"}),c=a.createEl("input",{type:"search",placeholder:"Search transfer paths"});c.setAttr("aria-label","Search transfer paths"),c.setAttr("data-focus-key","transfer-search"),c.value=this.transferQuery,c.oninput=()=>{this.transferQuery=c.value,this.transferPages.clear(),this.ctx.render()};let l=a.createEl("select");l.setAttr("aria-label","Filter transfers"),l.setAttr("data-focus-key","transfer-filter");for(let[p,h]of[["all","All changes"],["delete","Deletes"],["replace","Replacements"],["upload","Uploads"],["download","Downloads"],["attention","Needs attention"]])l.createEl("option",{value:p,text:h});l.value=this.transferFilter,l.onchange=()=>{this.transferFilter=l.value,this.transferPages.clear(),this.ctx.render()};let u=this.transferQuery.trim().toLowerCase(),d=t.entries.filter(p=>(!u||`${p.path} ${p.detail}`.toLowerCase().includes(u))&&(this.transferFilter==="all"||p.action===this.transferFilter||p.direction===this.transferFilter));d.length||n.createDiv({cls:"mdbase-muted",text:"No changes match these filters."}),n.createDiv({cls:"mdbase-muted",text:`Showing ${d.length} of ${t.entries.length} items. Approval always applies to the entire reviewed plan, not just these filters.`});let f=[{direction:"download",title:"Downloads"},{direction:"upload",title:"Uploads"},{direction:"attention",title:"Needs attention"}];for(let p of f){let h=d.filter(_=>_.direction===p.direction);if(!h.length)continue;let m=n.createEl("section",{cls:"mdbase-transfer-group"});m.setAttr("data-direction",p.direction);let y=m.createDiv({cls:"mdbase-transfer-group-heading"}),g=y.createSpan({cls:"mdbase-transfer-group-icon"});(0,Is.setIcon)(g,p.direction==="download"?"download":p.direction==="upload"?"upload":"circle-alert"),y.createEl("h4",{text:p.title}),y.createSpan({text:String(h.length),cls:"mdbase-transfer-count"});let b=m.createDiv({cls:"mdbase-transfer-ledger"}),v=Math.min(this.transferPages.get(p.direction)??0,Math.floor((h.length-1)/250)),S=v*250;for(let _ of h.slice(S,S+250)){let E=b.createDiv({cls:"mdbase-transfer-row"});E.createSpan({cls:"mdbase-transfer-action",text:_.action}).setAttr("data-action",_.action);let x=E.createDiv({cls:"mdbase-transfer-body"}),R=x.createDiv({cls:"mdbase-transfer-path"}),$=this.ctx.app.vault.getAbstractFileByPath(_.path)?_.path:null;if($){let M=R.createEl("button",{cls:"mdbase-link-button mdbase-transfer-open"});M.createEl("code",{text:_.path}),M.setAttr("title",`Open ${_.path}`),M.setAttr("data-focus-key",`preview-open-${_.path}`),M.onclick=()=>void this.ctx.host.openFileByPath($)}else R.createEl("code",{text:_.path});_.estimatedBytes!==void 0&&R.createSpan({cls:"mdbase-transfer-size",text:yr(_.estimatedBytes)}),_.direction==="attention"||["rename","replace","delete"].includes(_.action)?x.createDiv({text:_.detail}):E.setAttr("title",_.detail);let q=_.recordId;if(q&&_.kind==="document"&&_.action==="update"&&$){let M=`${q}:${_.path}`,V=this.previewComparisons.get(M),P=E.createEl("button",{text:V?"Hide":this.loadingPreviewComparisons.has(M)?"Loading\u2026":"Compare"});P.setAttr("data-focus-key",`preview-compare-${M}`),P.disabled=this.loadingPreviewComparisons.has(M),P.onclick=()=>{V?(this.previewComparisons.delete(M),this.ctx.render()):this.loadPreviewComparison(M,q,_.path)},V&&this.renderConflictComparison(x,V)}}if(h.length>250){let _=b.createDiv({cls:"mdbase-actions"});_.createSpan({cls:"mdbase-muted",text:`Showing ${S+1}\u2013${Math.min(S+250,h.length)} of ${h.length}`});let E=_.createEl("button",{text:`Previous ${p.title.toLowerCase()}`});E.disabled=v===0,E.setAttr("data-focus-key",`transfer-previous-${p.direction}`),E.onclick=()=>{this.transferPages.set(p.direction,v-1),this.ctx.render()};let A=_.createEl("button",{text:`Next ${p.title.toLowerCase()}`});A.disabled=S+250>=h.length,A.setAttr("data-focus-key",`transfer-next-${p.direction}`),A.onclick=()=>{this.transferPages.set(p.direction,v+1),this.ctx.render()}}}t.collisions.length?n.createDiv({cls:"mdbase-inline-error",text:"Colliding files and related moves are left unchanged. Independent files can still sync. Move or rename the obstruction, then review again."}):t.local_issues.length&&n.createDiv({cls:"mdbase-inline-message",text:t.plan.summary.blocking_issues>0?ny(t.plan,t.entries.length).message:"These diagnostics do not block synchronization. Document bytes are preserved unchanged."})}renderConflicts(e,t){let n=e.createEl("section",{cls:"mdbase-editor-section"});n.id="mdbase-sync-conflicts",n.createEl("h3",{text:"Conflicts"});for(let i of t.conflicts){let s=n.createDiv({cls:"mdbase-conflict-row"}),o=s.createDiv({cls:"mdbase-conflict-summary"});o.createEl("strong",{text:i.path??i.object_id}),o.createDiv({text:i.message});let a=s.createDiv({cls:"mdbase-actions"}),c=`${i.object_id}:${i.decision_id}`,l=this.conflictComparisons.get(c),u=a.createEl("button",{text:l?"Hide":this.loadingConflictComparisons.has(c)?"Loading\u2026":"Resolve\u2026"});if(u.setAttr("data-focus-key",`compare-${c}`),u.disabled=this.ctx.busy||this.loadingConflictComparisons.has(c),u.onclick=()=>{if(l){this.conflictComparisons.delete(c),this.ctx.render();return}this.loadConflictComparison(i,c)},l){for(let d of["local","remote"]){let f=l[d].state==="absent",p=a.createEl("button",{text:d==="local"?f?"Delete from Connect":"Keep local":f?"Move local file to trash":"Use hosted",cls:f?"mod-warning":""});p.setAttr("data-focus-key",`resolve-${c}-${d}`),p.disabled=this.ctx.busy,p.onclick=()=>void this.resolveMirrorConflict(i,d,!1)}if(i.path&&l.local.state==="exact"){let d=a.createEl("button",{text:l.remote.state==="absent"?"Keep a local copy":"Keep both"});d.setAttr("data-focus-key",`resolve-${c}-both`),d.disabled=this.ctx.busy,d.onclick=()=>void this.resolveMirrorConflict(i,"remote",!0)}this.renderConflictComparison(s,l,!!i.path)}}}async loadPreviewComparison(e,t,n){this.loadingPreviewComparisons.add(e),this.ctx.render();try{this.previewComparisons.set(e,await this.ctx.host.connectSync.recordComparison(t,n))}catch(i){this.ctx.message=Dt(i).message}finally{this.loadingPreviewComparisons.delete(e),this.ctx.render()}}async loadConflictComparison(e,t){this.loadingConflictComparisons.add(t),this.ctx.render();try{this.conflictComparisons.set(t,await this.ctx.host.connectSync.conflictComparison(e))}catch(n){this.session.reportProblem(n).code==="conflict_decision_stale"&&await this.session.refreshStatus()}finally{this.loadingConflictComparisons.delete(t),this.ctx.render()}}renderConflictComparison(e,t,n=!1){let i=e.createDiv({cls:"mdbase-conflict-comparison"});if(t.local.state==="absent"&&i.createDiv({cls:"mdbase-muted",text:"No local version."}),t.remote.state==="absent"&&i.createDiv({cls:"mdbase-muted",text:n&&t.local.state==="exact"?"No hosted version. Keeping a local copy saves this device's version before moving the original to trash.":"No hosted version."}),t.entity==="record"){let o=N$(t.local.document??"",t.remote.document??""),a=i.createDiv({cls:"mdbase-conflict-legend"});a.createSpan({text:"\u2212 Local only",cls:"is-local"}),a.createSpan({text:"+ Hosted only",cls:"is-remote"});let c=i.createEl("pre",{cls:"mdbase-conflict-diff"});for(let l of o.lines){let u=c.createEl("div",{cls:`is-${l.kind}`});u.createSpan({text:l.kind==="local"?"\u2212":l.kind==="remote"?"+":" "}),u.createSpan({text:l.value||" "})}o.truncated&&i.createDiv({cls:"mdbase-muted",text:"Diff shortened for a responsive review. Open the local note to inspect it in full."});return}let s=i.createDiv({cls:"mdbase-conflict-sides"});this.renderConflictSide(s,"Local",t.local),this.renderConflictSide(s,"Hosted",t.remote)}renderConflictSide(e,t,n){let i=e.createDiv({cls:"mdbase-conflict-side"});if(i.createEl("h4",{text:t}),n.state==="absent"){i.createDiv({cls:"mdbase-muted",text:"File is absent in this version."});return}if(n.path&&i.createEl("code",{text:n.path}),n.size!==void 0&&i.createDiv({text:`Size: ${yr(n.size)}`}),n.modifiedAt&&i.createDiv({text:`Modified: ${new Date(n.modifiedAt).toLocaleString()}`}),n.revision&&i.createDiv({cls:"mdbase-conflict-digest",text:`Digest: ${n.revision}`}),n.resourceUrl&&n.path&&/\.(?:avif|gif|jpe?g|png|svg|webp)$/i.test(n.path)){let s=i.createEl("img",{cls:"mdbase-conflict-image-preview"});s.src=n.resourceUrl,s.alt=`${t} preview of ${n.path}`}else t==="Hosted"&&i.createDiv({cls:"mdbase-muted",text:"Hosted binary preview is materialized only after you choose it."})}async resolveMirrorConflict(e,t,n){await this.ctx.perform(async()=>{await this.session.resolveConflict(e,t,n)&&this.conflictComparisons.delete(`${e.object_id}:${e.decision_id}`)})}renderLocalMirrorIssues(e,t){let n=e.createEl("section",{cls:"mdbase-editor-section"});n.createEl("h3",{text:"Local files needing attention"}),n.createEl("p",{text:"Review these file diagnostics. The sync preview identifies which issues block synchronization; a diagnostic alone does not mean syncing is paused."});for(let i of t.local_issues){let s=n.createDiv({cls:"mdbase-conflict-row"}),o=s.createDiv({cls:"mdbase-conflict-summary"});o.createEl("strong",{text:i.path}),o.createDiv({text:i.message});let c=s.createDiv({cls:"mdbase-actions"}).createEl("button",{text:"Open file"});c.setAttr("data-focus-key",`issue-open-${i.path}`),c.disabled=this.ctx.busy,c.onclick=()=>void this.ctx.host.openFileByPath(i.path)}}async refresh(){if(!this.session.isSyncing()){if(!this.ctx.host.getMirrorProfile()){if(!this.ctx.schema||this.enrollmentAbort)return;try{this.adoptionPreview=await this.ctx.host.connectSync.previewAdoption(this.filePolicy())}catch(e){this.ctx.message=Dt(e).message}return}await this.session.refreshStatus()}}};var tt=require("obsidian");Vt();function q$(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Os(r){return typeof r=="number"&&Number.isFinite(r)?r:null}function iy(r,e,t=""){let n=t?` ${t}`:"";return r!==null&&e!==null?r===e?`${r}${n}`:`${r}\u2013${e}${n}`:r!==null?`\u2265 ${r}${n}`:e!==null?`\u2264 ${e}${n}`:null}function an(r){return typeof r=="string"?r:typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r):JSON.stringify(r)??""}function sy(r){let e=an(r);return e.length>24?`${e.slice(0,23)}\u2026`:e}function B$(r){let e=typeof r.type=="string"?r.type:"any",t=[];if(e==="enum"&&Array.isArray(r.values)){let n=r.values.map(sy);t.push(n.length>3?`${n.slice(0,3).join(", ")}, +${n.length-3}`:n.join(", ")||"no values")}if(e==="integer"||e==="number"){let n=iy(Os(r.min),Os(r.max));n&&t.push(n)}if(e==="list"){let n=iy(Os(r.min_length),Os(r.max_length),"items");n&&t.push(n),q$(r.items)&&typeof r.items.type=="string"&&t.push(`of ${r.items.type}`)}else{let n=iy(Os(r.min_length),Os(r.max_length),"chars");n&&t.push(n)}if(typeof r.pattern=="string"&&r.pattern&&t.push(`/${sy(r.pattern)}/`),e==="link"&&typeof r.target=="string"&&r.target&&t.push(`\u2192 ${r.target}`),e==="object"&&q$(r.fields)){let n=Object.keys(r.fields).length;t.push(`${n} ${n===1?"field":"fields"}`)}return r.default!==void 0&&t.push(`default ${sy(r.default)}`),r.unique===!0&&t.push("unique"),r.deprecated===!0&&t.push("deprecated"),t}function U$(r,e,t){if(e!==void 0&&an(e)===r)return e;let n=r.trim()!==""&&Number.isFinite(Number(r)),i=r==="true"||r==="false",s=o=>t.length>0&&t.every(a=>typeof a===o);return n&&(typeof e=="number"||typeof e!="boolean"&&s("number"))?Number(r):i&&(typeof e=="boolean"||typeof e!="number"&&s("boolean"))?r==="true":r}function V$(r,e){if(r==="")return{};if(e==="integer"||e==="number"){let t=Number(r);return Number.isFinite(t)?e==="integer"&&!Number.isInteger(t)?{error:"Default must be a whole number."}:{value:t}:{error:"Default must be a number."}}return e==="boolean"?r==="true"?{value:!0}:r==="false"?{value:!1}:{error:"Default must be true or false."}:{value:r}}var Vn=require("@codemirror/commands"),Hn=require("@codemirror/language"),Jt=require("@codemirror/state"),Et=require("@codemirror/view"),Un=require("@lezer/highlight"),oj=Hn.StreamLanguage.define({startState:()=>({section:"start"}),copyState:r=>({...r}),token(r,e){return r.sol()&&r.match(/^---\s*$/)?(e.section=e.section==="start"?"yaml":"body","meta"):e.section==="body"?(r.skipToEnd(),null):(e.section==="start"&&(e.section="yaml"),r.eatSpace()?null:r.match("#")?(r.skipToEnd(),"comment"):r.match(/^-(?=\s|$)/)?"punctuation":r.match(/^(?:[^\s:#'"[\]{},][^:#]*?|"[^"]*"|'[^']*')(?=\s*:(?:\s|$))/)?"propertyName":r.match(/^"(?:[^"\\]|\\.)*"?/)||r.match(/^'(?:[^']|'')*'?/)?"string":r.match(/^-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?(?=[\s,\]}]|$)/)?"number":r.match(/^(?:true|false|null|~)(?=[\s,\]}]|$)/)?"atom":r.match(/^[:[\]{},|>]/)?"punctuation":(r.eatWhile(/[^\s#:,[\]{}]/),r.current()===""&&r.next(),"string"))}}),aj=Hn.HighlightStyle.define([{tag:Un.tags.propertyName,color:"var(--text-accent)"},{tag:Un.tags.string,color:"var(--text-normal)"},{tag:Un.tags.number,color:"var(--color-orange)"},{tag:Un.tags.atom,color:"var(--color-purple)"},{tag:Un.tags.comment,color:"var(--text-faint)",fontStyle:"italic"},{tag:Un.tags.meta,color:"var(--text-faint)"},{tag:Un.tags.punctuation,color:"var(--text-muted)"}]),H$=Jt.StateEffect.define(),cj=Jt.StateField.define({create:()=>Et.Decoration.none,update(r,e){let t=r.map(e.changes);for(let n of e.effects){if(!n.is(H$))continue;let i=new Jt.RangeSetBuilder,s=[...new Set(n.value.map(o=>o.line).filter(o=>o!==null&&o>=1&&o<=e.state.doc.lines))].sort((o,a)=>o-a);for(let o of s){let a=e.state.doc.line(o),c=n.value.find(l=>l.line===o)?.severity??"error";i.add(a.from,a.from,Et.Decoration.line({class:`mdbase-yaml-problem-line is-${c}`}))}t=i.finish()}return t},provide:r=>Et.EditorView.decorations.from(r)}),Ad=class{constructor(e){this.editable=new Jt.Compartment;this.applyingExternalChange=!1;this.view=new Et.EditorView({state:Jt.EditorState.create({doc:e.doc,extensions:[(0,Et.lineNumbers)(),(0,Vn.history)(),Hn.indentUnit.of(" "),Jt.EditorState.tabSize.of(2),Et.keymap.of([...Vn.defaultKeymap,...Vn.historyKeymap,Vn.indentWithTab]),oj,(0,Hn.syntaxHighlighting)(aj),cj,Et.EditorView.lineWrapping,this.editable.of(this.editability(e.readOnly)),Et.EditorView.contentAttributes.of({"aria-labelledby":e.labelledBy,"data-focus-key":"yaml-editor",spellcheck:"false"}),Et.EditorView.updateListener.of(t=>{t.docChanged&&!this.applyingExternalChange&&e.onChange(t.state.doc.toString())})]})}),this.dom=this.view.dom,this.dom.addClass("mdbase-yaml-editor")}get value(){return this.view.state.doc.toString()}setValue(e){if(e!==this.value){this.applyingExternalChange=!0;try{this.view.dispatch({changes:{from:0,to:this.view.state.doc.length,insert:e}})}finally{this.applyingExternalChange=!1}}}setReadOnly(e){this.view.dispatch({effects:this.editable.reconfigure(this.editability(e))})}setProblems(e){this.view.dispatch({effects:H$.of(e)})}revealLine(e){if(e<1||e>this.view.state.doc.lines)return;let t=this.view.state.doc.line(e).from;this.view.dispatch({selection:{anchor:t},scrollIntoView:!0}),this.view.focus()}destroy(){this.view.destroy()}editability(e){return[Jt.EditorState.readOnly.of(e),Et.EditorView.editable.of(!e)]}};function z$(r,e=2){let t=r.match(/line (\d+)/i)??r.match(/\((\d+):\d+\)/);return t?Number(t[1])+e-1:null}function oy(r,e){if(!e)return null;let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^\\s*(?:-\\s+)?["']?${t}["']?\\s*:`),s=r.split(` +`).findIndex(o=>n.test(o));return s===-1?null:s+1}var Pd=class{constructor(e){this.ctx=e;this.editorMode="design";this.query="";this.selectedPath=null;this.model=null;this.originalModel=null;this.yamlDraft="";this.dirty=!1;this.migrationPlan=null;this.allowLossy=!1;this.statsCache=null;this.impact=null;this.impactVersion=0;this.impactTimer=null;this.showAllMatches=!1;this.pendingFieldReveal=null;this.sessionDrafts=new Set;this.yamlEditor=null;this.yamlProblemTimer=null;this.draftSaveTimer=null;this.fieldQuery="";this.expandedFields=new Set;this.fieldIds=new WeakMap;this.nextFieldId=1;this.typeSelectionVersion=0}async onSchemaLoaded(e,t){if(this.selectedPath&&!this.typeEntries().some(n=>n.filePath===this.selectedPath)&&(this.selectedPath=null,this.model=null,this.originalModel=null),!this.selectedPath&&this.typeEntries().length&&!tt.Platform.isMobile&&(this.selectedPath=this.typeEntries()[0].filePath),this.selectedPath&&(!this.model||e)){if(this.dirty&&await this.flushTypeDraft(),!t())return;await this.selectType(this.selectedPath,!1)}}onRecordsLoaded(e){(e||!this.impact)&&this.scheduleImpact(0)}afterRender(e){if(!this.pendingFieldReveal)return;let t=e.querySelector(`[data-field-id="${this.pendingFieldReveal}"]`);t&&(t.scrollIntoView({block:"nearest"}),(!e.contains(e.ownerDocument.activeElement)||e.ownerDocument.activeElement===e.ownerDocument.body)&&t.querySelector("summary")?.focus({preventScroll:!0}),t.addClass("is-revealed")),this.pendingFieldReveal=null}getState(){return{selectedPath:this.selectedPath,editorMode:this.editorMode,query:this.query,fieldQuery:this.fieldQuery}}async setState(e){for(let t of["query","fieldQuery"])typeof e[t]=="string"&&(this[t]=e[t].slice(0,2e3));typeof e.selectedPath=="string"&&e.selectedPath!==this.selectedPath&&(await this.leaveCurrentType(),this.selectedPath=e.selectedPath,this.model=null,this.originalModel=null)}restoreEditorMode(e){e==="yaml"&&this.editorMode!=="yaml"&&this.switchEditorMode("yaml")}async dispose(){this.impactTimer!==null&&window.clearTimeout(this.impactTimer),this.yamlProblemTimer!==null&&window.clearTimeout(this.yamlProblemTimer),this.impactVersion++,await this.flushTypeDraft(),this.yamlEditor?.destroy(),this.yamlEditor=null}async openTypeField(e,t){this.ctx.destination="types",(e!==this.selectedPath||!this.model)&&await this.selectType(e),!(!this.model||this.selectedPath!==e)&&(t&&this.revealField(t),this.ctx.render())}revealField(e){if(!this.model)return;let t=e.split(".").filter(Boolean),n=t.shift()?.replace(/\[\]$/g,"")??"",i=this.model.fields.find(s=>s.name===n)?.definition;if(i){this.editorMode="design",this.fieldQuery="",this.expandedFields.add(this.fieldId(i));for(let s of t){let o=s.replace(/\[\]$/g,""),a=Se(i.items)?i.items:i,c=Se(a.fields)?a.fields[o]:void 0;if(!Se(c))break;a!==i&&this.expandedFields.add(this.fieldId(a)),i=c,this.expandedFields.add(this.fieldId(i))}this.pendingFieldReveal=this.fieldId(i)}}currentStats(){let e=this.ctx.host.getIssues(),t=this.ctx.schema?.types??null,n=this.statsCache;if(n&&n.records===this.ctx.records&&n.types===t&&n.issues===e)return n;let i=this.ctx.records&&this.ctx.schema?E$(this.ctx.records,this.ctx.schema.config,this.ctx.schema.types):new Map;return this.statsCache={records:this.ctx.records,types:t,issues:e,recordTypes:i,stats:k$(i,e)},this.statsCache}scheduleImpact(e=400){this.impactTimer!==null&&window.clearTimeout(this.impactTimer),this.impactTimer=window.setTimeout(()=>{this.impactTimer=null,this.computeImpact().then(t=>{t!==void 0&&(this.impact=t,this.updateImpactRegions())})},e)}async computeImpact(){let e=++this.impactVersion,t=this.editorMode==="yaml"?this.modelFromYamlDraft():null;if(t&&"error"in t)return{error:t.error};let n=t?.model??this.model;if(!n||!this.ctx.schema||!this.ctx.records||n.specProfile!=="v0.3"||n.readOnlyReason)return null;let i=this.selectedPath?[...this.ctx.schema.types.values()].find(o=>o.filePath===this.selectedPath)?.name??null:null,s=await A$({records:this.ctx.records,config:this.ctx.schema.config,types:this.ctx.schema.types,draft:n,savedName:i,filePath:this.selectedPath,isCurrent:()=>e===this.impactVersion});return e===this.impactVersion&&s!==null?s:void 0}updateImpactRegions(){let e=this.ctx.containerEl.querySelector(".mdbase-match-preview");e&&(e.empty(),this.fillMatchPreview(e));let t=this.ctx.containerEl.querySelector("[data-disclosure='type-matching'] > summary");t&&(t.textContent=this.matchingLabel());let n=this.ctx.containerEl.querySelector(".mdbase-impact");n&&(n.empty(),this.fillImpact(n));let i=this.ctx.containerEl.querySelector(".mdbase-type-editor-pane"),s=i?.querySelector(".mdbase-draft-bar");i&&s&&this.model&&(s.remove(),this.renderDraftBar(i,this.model))}createNewType(){this.ctx.destination="types",this.createType()}async editType(e){this.ctx.destination="types",await this.selectType(e)}typeEntries(){return this.ctx.schema?[...this.ctx.schema.types.values()].sort((e,t)=>e.name.localeCompare(t.name)):[]}renderSetup(e){let t=e.createDiv({cls:"mdbase-empty-state mdbase-setup"});if(this.ctx.host.getMirrorProfile()){t.createEl("h2",{text:"Waiting for the first sync"}),t.createEl("p",{text:"Types appear here once the hosted collection has synced."});let s=t.createEl("button",{text:"Open sync",cls:"mod-cta"});s.onclick=()=>this.ctx.showDestination("sync");return}t.createEl("h2",{text:"Set up mdbase"});let n=t.createDiv({cls:"mdbase-setup-choices"}),i=(s,o,a,c)=>{let l=n.createDiv({cls:"mdbase-setup-choice"}),u=l.createDiv();u.createEl("strong",{text:s}),u.createDiv({cls:"mdbase-muted",text:o});let d=l.createEl("button",{text:s,cls:a?"mod-cta":""});d.disabled=this.ctx.busy,d.onclick=c};i("Start a collection","This vault holds the collection. You can upload it to Connect later.",!0,()=>{this.ctx.perform(async()=>{await this.ctx.host.initializeCollection(),await this.ctx.refresh(!0)})}),i("Copy from Connect","Connect holds the collection. This vault syncs a copy.",!1,()=>{this.ctx.showDestination("sync")})}render(e){if(!this.ctx.schema){this.renderSetup(e);return}if(this.ctx.schema.config.spec_version.startsWith("0.2.")&&this.renderLegacyBanner(e),!this.typeEntries().length&&!this.model){let n=e.createDiv({cls:"mdbase-empty-state"});n.createEl("h2",{text:"Add your first type"}),n.createEl("p",{text:"Install ready-made types and application contracts from mdbase-contracts, or design your own type."});let i=n.createDiv({cls:"mdbase-actions"}),s=i.createEl("button",{text:"Browse ready-made types",cls:"mod-cta"});s.disabled=this.ctx.busy||this.ctx.schema.config.spec_version.startsWith("0.2.")||this.ctx.host.getMirrorProfile()!==null,s.onclick=()=>void this.ctx.perform(()=>this.ctx.host.openContractCatalog());let o=i.createEl("button",{text:"Design a custom type"});o.disabled=this.ctx.schema.config.spec_version.startsWith("0.2.")||this.ctx.host.getMirrorProfile()?.mode==="read_only",o.onclick=()=>void this.createType();return}let t=e.createDiv({cls:"mdbase-types-layout"});this.model&&t.addClass("has-selection"),this.renderTypeList(t),this.renderTypeEditor(t)}renderLegacyBanner(e){let t=e.createDiv({cls:"mdbase-legacy-banner"}),n=t.createDiv();if(n.createEl("strong",{text:"Read-only \xB7 v0.2 collection"}),n.createEl("p",{text:"Migrate to edit types."}),!this.migrationPlan){let i=t.createEl("button",{text:"Review migration"});i.disabled=this.ctx.busy||this.ctx.host.getMirrorProfile()!==null,i.onclick=()=>void this.ctx.perform(async()=>{this.migrationPlan=await this.ctx.host.analyzeMigration(),this.ctx.render()})}this.ctx.host.getMirrorProfile()&&t.createDiv({cls:"mdbase-form-description",text:"Hosted resources must be migrated at the collection authority."}),this.migrationPlan&&this.renderMigrationReview(e,this.migrationPlan)}renderMigrationReview(e,t){let n=e.createDiv({cls:"mdbase-migration-review"}),i=n.createDiv({cls:"mdbase-section-header"});i.createEl("h3",{text:"Migration review"}),i.createSpan({cls:"mdbase-spec-badge",text:`${t.sourceVersion} \u2192 ${t.targetVersion}`});let s=n.createDiv({cls:"mdbase-status-list"});Gt(s,"Files replaced",String(t.operations.length)),Gt(s,"Type definitions",String(t.typeSummaries.length)),Gt(s,"Record reads verified",String(t.recordsVerified)),t.recordsSkipped&&Gt(s,"Records skipped",String(t.recordsSkipped)),Gt(s,"Record files rewritten","0"),Gt(s,"Recovery backup",t.backupLocation);let o=n.createDiv({cls:"mdbase-review-list"});t.diagnostics.length||o.createDiv({cls:"mdbase-review-ok",text:"No migration diagnostics."});for(let u of t.diagnostics.slice(0,250)){let d=o.createDiv({cls:"mdbase-review-item"});d.setAttr("data-severity",u.severity),d.createDiv({cls:"mdbase-review-code",text:`${u.severity} \xB7 ${u.path}`}),d.createDiv({text:u.message})}if(t.diagnostics.length>250&&o.createDiv({cls:"mdbase-form-description",text:`Showing 250 of ${t.diagnostics.length} diagnostics.`}),!t.applicable){let u=n.createEl("label",{cls:"mdbase-consent"}),d=u.createEl("input",{type:"checkbox"});d.checked=this.allowLossy,d.onchange=()=>{this.allowLossy=d.checked,this.ctx.render()},u.createSpan({text:"I reviewed the lossy diagnostics and want to apply this migration."})}let a=n.createDiv({cls:"mdbase-actions"}),c=a.createEl("button",{text:"Apply migration"});c.addClass("mod-warning"),c.disabled=this.ctx.busy||!t.applicable&&!this.allowLossy,c.onclick=()=>void this.ctx.perform(async()=>{await this.ctx.host.applyMigration(t,this.allowLossy),this.migrationPlan=null,this.allowLossy=!1,this.model=null,this.originalModel=null,await this.ctx.refresh(!0)});let l=a.createEl("button",{text:"Close review"});l.onclick=()=>{this.migrationPlan=null,this.ctx.render()}}renderTypeList(e){let t=e.createDiv({cls:"mdbase-type-list-pane"}),n=t.createDiv({cls:"mdbase-pane-header"});n.createEl("h2",{text:"Types"});let i=this.ctx.iconButton(n,"download","Browse ready-made types");i.disabled=this.ctx.busy||this.ctx.schema?.config.spec_version.startsWith("0.2.")===!0||this.ctx.host.getMirrorProfile()!==null,i.onclick=()=>void this.ctx.perform(()=>this.ctx.host.openContractCatalog());let s=this.ctx.schema?.config.spec_version.startsWith("0.2.")??!0?"Migrate to v0.3 to create types":this.ctx.host.getMirrorProfile()?.mode==="read_only"?"Read-only mirror":"",o=this.ctx.iconButton(n,"plus",s?`Create type \xB7 ${s}`:"Create type");o.disabled=!!s,o.onclick=()=>void this.createType();let a=t.createEl("input",{type:"search"});a.addClass("mdbase-type-search"),a.placeholder="Search types",a.setAttr("aria-label","Search types"),a.setAttr("data-focus-key","type-search"),a.value=this.query,a.oninput=()=>{this.query=a.value,this.ctx.render();let f=this.ctx.containerEl.querySelector(".mdbase-type-search");f?.focus(),f?.setSelectionRange(f.value.length,f.value.length)};let c=t.createDiv({cls:"mdbase-type-list"});c.setAttr("data-scroll-key","type-list");let l=this.query.trim().toLowerCase(),u=this.typeEntries().filter(f=>`${f.name} ${f.description??""} ${f.filePath}`.toLowerCase().includes(l));if(!u.length){c.createDiv({cls:"mdbase-empty-list",text:l?"No matching types.":"No type definitions."});return}let{stats:d}=this.currentStats();for(let f of u){let p=c.createEl("button",{cls:"mdbase-type-row"});f.filePath===this.selectedPath&&p.addClass("is-active"),p.setAttr("aria-current",f.filePath===this.selectedPath?"true":"false");let h=p.createDiv({cls:"mdbase-type-name-line"});if(h.createSpan({cls:"mdbase-type-name",text:f.name}),f.filePath===this.selectedPath?this.dirty:this.ctx.host.loadTypeDraft(f.filePath)!==null){let g=h.createSpan({cls:"mdbase-unsaved-dot"});g.setAttr("aria-label","Unsaved changes"),g.setAttr("title","Unsaved changes")}let y=d.get(f.name);if(this.ctx.records){let g=p.createDiv({cls:"mdbase-type-meta"}),b=y?.notes??0;g.createSpan({text:`${b.toLocaleString()} ${b===1?"note":"notes"}`}),y?.issues&&g.createSpan({cls:"mdbase-type-issues",text:`${y.issues.toLocaleString()} ${y.issues===1?"issue":"issues"}`})}p.onclick=()=>void this.selectType(f.filePath)}}renderTypeEditor(e){let t=e.createDiv({cls:"mdbase-type-editor-pane"});if(t.setAttr("data-scroll-key","type-editor"),!this.model){t.createDiv({cls:"mdbase-empty-state"}).createEl("p",{text:"Select a type"});return}let n=this.ctx.host.getMirrorProfile()?.mode==="read_only",i=this.model.specProfile==="v0.2"||n||!!this.model.readOnlyReason,s=this.model.readOnlyReason??(n?"Read-only mirror. Reconnect with write access to edit.":"Migrate this v0.2 collection to edit types."),o=t.createDiv({cls:"mdbase-editor-header"}),a=this.ctx.iconButton(o,"arrow-left","Back to type list");a.addClass("mdbase-mobile-back"),a.onclick=()=>void this.leaveCurrentType().then(()=>{this.selectedPath=null,this.model=null,this.originalModel=null,this.ctx.render()});let c=o.createDiv({cls:"mdbase-editor-heading"});c.createDiv({cls:"mdbase-editor-title-line"}).createEl("h2",{text:this.model.name||"Untitled type"}),c.createDiv({cls:"mdbase-editor-path",text:this.selectedPath??"New type"});let u=o.createDiv({cls:"mdbase-editor-actions"});if(this.selectedPath){let p=this.selectedPath,h=this.ctx.iconButton(u,"file-code","Open source");h.onclick=()=>void this.ctx.host.openFileByPath(p)}if(this.selectedPath){let p=this.model.name,h=u.createEl("button",{text:"New note"});h.disabled=i||this.ctx.busy,h.onclick=()=>void this.ctx.host.createNoteFromType(p),this.renderStaleDrafts(t)}i&&t.createDiv({cls:"mdbase-readonly-note",text:s});let d=t.createDiv({cls:"mdbase-mode-switch"});d.setAttr("role","tablist");for(let[p,h]of[["design","Design"],["yaml","YAML"]]){let m=d.createEl("button",{text:h});m.id=`mdbase-mode-${p}`,m.setAttr("role","tab"),m.setAttr("aria-selected",String(this.editorMode===p)),this.editorMode===p&&m.addClass("is-active"),m.onclick=()=>this.switchEditorMode(p)}let f=t.createDiv({cls:"mdbase-editor-document"});f.setAttr("data-scroll-key","type-document"),this.editorMode==="design"?this.renderDesignEditor(f,this.model,i):this.renderYamlEditor(f,i),this.dirty&&!i&&this.renderDraftBar(t,this.model)}renderStaleDrafts(e){if(!this.selectedPath||!this.originalModel)return;let t=this.selectedPath,n=this.ctx.host.loadTypeDraft(t),i=[...this.ctx.host.getArchivedTypeDrafts(t),...n&&n.sourceRevision!==(this.originalModel.sourceRevision??null)?[n]:[]];for(let s of i){let o=e.createDiv({cls:"mdbase-recovery-card"});o.createDiv({text:`An older draft from ${new Date(s.updatedAt).toLocaleString()} is available. The source changed; it will not be applied automatically.`});let a=o.createEl("button",{text:"Compare draft"});a.onclick=()=>{let u=new tt.Modal(this.ctx.app);u.titleEl.setText("Current source and recovered draft");let d=s.yamlDraft;if(d===void 0)try{d=gt(Aa(s.model),s.model.body)}catch{d=JSON.stringify(s.model,null,2)}u.contentEl.createEl("h3",{text:"Current source"}),u.contentEl.createEl("pre",{text:this.originalModel?gt(Aa(this.originalModel),this.originalModel.body):this.yamlDraft}),u.contentEl.createEl("h3",{text:"Recovered draft (read-only)"}),u.contentEl.createEl("pre",{text:d}),u.contentEl.createEl("p",{text:"Copy the parts you want into the current definition, then review before saving."}),u.open()};let c=o.createEl("button",{text:"Export draft"});c.onclick=()=>void this.ctx.perform(async()=>{let u="mdbase-draft-recovery";this.ctx.app.vault.getAbstractFileByPath(u)||await this.ctx.app.vault.createFolder(u);let d=await this.ctx.app.vault.create(`${u}/draft-${crypto.randomUUID()}.txt`,s.yamlDraft??JSON.stringify(s.model,null,2));this.ctx.message=`Exported recovery draft to ${d.path}. The original draft is still retained.`});let l=o.createEl("button",{text:"Discard old draft"});l.onclick=()=>{let u=new tt.Modal(this.ctx.app);u.titleEl.setText("Discard this recovered draft?"),u.contentEl.createEl("p",{text:"This removes the saved recovery copy, not the current source or your current edits. Export it first if you might need it."}),u.contentEl.createEl("button",{text:"Cancel"}).onclick=()=>u.close(),u.contentEl.createEl("button",{text:"Discard old draft",cls:"mod-warning"}).onclick=()=>{u.close(),this.ctx.perform(async()=>{s===n?await this.ctx.host.clearTypeDraft(t):await this.ctx.host.discardArchivedTypeDraft(s)})},u.open()}}}renderDraftBar(e,t){let n=xa(this.originalModel,t),s=Sa(t,{knownTypes:this.typeEntries().map(m=>m.name),contracts:this.ctx.schema?.contracts.values()}).filter(m=>m.severity==="error").length,o=n.filter(m=>m.risk==="high").length,a=this.newlyFailing(),c=this.editorMode==="yaml"?this.yamlProblems().filter(m=>m.severity==="error").length:0,l=e.createDiv({cls:"mdbase-draft-bar"}),u=l.createDiv({cls:"mdbase-draft-summary"}),d=this.editorMode==="yaml"?c:s;u.setAttr("data-tone",d?"error":a||o?"warning":"normal"),u.createSpan({text:d?`${d} ${d===1?"error":"errors"}`:a?`${a} ${a===1?"note":"notes"} would fail`:o?`${o} high-impact ${o===1?"change":"changes"}`:"Unsaved changes"});let f=l.createDiv({cls:"mdbase-actions"});if(this.editorMode==="design"){let m=f.createEl("button",{text:"Review"});m.onclick=()=>{let g=this.ctx.containerEl.querySelector("#mdbase-section-review")?.closest("details");g&&(g.open=!0),this.ctx.render(),this.ctx.containerEl.querySelector("#mdbase-section-review")?.scrollIntoView({block:"nearest"})}}let p=f.createEl("button",{text:"Discard"});p.onclick=()=>void this.discardCurrentType();let h=f.createEl("button",{text:"Save"});h.addClass("mod-cta"),h.disabled=(this.editorMode==="design"?s>0:c>0)||this.ctx.busy,h.onclick=()=>void this.saveCurrentType()}newlyFailing(){return!this.dirty||!this.impact||"error"in this.impact?0:this.impact.impact.failing.filter(e=>e.isNew).length}matchingLabel(){let e=this.impact&&!("error"in this.impact)?this.impact.impact.matched.length:this.savedTypeName()?this.currentStats().stats.get(this.savedTypeName()??"")?.notes:void 0;return e===void 0||!this.ctx.records?"Matching":`Matching \xB7 ${e.toLocaleString()} ${e===1?"note":"notes"}`}savedTypeName(){return!this.selectedPath||!this.ctx.schema?null:[...this.ctx.schema.types.values()].find(e=>e.filePath===this.selectedPath)?.name??null}fillMatchPreview(e){let t=this.impact,n,i=[],s=[];if(t&&!("error"in t))({matched:n,added:i,removed:s}=t.impact);else{let d=this.savedTypeName();if(!this.ctx.records||!d||t&&"error"in t&&this.dirty){e.createDiv({cls:"mdbase-muted",text:this.ctx.records?t&&"error"in t?"Fix errors to preview matching notes.":"Save the type to preview matching notes.":"Counting notes\u2026"});return}n=[...this.currentStats().recordTypes].filter(([,f])=>f.includes(d)).map(([f])=>f)}let o=e.createDiv({cls:"mdbase-match-summary"});o.createSpan({text:`${n.length.toLocaleString()} ${n.length===1?"note matches":"notes match"}`}),i.length&&o.createSpan({cls:"mdbase-match-added",text:`${i.length} added`}),s.length&&o.createSpan({cls:"mdbase-match-removed",text:`${s.length} no longer match`});let a=new Set(i),c=[...i.map(d=>({path:d,change:"added"})),...s.map(d=>({path:d,change:"removed"})),...n.filter(d=>!a.has(d)).map(d=>({path:d,change:null}))];if(!c.length)return;let l=this.showAllMatches?200:5,u=e.createDiv({cls:"mdbase-match-list"});for(let d of c.slice(0,l)){let f=u.createEl("button",{cls:"mdbase-match-row"});d.change&&(f.setAttr("data-change",d.change),f.createSpan({cls:"mdbase-match-marker",text:d.change==="added"?"+":"\u2212",attr:{"aria-label":d.change==="added"?"Added":"No longer matches"}})),f.createSpan({text:d.path}),f.setAttr("title",`Open ${d.path}`),f.onclick=()=>void this.ctx.host.openFileByPath(d.path)}if(c.length>5){let d=e.createEl("button",{cls:"mdbase-link-button",text:this.showAllMatches?"Show fewer":c.length>200?`Show 200 of ${c.length.toLocaleString()}`:`Show all ${c.length.toLocaleString()}`});d.onclick=()=>{this.showAllMatches=!this.showAllMatches,e.empty(),this.fillMatchPreview(e)}}}fillImpact(e){let t=this.impact;if(!t){e.createDiv({cls:"mdbase-muted",text:this.ctx.records?"Checking notes\u2026":"Counting notes\u2026"});return}if("error"in t){e.createDiv({cls:"mdbase-muted",text:"Fix errors to check existing notes."});return}let{impact:n}=t,i=n.failing.filter(l=>l.isNew),s=n.failing.length-i.length,o=e.createDiv({cls:"mdbase-impact-heading"});o.setAttr("data-tone",i.length?"warning":"normal"),o.createEl("strong",{text:i.length?`${i.length} ${i.length===1?"note":"notes"} would fail`:"No notes newly fail"});let a=[`${n.matched.length.toLocaleString()} ${n.matched.length===1?"note":"notes"} checked`];if(n.fixed&&a.push(`${n.fixed} fixed`),s&&a.push(`${s} already failing`),o.createSpan({cls:"mdbase-muted",text:a.join(" \xB7 ")}),!i.length)return;let c=e.createDiv({cls:"mdbase-impact-list"});for(let l of i.slice(0,10)){let u=c.createDiv({cls:"mdbase-impact-row"}),d=u.createEl("button",{cls:"mdbase-link-button",text:l.path});d.onclick=()=>void this.ctx.host.openFileByPath(l.path,l.issues[0]?.field),u.createSpan({cls:"mdbase-muted",text:`${l.issues[0]?.message??""}${l.issues.length>1?` \xB7 +${l.issues.length-1} more`:""}`})}i.length>10&&c.createDiv({cls:"mdbase-muted",text:`${i.length-10} more notes`})}renderDesignEditor(e,t,n){let i=Sa(t,{knownTypes:this.typeEntries().map(M=>M.name),contracts:this.ctx.schema?.contracts.values()}),s=e.createEl("section",{cls:"mdbase-editor-section"});s.id="mdbase-section-identity";let o=Ot(s,"Name",t.name,M=>{t.name=M,this.markDirty()});o.disabled=n;let a=Ot(s,"Description",t.description,M=>{t.description=M,this.markDirty()},{multiline:!0});a.disabled=n;let c=this.ctx.disclosure(e,"type-options","Options"),l=c.createDiv({cls:"mdbase-form-row"}),u=l.createEl("label",{text:"Display field"}),d=l.createEl("select");u.htmlFor=d.id="mdbase-display-field",d.createEl("option",{value:"",text:"Use the file name"});for(let M of t.fields)d.createEl("option",{value:M.name,text:M.name||"Unnamed field"});t.displayNameKey&&!t.fields.some(M=>M.name===t.displayNameKey)&&d.createEl("option",{value:t.displayNameKey,text:`${t.displayNameKey} \xB7 missing`}),d.value=t.displayNameKey,d.onchange=()=>{t.displayNameKey=d.value,this.markDirty()},d.disabled=n;let f=c.createEl("label",{cls:"mdbase-checkbox-row"}),p=f.createEl("input",{type:"checkbox"});p.checked=t.strictMode===!0,p.disabled=n,p.onchange=()=>{t.strictMode=p.checked,this.markDirty()},f.createSpan({text:"Reject undeclared fields"});let h=this.ctx.disclosure(e,"type-matching",this.matchingLabel());h.id="mdbase-section-membership",this.fillMatchPreview(h.createDiv({cls:"mdbase-match-preview"}));let m=Ot(h,"Path glob",t.matchPathGlob,M=>{t.matchPathGlob=M,this.markDirty()},{placeholder:"Projects/**/*.md"});m.disabled=n;let y=Ot(h,"Fields present",t.matchFieldsPresent,M=>{t.matchFieldsPresent=M,this.markDirty()},{description:"Comma-separated frontmatter keys."});y.disabled=n;let g=Ot(h,"Where",t.matchWhere,M=>{t.matchWhere=M,this.markDirty()},{multiline:!0,description:"YAML predicate, including contains and nested equality conditions.",placeholder:`tags: + contains: task`});g.disabled=n;let b=e.createEl("section",{cls:"mdbase-editor-section"});b.id="mdbase-section-fields";let v=b.createDiv({cls:"mdbase-section-header"});v.createEl("h3",{text:"Fields"});let S=v.createDiv({cls:"mdbase-section-actions"});if(this.expandedFields.size){let M=this.ctx.iconButton(S,"fold-vertical","Collapse all fields");M.onclick=()=>{this.expandedFields.clear(),this.ctx.render()}}let _=this.ctx.iconButton(S,"plus","Add field");if(_.disabled=n,_.onclick=()=>{let M={type:"string"};t.fields.push({name:"",definition:M}),this.expandedFields.add(this.fieldId(M)),this.markDirty(!0)},t.fields.length>6||this.fieldQuery){let P=b.createDiv({cls:"mdbase-field-toolbar"}).createDiv({cls:"mdbase-field-toolbar-actions"}).createEl("input",{type:"search"});P.placeholder="Filter fields",P.setAttr("aria-label","Filter fields"),P.setAttr("data-focus-key","field-search"),P.value=this.fieldQuery,P.oninput=()=>{this.fieldQuery=P.value,this.ctx.render()}}let E=b.createDiv({cls:"mdbase-fields"}),A=this.fieldQuery.trim().toLowerCase(),x=t.fields.filter(M=>!A||this.fieldMatches(M.name,M.definition,A));for(let M of x){let V=t.fields.indexOf(M);this.renderFieldRow(E,M,V,n)}x.length||E.createDiv({cls:"mdbase-empty-list",text:t.fields.length?"No fields match this filter.":"No fields declared."}),h.parentElement&&e.appendChild(h.parentElement),c.parentElement&&e.appendChild(c.parentElement);let $=Ot(c,"Path pattern",t.pathPattern,M=>{t.pathPattern=M,this.markDirty()},{placeholder:"Notes/{title}.md"});if($.disabled=n,this.renderContractEditor(e,t,n),!this.dirty&&!i.length)return;let q=this.ctx.disclosure(e,"type-review","Changes",i.some(M=>M.severity==="error"));if(q.id="mdbase-section-review",this.dirty&&this.fillImpact(q.createDiv({cls:"mdbase-impact"})),i.length){let M=q.createDiv({cls:"mdbase-diagnostic-summary"}),V=i.filter(C=>C.severity==="error").length,P=i.length-V;M.createEl("strong",{text:`${V} ${V===1?"error":"errors"} \xB7 ${P} ${P===1?"warning":"warnings"}`});for(let C of i.slice(0,12)){let Ve=M.createDiv({cls:"mdbase-diagnostic-item"});Ve.setAttr("data-severity",C.severity),Ve.createEl("code",{text:C.path}),Ve.createSpan({text:C.message})}}if(this.dirty){let M=q.createEl("ul");for(let V of xa(this.originalModel,t))M.createEl("li",{text:V.summary}).setAttr("data-risk",V.risk)}}renderContractEditor(e,t,n){let i=this.ctx.disclosure(e,"type-applications","Applications");i.addClass("mdbase-contracts-section"),i.id="mdbase-section-applications";let s=[...this.ctx.schema?.contracts.values()??[]],o=new Set(t.implementations.map(c=>`${c.contract}@${c.version}`)),a=s.filter(c=>!o.has(Ms(c)));s.length||i.createDiv({cls:"mdbase-contract-empty",text:"No application contracts installed."});for(let c of t.implementations){let l=s.find(u=>u.id===c.contract&&u.version===c.version);this.renderContractImplementation(i,t,c,l,n)}if(a.length){let c=i.createDiv({cls:"mdbase-contract-add"}),l=c.createEl("label",{text:"Installed contract"}),u=c.createEl("select");l.htmlFor=u.id=`mdbase-contract-${Math.random().toString(36).slice(2)}`;for(let f of a)u.createEl("option",{value:Ms(f),text:`${f.id} \xB7 ${f.version}`});let d=c.createEl("button",{text:"Add contract"});d.disabled=n,d.onclick=()=>{let f=a.find(p=>Ms(p)===u.value);if(f)try{m$(t,f),this.markDirty(!0)}catch(p){new tt.Notice(p instanceof Error?p.message:String(p))}}}}renderContractImplementation(e,t,n,i,s){let o=e.createEl("article",{cls:"mdbase-contract-implementation"}),a=o.createDiv({cls:"mdbase-contract-header"}),c=a.createDiv();c.createEl("strong",{text:n.contract}),c.createSpan({cls:"mdbase-contract-version",text:n.version});let l=a.createEl("button",{text:"Remove"});if(l.disabled=s,l.onclick=()=>{y$(t,n.contract,n.version),this.markDirty(!0)},!i){o.createDiv({cls:"mdbase-contract-unavailable",text:"This exact contract is not installed in the collection. Restore it or remove this implementation before saving."});return}let u=ba(i),d=va(t),f=u.filter(b=>Rs(n,b)),p=u.filter(b=>b.required),h=p.filter(b=>Rs(n,b)).length,m=o.createEl("details");m.open=h$.reference===v),_=wa(b,S),E=g.createDiv({cls:`mdbase-contract-mapping-row ${_.level}`}),A=E.createDiv({cls:"mdbase-contract-field-definition"});A.createEl("code",{text:b.reference}),A.createSpan({cls:b.required?"mdbase-contract-required":"mdbase-contract-optional",text:b.required?"Required":"Optional"}),A.createEl("small",{text:b.description||b$(b.schema)});let x=E.createEl("select");x.setAttr("aria-label",`${n.contract} ${b.reference} source field`),x.setAttr("aria-invalid",_.level==="error"?"true":"false"),x.disabled=s,x.createEl("option",{value:"",text:b.required?"Choose a source field":"Not exposed"});for(let $ of d){let q=wa(b,$),M=x.createEl("option",{value:$.reference,text:`${$.reference} \xB7 ${$.type}${q.level==="warning"?" \xB7 review":""}`});M.disabled=q.level==="error"}x.value=v,x.onchange=()=>{g$(n,b.reference,x.value||void 0),this.markDirty(!0)};let R=E.createDiv({cls:"mdbase-contract-mapping-status"});R.createEl("strong",{text:_.label}),R.createEl("small",{text:_.message})}if(i.binding_schema){let b=o.createEl("details",{cls:"mdbase-contract-settings"});b.open=!!n.binding;let v=b.createEl("summary");v.createSpan({text:"Contract settings"}),v.createSpan({cls:"mdbase-contract-summary",text:n.binding?"Configured":"Optional"});let S=b.createDiv({cls:"mdbase-contract-settings-body"});if(S.createEl("p",{cls:"mdbase-form-description",text:"Control how compatible applications interpret this type. Values follow the contract's schema."}),n.binding)this.renderContractSchemaValue(S,i.binding_schema,n.binding,_=>{Se(_)&&(Wm(n,_),this.markDirty())},"Settings",s);else{let _=S.createEl("button",{text:"Configure settings"});_.disabled=s,_.onclick=()=>{let E=_a(i.binding_schema);Se(E)&&(Wm(n,E),this.markDirty(!0))}}}}renderContractSchemaValue(e,t,n,i,s,o){if(qn(t)==="object"){let c=Se(n)?n:{},l=e.createEl("fieldset",{cls:"mdbase-contract-schema-object"});l.createEl("legend",{text:s});let u=Se(t.properties)?t.properties:{},d=new Set(Array.isArray(t.required)?t.required.map(String):[]),f=[...new Set([...d,...Object.keys(c).filter(h=>h in u)])];for(let h of f){let m=u[h];if(!Se(m))continue;let y=l.createDiv({cls:"mdbase-contract-schema-field"}),g=typeof m.description=="string"?m.description:void 0;y.createEl("label",{text:`${h}${d.has(h)?" \xB7 required":""}`}),g&&y.createEl("small",{text:g}),this.renderContractSchemaControl(y,m,c[h],b=>{i({...c,[h]:b})},h,o)}f.length||l.createDiv({cls:"mdbase-empty-list",text:"No settings declared."});let p=Object.keys(u).filter(h=>!f.includes(h));if(p.length){let h=l.createDiv({cls:"mdbase-contract-schema-add"}),m=h.createEl("select");for(let g of p)m.createEl("option",{value:g,text:g});let y=h.createEl("button",{text:"Add optional setting"});y.disabled=o,y.onclick=()=>{let g=m.value,b=u[g];Se(b)&&i({...c,[g]:_a(b)})}}return}this.renderContractSchemaControl(e,t,n,i,s,o)}renderContractSchemaControl(e,t,n,i,s,o){let a=qn(t);if(Array.isArray(t.enum)){let l=e.createEl("select");l.setAttr("aria-label",s);for(let u of t.enum)l.createEl("option",{value:JSON.stringify(u),text:String(u)});l.value=JSON.stringify(n),l.disabled=o,l.onchange=()=>i(JSON.parse(l.value));return}if(a==="array"){let l=Se(t.items)?t.items:{type:"string"},u=Array.isArray(n)?n:[],d=e.createDiv({cls:"mdbase-contract-schema-array"});for(let[p,h]of u.entries()){let m=d.createDiv({cls:"mdbase-contract-schema-array-item"});m.createSpan({text:`${p+1}.`}),this.renderContractSchemaControl(m,l,h,g=>{i(u.map((b,v)=>v===p?g:b))},`${s} item ${p+1}`,o);let y=m.createEl("button",{text:"Remove"});y.disabled=o||u.length<=(typeof t.minItems=="number"?t.minItems:0),y.onclick=()=>i(u.filter((g,b)=>b!==p))}let f=e.createEl("button",{text:`Add ${s.toLowerCase()} item`});f.disabled=o||typeof t.maxItems=="number"&&u.length>=t.maxItems,f.onclick=()=>i([...u,_a(l)]);return}if(a==="object"){this.renderContractSchemaValue(e,t,n,i,s,o);return}if(a==="boolean"){let l=e.createEl("input",{type:"checkbox"});l.checked=n===!0,l.disabled=o,l.setAttr("aria-label",s),l.onchange=()=>i(l.checked);return}let c=e.createEl("input",{type:a==="number"||a==="integer"?"number":"text"});c.setAttr("aria-label",s),c.value=n==null?"":typeof n=="string"?n:typeof n=="number"||typeof n=="boolean"?String(n):"",c.disabled=o,c.oninput=()=>i(a==="number"||a==="integer"?Number(c.value):c.value)}renderFieldRow(e,t,n,i){let s=this.model?.fields??[];this.renderFieldDefinition(e,t.definition,{name:t.name,nameLabel:`Field ${n+1} name`,onNameInput:o=>{t.name=o,this.markDirty()},required:t.definition.required===!0,onRequiredChange:o=>{t.definition.required=o,this.markDirty()},onRemove:()=>{this.model?.fields.splice(n,1),this.markDirty(!0)},onMove:o=>{let a=n+o;a<0||a>=s.length||([s[n],s[a]]=[s[a],s[n]],this.pendingFieldReveal=this.fieldId(t.definition),this.markDirty(!0))},canMoveUp:n>0,canMoveDown:n{i.open?this.expandedFields.add(s):this.expandedFields.delete(s)};let a=n.name||n.staticLabel||"Unnamed field",c=i.createEl("summary",{cls:"mdbase-field-summary"});c.setAttr("data-focus-key",`field-${s}-summary`);let l=c.createSpan({cls:"mdbase-field-chevron"});l.setAttr("aria-hidden","true"),(0,tt.setIcon)(l,"chevron-right"),c.createSpan({cls:"mdbase-field-summary-name",text:a}),c.createSpan({cls:"mdbase-field-summary-type",text:ey(Ea(t))});let u=c.createSpan({cls:"mdbase-field-summary-rules"}),d=()=>{u.textContent=B$(t).join(" \xB7 ")};d(),n.required&&c.createSpan({cls:"mdbase-field-summary-rule",text:"Required"}),n.onMove&&!n.readOnly&&c.addEventListener("keydown",y=>{!y.altKey||y.key!=="ArrowUp"&&y.key!=="ArrowDown"||(y.preventDefault(),y.key==="ArrowUp"&&n.canMoveUp&&n.onMove?.(-1),y.key==="ArrowDown"&&n.canMoveDown&&n.onMove?.(1))});let f=i.createDiv({cls:"mdbase-field-row"});if(n.staticLabel)f.createDiv({cls:"mdbase-field-role",text:n.staticLabel});else{let y=f.createEl("input",{type:"text",cls:"mdbase-field-name-control"});y.setAttr("data-focus-key",`field-${s}-name`),y.setAttr("aria-label",n.nameLabel),y.placeholder="Field name",y.value=n.name??"",y.disabled=n.readOnly,n.onNameInput&&(y.oninput=()=>n.onNameInput?.(y.value)),n.onNameCommit&&(y.onchange=()=>n.onNameCommit?.(y.value,y))}let p=f.createEl("select",{cls:"mdbase-field-type-control"});p.setAttr("data-focus-key",`field-${s}-type`),p.setAttr("aria-label",`${n.name||n.staticLabel||"Field"} type`);for(let y of C$)p.createEl("option",{value:y,text:ey(y)});p.value=Ea(t),p.disabled=n.readOnly,p.onchange=()=>{t.type=p.value,p.value==="list"&&!Se(t.items)&&(t.items={type:"string"}),p.value==="object"&&!Se(t.fields)&&(t.fields={}),p.value==="enum"&&!Array.isArray(t.values)&&(t.values=[]),p.value!=="integer"&&p.value!=="number"&&(delete t.min,delete t.max),p.value!=="string"&&delete t.pattern,["string","list"].includes(p.value)||(delete t.min_length,delete t.max_length),delete t.default,this.markDirty(!0)};let h=f.createEl("input",{type:"text",cls:"mdbase-field-description-control"});if(h.setAttr("data-focus-key",`field-${s}-description`),h.setAttr("aria-label",`${n.name||n.staticLabel||"Field"} description`),h.placeholder="Description",h.value=typeof t.description=="string"?t.description:"",h.disabled=n.readOnly,h.oninput=()=>{h.value?t.description=h.value:delete t.description,this.markDirty()},n.onRequiredChange){let y=f.createEl("label",{cls:"mdbase-field-required"}),g=y.createEl("input",{type:"checkbox"});g.setAttr("data-focus-key",`field-${s}-required`),g.checked=n.required===!0,g.disabled=n.readOnly,g.onchange=()=>n.onRequiredChange?.(g.checked),y.createSpan({text:"Required"})}if(n.onRemove||n.onMove){let y=this.ctx.iconButton(f,"more-horizontal",`${a} actions`);y.addClass("mdbase-field-menu"),y.setAttr("data-focus-key",`field-${s}-menu`),y.disabled=n.readOnly,y.onclick=g=>{let b=new tt.Menu;if(n.onMove&&(b.addItem(v=>v.setTitle("Move up").setIcon("arrow-up").setDisabled(!n.canMoveUp).onClick(()=>n.onMove?.(-1))),b.addItem(v=>v.setTitle("Move down").setIcon("arrow-down").setDisabled(!n.canMoveDown).onClick(()=>n.onMove?.(1)))),n.onRemove&&(n.onMove&&b.addSeparator(),b.addItem(v=>{v.setTitle("Remove field").setIcon("trash-2").onClick(()=>n.onRemove?.()),v.setWarning(!0)})),g.detail===0){let v=y.getBoundingClientRect();b.showAtPosition({x:v.left,y:v.bottom})}else b.showAtMouseEvent(g)}}let m=Ea(t);this.renderConstraintControls(i,t,m,n,d),m==="enum"&&this.renderEnumFieldDetails(i,t,n,d),m==="link"&&this.renderLinkFieldDetails(i,t,n),m==="list"&&this.renderListFieldDetails(i,t,n),m==="object"&&this.renderObjectFieldDetails(i,t,n)}renderConstraintControls(e,t,n,i,s){let a=n==="integer"||n==="number"?[["min","Minimum"],["max","Maximum"]]:n==="string"?[["min_length","Min length"],["max_length","Max length"]]:n==="list"?[["min_length","Min items"],["max_length","Max items"]]:[],c=!["list","object","any","link"].includes(n);if(!a.length&&n!=="string"&&!c)return;let l=e.createDiv({cls:"mdbase-field-details mdbase-field-constraints"}),u=i.name||i.staticLabel||"Field",d=this.fieldId(t);for(let[g,b]of a){let v=l.createDiv({cls:"mdbase-constraint"}),S=v.createEl("label",{text:b}),_=v.createEl("input",{type:"number"});_.id=`mdbase-${d}-${g}`,S.htmlFor=_.id,_.setAttr("data-focus-key",`field-${d}-${g}`),_.setAttr("aria-label",`${u} ${b.toLowerCase()}`),(g.endsWith("length")||n==="integer")&&(_.step="1"),g.endsWith("length")&&(_.min="0"),_.value=typeof t[g]=="number"?String(t[g]):"",_.disabled=i.readOnly,_.oninput=()=>{let E=_.value.trim()===""?NaN:Number(_.value);Number.isFinite(E)?t[g]=E:delete t[g],s(),this.markDirty()}}if(n==="string"){let g=l.createDiv({cls:"mdbase-constraint mdbase-constraint-wide"}),b=g.createEl("label",{text:"Pattern"}),v=g.createEl("input",{type:"text"});v.id=`mdbase-${d}-pattern`,b.htmlFor=v.id,v.setAttr("data-focus-key",`field-${d}-pattern`),v.setAttr("aria-label",`${u} pattern`),v.placeholder="Regular expression",v.spellcheck=!1,v.value=typeof t.pattern=="string"?t.pattern:"",v.disabled=i.readOnly,v.oninput=()=>{v.value?t.pattern=v.value:delete t.pattern,s(),this.markDirty()}}if(!c)return;let f=l.createDiv({cls:"mdbase-constraint mdbase-constraint-wide"}),p=f.createEl("label",{text:"Default"}),h=`mdbase-${d}-default`;if(p.htmlFor=h,n==="enum"||n==="boolean"){let g=f.createEl("select");g.id=h,g.setAttr("data-focus-key",`field-${d}-default`),g.createEl("option",{value:"",text:"None"});let b=n==="boolean"?[!0,!1]:Array.isArray(t.values)?t.values:[];for(let[S,_]of b.entries())g.createEl("option",{value:String(S),text:an(_)});let v=b.findIndex(S=>JSON.stringify(S)===JSON.stringify(t.default));t.default!==void 0&&v===-1?(g.createEl("option",{value:"missing",text:`${an(t.default)} \xB7 not allowed`}),g.value="missing"):g.value=v===-1?"":String(v),g.disabled=i.readOnly,g.onchange=()=>{g.value===""?delete t.default:g.value!=="missing"&&(t.default=b[Number(g.value)]),s(),this.markDirty()};return}let m=f.createEl("input",{type:"text"});m.id=h,m.setAttr("data-focus-key",`field-${d}-default`),m.setAttr("aria-label",`${u} default`),m.placeholder=n==="date"?"YYYY-MM-DD":n==="time"?"HH:MM":"None",m.value=t.default===void 0?"":an(t.default),m.disabled=i.readOnly;let y=f.createDiv({cls:"mdbase-constraint-error"});m.oninput=()=>{let g=V$(m.value,n);y.textContent=g.error??"",m.toggleClass("is-invalid",!!g.error),!g.error&&(g.value===void 0?delete t.default:t.default=g.value,s(),this.markDirty())}}fieldId(e){let t=this.fieldIds.get(e);if(t)return t;let n=`field-${this.nextFieldId}`;return this.nextFieldId+=1,this.fieldIds.set(e,n),n}fieldMatches(e,t,n){return`${e} ${Ea(t)} ${typeof t.description=="string"?t.description:""}`.toLowerCase().includes(n)||Se(t.items)&&this.fieldMatches("item",t.items,n)?!0:Se(t.fields)?Object.entries(t.fields).some(([s,o])=>Se(o)&&this.fieldMatches(s,o,n)):!1}renderEnumFieldDetails(e,t,n,i){let s=e.createDiv({cls:"mdbase-field-details mdbase-enum-values"}),o=n.name||n.staticLabel||"Enum",a=this.fieldId(t);s.createDiv({cls:"mdbase-field-children-label",text:"Allowed values"});let c=Array.isArray(t.values)?t.values:[];!Array.isArray(t.values)&&!n.readOnly&&(t.values=c);let l=s.createDiv({cls:"mdbase-enum-list"});l.setAttr("role","list");let u=new Set(c.map(f=>typeof f)).size>1;for(let[f,p]of c.entries()){let h=l.createDiv({cls:"mdbase-enum-row"});h.setAttr("role","listitem");let m=h.createEl("input",{type:"text"});m.setAttr("data-focus-key",`field-${a}-value-${f}`),m.setAttr("aria-label",`${o} allowed value ${f+1}`),m.value=an(p),m.disabled=n.readOnly,m.oninput=()=>{c[f]=U$(m.value,p,c.filter((g,b)=>b!==f)),i(),this.markDirty()},m.onkeydown=g=>{g.key==="Enter"&&(g.preventDefault(),c.splice(f+1,0,""),this.ctx.pendingFocusKey=`field-${a}-value-${f+1}`,this.markDirty(!0))},u&&h.createSpan({cls:"mdbase-enum-kind",text:typeof p});for(let[g,b,v]of[["arrow-up","Move value up",-1],["arrow-down","Move value down",1]]){let S=this.ctx.iconButton(h,g,`${b}: ${an(p)}`);S.disabled=n.readOnly||f+v<0||f+v>=c.length,S.onclick=()=>{[c[f],c[f+v]]=[c[f+v],c[f]],this.markDirty(!0)}}let y=this.ctx.iconButton(h,"x",`Remove value ${an(p)}`);y.disabled=n.readOnly,y.onclick=()=>{c.splice(f,1),this.markDirty(!0)}}let d=s.createEl("button",{cls:"mdbase-link-button",text:"Add value"});d.disabled=n.readOnly,d.onclick=()=>{c.push(""),this.ctx.pendingFocusKey=`field-${a}-value-${c.length-1}`,this.markDirty(!0)}}renderLinkFieldDetails(e,t,n){let i=e.createDiv({cls:"mdbase-field-details mdbase-field-options"}),s=this.fieldId(t),o=i.createEl("label",{text:"Target type"}),a=i.createEl("select");a.setAttr("data-focus-key",`field-${s}-target`),a.setAttr("aria-label",`${n.name||n.staticLabel||"Link"} target type`),a.createEl("option",{value:"",text:"Any type"});let c=typeof t.target=="string"?t.target:"";for(let d of this.typeEntries())a.createEl("option",{value:d.name,text:d.name});c&&!this.typeEntries().some(d=>d.name===c)&&a.createEl("option",{value:c,text:`${c} \xB7 missing`}),a.value=c,a.disabled=n.readOnly,a.onchange=()=>{a.value?t.target=a.value:delete t.target,this.markDirty()},o.htmlFor=a.id=`mdbase-${s}-target`;let l=i.createEl("label",{cls:"mdbase-field-required"}),u=l.createEl("input",{type:"checkbox"});u.setAttr("data-focus-key",`field-${s}-exists`),u.checked=t.validate_exists===!0,u.disabled=n.readOnly,u.onchange=()=>{t.validate_exists=u.checked,this.markDirty()},l.createSpan({text:"Validate target exists"})}renderListFieldDetails(e,t,n){let i=e.createDiv({cls:"mdbase-field-children"});i.createDiv({cls:"mdbase-field-children-label",text:"List items"});let s=Se(t.items)?t.items:{type:"any"};!Se(t.items)&&!n.readOnly&&(t.items=s),this.renderFieldDefinition(i,s,{staticLabel:"Item",nameLabel:"List item",readOnly:n.readOnly,depth:n.depth+1})}renderObjectFieldDetails(e,t,n){let i=e.createDiv({cls:"mdbase-field-children"});i.createDiv({cls:"mdbase-field-children-label",text:"Object fields"});let s=Se(t.fields)?t.fields:{};!Se(t.fields)&&!n.readOnly&&(t.fields=s);let o=i.createDiv({cls:"mdbase-nested-fields"}),a=i.createEl("button",{cls:"mdbase-link-button",text:"Add nested field"});a.disabled=n.readOnly,a.onclick=()=>{let l=R$(s);Sd(s,l,{type:"string"}),this.expandedFields.add(this.fieldId(s[l])),this.markDirty(!0)};let c=Object.entries(s).filter(l=>Se(l[1]));if(!c.length){o.createDiv({cls:"mdbase-empty-list",text:"No nested fields."});return}for(let[l,[u,d]]of c.entries()){let f=u;this.renderFieldDefinition(o,d,{name:f,nameLabel:`${f} nested field name`,onNameCommit:(p,h)=>{let m=p.trim();if(!m){new tt.Notice("Nested field name is required."),h.value=f;return}if(m!==f&&Object.prototype.hasOwnProperty.call(s,m)){new tt.Notice(`Nested field already exists: ${m}`),h.value=f;return}m!==f&&(delete s[f],Sd(s,m,d),f=m,this.markDirty())},required:d.required===!0,onRequiredChange:p=>{d.required=p,this.markDirty()},onRemove:()=>{delete s[f],this.markDirty(!0)},onMove:p=>{let h=Object.keys(s),m=h.indexOf(f),y=m+p;if(m===-1||y<0||y>=h.length)return;[h[m],h[y]]=[h[y],h[m]];let g=h.map(b=>[b,s[b]]);for(let b of h)delete s[b];for(let[b,v]of g)Se(v)&&Sd(s,b,v);this.pendingFieldReveal=this.fieldId(d),this.markDirty(!0)},canMoveUp:l>0,canMoveDown:lthis.onYamlInput(s.value)}}ensureYamlEditor(e){try{return this.yamlEditor?(this.yamlEditor.setValue(this.yamlDraft),this.yamlEditor.setReadOnly(e)):this.yamlEditor=new Ad({doc:this.yamlDraft,readOnly:e,labelledBy:"mdbase-mode-yaml",onChange:t=>this.onYamlInput(t)}),this.yamlEditor.setProblems(this.yamlProblems()),this.yamlEditor}catch(t){return console.error("mdbase: YAML editor unavailable",t),this.yamlEditor=null,null}}onYamlInput(e){this.yamlDraft=e,this.markDirty(!1),this.yamlProblemTimer!==null&&window.clearTimeout(this.yamlProblemTimer),this.yamlProblemTimer=window.setTimeout(()=>{this.yamlProblemTimer=null;let t=this.yamlProblems();this.yamlEditor?.setProblems(t);let n=this.ctx.containerEl.querySelector(".mdbase-yaml-problems");n&&(n.empty(),this.fillYamlProblems(n,t))},250)}fillYamlProblems(e,t=this.yamlProblems()){if(!(!this.dirty||!t.length))for(let n of t.slice(0,20)){let i=e.createEl("button",{cls:"mdbase-yaml-problem"});if(i.setAttr("data-severity",n.severity),i.createSpan({cls:"mdbase-yaml-problem-line-number",text:n.line?`Line ${n.line}`:"Type"}),i.createSpan({text:n.message}),i.disabled=n.line===null,n.line!==null){let s=n.line;i.onclick=()=>this.yamlEditor?.revealLine(s)}}}async leaveCurrentType(){this.dirty&&await this.flushTypeDraft(),this.yamlEditor?.destroy(),this.yamlEditor=null,this.impact=null,this.showAllMatches=!1}async selectType(e,t=!0){t&&e!==this.selectedPath&&await this.leaveCurrentType();let n=++this.typeSelectionVersion,i=await this.ctx.host.loadTypeModel(e);if(n!==this.typeSelectionVersion)return;let s=this.ctx.host.loadTypeDraft(e),o=s?.version===1&&s.sourceRevision===(i.sourceRevision??null),a=o?Bn(s.model):i;this.selectedPath=e,this.model=a,this.originalModel=Bn(i),this.yamlDraft=o&&s.yamlDraft!==void 0?s.yamlDraft:`${gt(Aa(i),i.body)} +`,this.dirty=!vd(this.originalModel,a),this.editorMode=o&&s.editorMode==="yaml"?"yaml":"design",this.editorMode==="yaml"&&(this.dirty=!0),o&&this.dirty?this.sessionDrafts.has(e)||(this.ctx.message=`Recovered unsaved changes for ${e}.`):s&&!o&&(this.ctx.message=`An older draft for ${e} was kept, but the source changed. The current file is shown.`),this.scheduleImpact(0),this.ctx.render()}async createType(){await this.leaveCurrentType(),this.typeSelectionVersion+=1;let e=this.ctx.host.loadTypeDraft(null),t=e?.version===1?Bn(e.model):Km();this.selectedPath=null,this.model=t,this.originalModel=null,this.yamlDraft=e?.yamlDraft??"",this.dirty=!0,e&&!this.sessionDrafts.has("__new__")&&(this.ctx.message="Recovered an unsaved new type."),this.editorMode=e?.editorMode??"design",this.scheduleImpact(0),this.ctx.render()}switchEditorMode(e){if(!(!this.model||e===this.editorMode)){if(e==="yaml")try{this.yamlDraft=`${gt(Aa(this.model),this.model.body)} +`}catch(t){new tt.Notice(t instanceof Error?t.message:String(t));return}else if(!this.readYamlDraftIntoModel())return;this.editorMode=e,e==="design"&&(this.yamlEditor?.destroy(),this.yamlEditor=null),this.scheduleImpact(0),this.ctx.render()}}modelFromYamlDraft(){let e=Me(this.yamlDraft);if(!e.hasFrontmatter)return{error:"Type YAML must start with a --- frontmatter block.",line:1};if(e.error)return{error:`Invalid YAML: ${e.error.split(` +`)[0].replace(/:$/,"").replace(/ at line \d+, column \d+$/,"")}`,line:z$(e.error)};if(e.frontmatter.kind!=="mdbase.type")return{error:"Canonical v0.3 type YAML requires kind: mdbase.type.",line:oy(this.yamlDraft,"kind")??2};try{let t=bd(e.frontmatter,e.body,this.model?.name||"type");return this.model?.sourceRevision&&(t.sourceRevision=this.model.sourceRevision),{model:t}}catch(t){return{error:t instanceof Error?t.message:String(t),line:null}}}yamlProblems(){let e=this.modelFromYamlDraft();return"error"in e?[{line:e.line??null,message:e.error,severity:"error"}]:Sa(e.model,{knownTypes:this.typeEntries().map(t=>t.name),contracts:this.ctx.schema?.contracts.values()}).map(t=>{let n=t.path.startsWith("fields.")?t.path.slice(7).split(/[.[]/)[0]:t.path==="identity.displayNameKey"?"name_field":t.path.split(".").pop()??"";return{line:oy(this.yamlDraft,n),message:t.message,severity:t.severity==="error"?"error":"warning"}})}readYamlDraftIntoModel(){let e=this.modelFromYamlDraft();return"error"in e?(new tt.Notice(e.error),e.line&&this.yamlEditor?.revealLine(e.line),!1):(this.model=e.model,!0)}async saveCurrentType(){if(!this.model||this.model.specProfile!=="v0.3"||this.model.readOnlyReason||this.editorMode==="yaml"&&!this.readYamlDraftIntoModel())return;let t=Sa(this.model,{knownTypes:this.typeEntries().map(a=>a.name),contracts:this.ctx.schema?.contracts.values()}).filter(a=>a.severity==="error");if(t.length){this.ctx.message=`${t.length} ${t.length===1?"error must":"errors must"} be fixed before saving.`,this.ctx.render(),new tt.Notice(t[0].message);return}let n=xa(this.originalModel,this.model).filter(a=>a.risk==="high"),i=await this.computeImpact();i!==void 0&&(this.impact=i);let s=this.impact&&!("error"in this.impact)?this.impact.impact.failing.filter(a=>a.isNew).map(a=>a.path):[];if(n.length||s.length){let a=n.length?n:xa(this.originalModel,this.model).filter(l=>l.risk!=="safe");if(!await new Ec(this.ctx.app).confirm(a,s))return}let o=this.model;await this.flushTypeDraft(),await this.ctx.perform(async()=>{let a=this.selectedPath,c=await this.ctx.host.saveTypeModel(o,a,this.originalModel?.sourceRevision);await this.ctx.host.clearTypeDraft(a),a!==c.path&&await this.ctx.host.clearTypeDraft(c.path),this.selectedPath=c.path,this.originalModel=Bn(o),this.dirty=!1,this.ctx.message=`Saved ${c.path}.`,await this.ctx.refresh(!0)})}markDirty(e=!1){let t=this.dirty;if(this.dirty=this.editorMode==="yaml"?!0:!vd(this.originalModel,this.model),this.scheduleTypeDraftSave(),this.scheduleImpact(),this.dirty&&!t&&(this.ctx.message=""),e||t!==this.dirty){this.ctx.render();return}let n=this.ctx.containerEl.querySelector(".mdbase-type-editor-pane"),i=n?.querySelector(".mdbase-draft-bar");if(n&&i&&this.model){i.remove(),this.renderDraftBar(n,this.model);let s=n.querySelector(".mdbase-editor-title-line h2");s&&(s.textContent=this.model.name||"Untitled type")}}scheduleTypeDraftSave(){this.draftSaveTimer!==null&&window.clearTimeout(this.draftSaveTimer),this.draftSaveTimer=window.setTimeout(()=>{this.draftSaveTimer=null,this.flushTypeDraft()},2e3)}async flushTypeDraft(){if(this.draftSaveTimer!==null&&(window.clearTimeout(this.draftSaveTimer),this.draftSaveTimer=null),!this.model)return;if(!this.dirty){let t=this.ctx.host.loadTypeDraft(this.selectedPath);t&&t.sourceRevision===(this.originalModel?.sourceRevision??null)&&await this.ctx.host.clearTypeDraft(this.selectedPath);return}this.sessionDrafts.add(this.selectedPath??"__new__");let e={version:1,path:this.selectedPath,sourceRevision:this.originalModel?.sourceRevision??null,model:Bn(this.model),editorMode:this.editorMode,yamlDraft:this.editorMode==="yaml"?this.yamlDraft:void 0,updatedAt:new Date().toISOString()};await this.ctx.host.saveTypeDraft(e)}async discardCurrentType(){let e=this.selectedPath,t=this.ctx.host.loadTypeDraft(e);if((!t||t.sourceRevision===(this.originalModel?.sourceRevision??null))&&await this.ctx.host.clearTypeDraft(e),e){let n=await this.ctx.host.loadTypeModel(e);this.model=n,this.originalModel=Bn(n),this.yamlDraft=`${gt(Aa(n),n.body)} +`,this.dirty=!1}else this.model=null,this.originalModel=null,this.yamlDraft="",this.dirty=!1;this.ctx.message="Unsaved changes discarded.",this.ctx.render()}};function Aa(r){return r.specProfile==="v0.3"&&!r.readOnlyReason?jn(r):Bn(r.originalFrontmatter??{name:r.name,fields:Object.fromEntries(r.fields.map(e=>[e.name,e.definition]))})}var Lr="mdbase-workspace-view",Cd=class r extends Ds.ItemView{constructor(t,n){super(t);this.host=n;this.destination="types";this.message="";this.pendingFocusKey=null;this.busy=!1;this.schema=null;this.records=null;this.disclosures=new Map;this.types=new Pd(this);this.sync=new kd(this);this.issues=new wd(this);this.navigationId=`mdbase-workspace-${++r.nextNavigationId}`;this.refreshVersion=0;this.unsubscribeSync=null;this.syncRenderTimer=null}static{this.nextNavigationId=0}getState(){return this.captureRenderSnapshot(this.containerEl),{destination:this.destination,...this.types.getState(),...this.issues.getState(),...this.sync.getState(),disclosures:Object.fromEntries(this.disclosures)}}async setState(t,n){if(["types","sync","issues"].includes(String(t.destination))&&(this.destination=t.destination),t.disclosures&&typeof t.disclosures=="object")for(let[i,s]of Object.entries(t.disclosures))typeof s=="boolean"&&this.disclosures.set(i,s);await this.types.setState(t),this.issues.setState(t),this.sync.setState(t),await this.refresh(),this.types.restoreEditorMode(t.editorMode),await super.setState(t,n)}refreshValidationControls(){this.destination==="issues"&&this.render()}updateValidationProgress(){this.issues.updateValidationProgress()}getViewType(){return Lr}getDisplayText(){return"mdbase"}getIcon(){return $a}async onOpen(){this.containerEl.addClass("mdbase-workspace"),this.registerDomEvent(this.containerEl,"keydown",n=>{(n.metaKey||n.ctrlKey)&&n.key.toLowerCase()==="s"&&this.types.dirty&&(n.preventDefault(),this.types.saveCurrentType())});let t=this.host.sync.state;this.unsubscribeSync=this.host.sync.subscribe(()=>{let n=this.host.sync.state,i=Object.keys(n).every(s=>s==="progress"||s==="fileProgress"||t[s]===n[s]);if(t=n,i&&(n.progress||n.fileProgress)){this.destination==="sync"&&this.syncRenderTimer===null&&(this.syncRenderTimer=window.setTimeout(()=>{this.syncRenderTimer=null,this.destination==="sync"&&this.render()},100));return}this.cancelSyncRender(),this.destination==="sync"?this.render():this.renderTopbarOnly()})}async onClose(){this.refreshVersion++,this.unsubscribeSync?.(),this.unsubscribeSync=null,this.cancelSyncRender(),await this.types.dispose(),this.sync.dispose()}cancelSyncRender(){this.syncRenderTimer!==null&&window.clearTimeout(this.syncRenderTimer),this.syncRenderTimer=null}async refresh(t=!1){let n=++this.refreshVersion,i=()=>n===this.refreshVersion;try{let s=await this.host.loadWorkspaceSchema(t);if(!i())return;if(this.schema=s,this.destination==="types"){if(await this.types.onSchemaLoaded(t,i),!i())return;let o=s?await this.host.loadCollectionRecords():null;if(!i())return;let a=o!==this.records;this.records=o,this.types.onRecordsLoaded(a||t)}else this.destination==="sync"&&await this.sync.refresh();if(!i())return;this.render()}catch(s){if(!i())return;this.message=s instanceof Error?s.message:String(s),this.render()}}showDestination(t){this.destination=t,this.render(),t==="types"?this.refresh():t==="sync"&&this.sync.refresh().then(()=>this.render())}showIssuesForPath(t){this.issues.filterToPath(t),this.showDestination("issues")}openTypeField(t,n){return this.types.openTypeField(t,n)}recordTypes(){return this.types.currentStats().recordTypes}createNewType(){this.types.createNewType()}editType(t){return this.types.editType(t)}focusSyncSection(t){this.sync.focusSection(t)}reconnectCollection(){return this.sync.reconnectCollection()}render(){let t=this.containerEl,n=this.captureRenderSnapshot(t);t.empty(),t.addClass("mdbase-workspace");let i=t.createDiv({cls:"mdbase-shell"});if(this.renderTopbar(i),this.message){let o=i.createDiv({cls:"mdbase-inline-message mdbase-notice"});o.createSpan({text:this.message}).setAttr("role","status");let a=this.iconButton(o,"x","Dismiss message");a.onclick=()=>{this.message="",this.render()}}let s=i.createDiv({cls:"mdbase-workspace-content"});s.setAttr("data-scroll-key","workspace"),s.id=`${this.navigationId}-${this.destination}-panel`,s.setAttr("role","tabpanel"),s.setAttr("aria-labelledby",`${this.navigationId}-${this.destination}-tab`),this.destination==="types"?this.types.render(s):this.destination==="sync"?this.sync.render(s):this.issues.render(s),this.restoreRenderSnapshot(t,n),this.app.workspace?.requestSaveLayout(),this.pendingFocusKey&&(this.focusTarget(t,this.pendingFocusKey)?.focus(),this.pendingFocusKey=null),this.destination==="types"&&this.types.afterRender(t)}syncAttention(){let{status:t,preview:n}=this.host.sync.state,i=t?.conflicts.length??0;if(i)return{count:i,label:`${i} sync ${i===1?"conflict":"conflicts"}`};let s=this.host.sync.safety(),o=s&&!s.safe?n?.plan.actions.length??0:0;return o?{count:o,label:`${o} ${o===1?"change needs":"changes need"} review`}:null}syncTabStatus(){if(this.destination==="sync"||!this.host.getMirrorProfile())return null;let{problem:t,paused:n,status:i,progress:s,fileProgress:o}=this.host.sync.state;if(s||o)return null;let a=t?.kind??(n?"paused":i?.recovery_required?"recovery":null);return!a||a==="busy"?null:{kind:a,label:{offline:"Offline",auth:"Sign in",device:"Set up",internal:"Error",decision:"Review",recovery:"Review",paused:"Paused"}[a],detail:t?.title??(n?"Sync is paused":"Synchronization needs recovery")}}renderTopbarOnly(){let t=this.containerEl.querySelector(".mdbase-topbar");if(!t)return;let n=this.captureRenderSnapshot(t),i=this.containerEl.ownerDocument.createElement("div");this.renderTopbar(i);let s=i.firstElementChild;s&&(t.replaceWith(s),this.restoreRenderSnapshot(s,n))}captureRenderSnapshot(t){for(let a of Array.from(t.querySelectorAll("details[data-disclosure]"))){let c=a.dataset.disclosure;c&&this.disclosures.set(c,a.open)}let n=t.ownerDocument,i=t.contains(n.activeElement)?n.activeElement:null,s=i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement?i:null,o=new Map;for(let a of Array.from(t.querySelectorAll("[data-scroll-key]"))){let c=a.getAttr("data-scroll-key");c&&o.set(c,{top:a.scrollTop,left:a.scrollLeft})}return{focusKey:i?.getAttr("data-focus-key")??null,selectionStart:s?.selectionStart??null,selectionEnd:s?.selectionEnd??null,scroll:o}}restoreRenderSnapshot(t,n){for(let[s,o]of n.scroll){let a=t.querySelector(`[data-scroll-key="${s}"]`);a&&(a.scrollTop=o.top,a.scrollLeft=o.left)}if(!n.focusKey)return;let i=this.focusTarget(t,n.focusKey);i?.focus({preventScroll:!0}),(i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement)&&n.selectionStart!==null&&n.selectionEnd!==null&&i.setSelectionRange(n.selectionStart,n.selectionEnd)}focusTarget(t,n){return Array.from(t.querySelectorAll("[data-focus-key]")).find(i=>i.getAttr("data-focus-key")===n)}iconButton(t,n,i){let s=t.createEl("button",{cls:"clickable-icon mdbase-icon-button"});return s.setAttr("aria-label",i),s.setAttr("title",i),s.setAttr("data-focus-key",`action-${i.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`),(0,Ds.setIcon)(s,n),s}disclosure(t,n,i,s=!1){let o=t.createEl("details",{cls:"mdbase-disclosure"});return o.dataset.disclosure=n,o.open=this.disclosures.get(n)??s,o.addEventListener("toggle",()=>{this.containerEl.contains(o)&&(this.disclosures.set(n,o.open),this.app.workspace?.requestSaveLayout())}),o.createEl("summary",{text:i}).setAttr("data-focus-key",`disclosure-${n}`),o.createDiv({cls:"mdbase-disclosure-body"})}renderTopbar(t){let i=t.createDiv({cls:"mdbase-topbar"}).createDiv({cls:"mdbase-nav"});i.setAttr("role","tablist"),i.setAttr("aria-label","mdbase destinations");let s=[["types","Types"],["sync","Sync"],["issues","Issues"]];for(let[o,[a,c]]of s.entries()){let l=i.createEl("button",{text:c,cls:"clickable-icon"});if(l.addClass("mdbase-nav-button"),l.setAttr("role","tab"),l.id=`${this.navigationId}-${a}-tab`,this.destination===a&&l.setAttr("aria-controls",`${this.navigationId}-${a}-panel`),l.tabIndex=this.destination===a?0:-1,l.setAttr("data-focus-key",`destination-${a}`),l.setAttr("aria-selected",String(this.destination===a)),this.destination===a&&l.addClass("is-active"),a==="issues"&&this.host.getIssues().length){let f=this.host.getIssues().length;l.createSpan({cls:"mdbase-count",text:ty(f)}).setAttr("title",`${f} issues`),l.setAttr("aria-label",`Issues \xB7 ${f} validation ${f===1?"issue":"issues"}`)}let u=a==="sync"?this.syncTabStatus():null,d=a==="sync"?this.syncAttention():null;if(u){let f=l.createSpan({cls:"mdbase-count mdbase-nav-status",text:u.label});f.setAttr("data-kind",u.kind),f.setAttr("title",u.detail),l.setAttr("aria-label",`Sync \xB7 ${u.detail}`)}else d&&(l.createSpan({cls:"mdbase-count",text:ty(d.count)}).setAttr("title",d.label),l.setAttr("aria-label",`Sync \xB7 ${d.label}`));l.onclick=()=>this.showDestination(a),l.onkeydown=f=>{let p=f.key==="ArrowRight"?(o+1)%s.length:f.key==="ArrowLeft"?(o+s.length-1)%s.length:f.key==="Home"?0:f.key==="End"?s.length-1:null;p!==null&&(f.preventDefault(),this.pendingFocusKey=`destination-${s[p][0]}`,this.showDestination(s[p][0]))}}}async perform(t){if(!this.busy){this.busy=!0,this.message="",this.render();try{await t()}catch(n){let i=n instanceof Error?n.message:String(n);this.message=i,new Ds.Notice(i)}finally{this.busy=!1,this.render()}}}};var Pa=class{constructor(e,t){this.delayMs=e;this.task=t;this.entries=new Map;if(!Number.isFinite(e)||e<0)throw new Error("Debounce delay must be a non-negative finite number.")}has(e){return this.entries.has(e)}schedule(e,t){let n=this.entries.get(e);n||(n={value:t,revision:0,timer:null,ready:!1,running:!1},this.entries.set(e,n)),n.value=t,n.revision+=1,n.ready=!1,n.timer!==null&&clearTimeout(n.timer),n.timer=setTimeout(()=>{this.entries.get(e)===n&&(n.timer=null,n.ready=!0,this.drain(e,n))},this.delayMs)}cancel(e){let t=this.entries.get(e);t&&(t.timer!==null&&clearTimeout(t.timer),this.entries.delete(e))}clear(){for(let e of this.entries.values())e.timer!==null&&clearTimeout(e.timer);this.entries.clear()}async drain(e,t){if(this.entries.get(e)!==t||t.running||!t.ready)return;t.ready=!1,t.running=!0;let n=t.revision,i=t.value,s=()=>this.entries.get(e)===t&&t.revision===n;try{await this.task(i,s)}finally{t.running=!1,this.entries.get(e)===t&&(t.ready?this.drain(e,t):t.timer===null&&t.revision===n&&this.entries.delete(e))}}};var K$=require("obsidian");var Md=class extends K$.Modal{constructor(t,n,i){super(t);this.path=n;this.runs=i}onOpen(){this.titleEl.setText(`Sync history \xB7 ${this.path.split("/").pop()??this.path}`),this.contentEl.addClass("mdbase-note-history");let t=Kx(this.runs,this.path).map(({run:i,file:s})=>({at:s.at,label:i.summary??Gx(s),detail:i.summary===void 0&&s.fromPath?`From ${s.fromPath}`:s.message}));if(!t.length){this.contentEl.createEl("p",{cls:"mdbase-muted",text:"No syncs of this note are recorded on this device."});return}let n=this.contentEl.createDiv({cls:"mdbase-transfer-ledger"});for(let i of t){let s=n.createDiv({cls:"mdbase-note-history-row"});s.createSpan({cls:"mdbase-muted",text:As(i.at)});let o=s.createDiv();o.createDiv({text:i.label}),i.detail&&o.createDiv({cls:"mdbase-muted",text:i.detail})}}onClose(){this.contentEl.empty()}};var De=require("obsidian");var lj=[["image","Images"],["audio","Audio"],["video","Video"],["pdf","PDFs"],["other","Other files"]],Rd=class extends De.PluginSettingTab{constructor(t,n){super(t,n);this.plugin=n}display(){let{containerEl:t,plugin:n}=this;t.empty(),new De.Setting(t).setName("Validate notes automatically").setDesc("Check notes against their types when they are opened or saved.").addToggle(i=>i.setValue(n.settings.validateOnSave||n.settings.validateOnOpen).onChange(async s=>{n.settings.validateOnSave=s,n.settings.validateOnOpen=s,await n.saveSettings(),this.display()})),n.settings.validateOnSave&&new De.Setting(t).setName("Show validation notices").setDesc("Notify when saving a note with issues.").addToggle(i=>i.setValue(n.settings.showNoticeOnSave).onChange(async s=>{n.settings.showNoticeOnSave=s,await n.saveSettings()})),new De.Setting(t).setName("Allow plugin integrations").setDesc("Let other installed plugins exchange mdbase events and actions in this vault.").addToggle(i=>i.setValue(n.settings.interopEnabled).onChange(async s=>{n.settings.interopEnabled=s,await n.saveSettings()})),this.displaySync(t)}displaySync(t){let{plugin:n}=this,i=n.getMirrorProfile();if(new De.Setting(t).setName("Sync").setHeading(),!i){new De.Setting(t).setName("Not connected").setDesc("Connect this vault to mdbase Connect from the sync tab of the mdbase workspace.").addButton(l=>l.setButtonText("Open sync").onClick(()=>{n.openWorkspace("sync")}));return}new De.Setting(t).setName(i.name).setDesc(`${i.mode==="read_write"?"Read and write":"Read only"} \xB7 ${new URL(i.controlUrl).host}`).addButton(l=>l.setButtonText("Reconnect").onClick(async()=>{l.setDisabled(!0);try{await n.openWorkspace("sync").then(u=>u.reconnectCollection())}catch(u){new De.Notice(u instanceof Error?u.message:String(u))}finally{l.setDisabled(!1)}})),new De.Setting(t).setName("Sync automatically").setDesc("Keep this vault in sync in the background. Deleted files go to the trash, and conflicting edits are merged or kept as two files. Deleting many files at once on this device waits for your review.").addToggle(l=>l.setValue(n.settings.autoSync).onChange(async u=>{n.settings.autoSync=u,await n.saveSettings(),n.requestSync()}));let s=n.connectSync.getSelectiveSync(),o=async l=>{try{return await n.sync.configureSelectiveSync(l),!0}catch(u){return new De.Notice(u instanceof Error?u.message:String(u)),this.display(),!1}};for(let[l,u]of lj)new De.Setting(t).setName(`Sync ${u.toLowerCase()}`).setDesc(l==="other"?"All remaining visible file formats. Markdown always syncs.":"").addToggle(d=>d.setValue(s.file_classes.includes(l)).onChange(async f=>{let p=n.connectSync.getSelectiveSync();await o({...p,file_classes:f?[...new Set([...p.file_classes,l])]:p.file_classes.filter(h=>h!==l)})}));let a=[...s.excluded_folders],c=new De.Setting(t).setName("Excluded folders").setDesc($d);Ed(this.app,c.controlEl,a,l=>{a=l}),c.addButton(l=>l.setButtonText("Apply").onClick(async()=>{l.setDisabled(!0);try{await o({...n.connectSync.getSelectiveSync(),excluded_folders:a})&&new De.Notice("Excluded folders updated. The next sync applies them.")}finally{l.setDisabled(!1)}})),new De.Setting(t).setName("Disconnect").setDesc("Stop syncing this vault. The hosted collection is not deleted.").addButton(l=>l.setButtonText("Disconnect\u2026").setWarning().setDisabled(n.sync.isSyncing()).onClick(async()=>{let u=await new Ac(this.app).choose(i.name);if(u){try{await n.sync.disconnect(i,u==="remove"),new De.Notice(n.sync.state.message)}catch(d){new De.Notice(d instanceof Error?d.message:String(d))}this.display()}}))}};async function W$(r,e,t,n){let i=await r.resolveConflict(e,t,n),s=await r.preview();return{status:i,preview:s}}var dj=4,G$={status:null,preview:null,progress:null,fileProgress:null,problem:null,message:"",localChangeObserved:!1,busy:!1,paused:!1,retryAt:null},Id=class{constructor(e,t,n,i=()=>{}){this.controller=e;this.getProfile=t;this.history=n;this.notify=i;this.current={...G$};this.listeners=new Set;this.safetyPreview=null;this.previewSafety=null;this.pinnedFailure=null}get state(){return this.current}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}update(e){this.current={...this.current,...e};for(let t of this.listeners)t()}reset(){this.update({...G$})}isSyncing(){return this.controller.isSyncing()}clearMessage(){this.current.message&&this.update({message:""})}observeLocalChange(){this.current.localChangeObserved||this.update({localChangeObserved:!0})}historyRuns(){let e=this.getProfile()?.collectionId;return e?this.history?.list(e)??[]:[]}async recordEvent(e,t=this.getProfile()?.collectionId){if(!(!t||!this.history)){try{await this.history.append(dd(t,e))}catch(n){console.error("mdbase: could not save sync history",n)}this.update({})}}async dismissEvent(e){await this.history?.acknowledge(e),this.update({})}async clearHistory(){await this.history?.clear(),this.update({})}async refreshStatus(){let e=this.getProfile();if(!e)return this.reset(),null;if(this.controller.isSyncing())return this.current.status;try{let t=await this.controller.status();return Td(e,this.getProfile())?(this.update({status:t,problem:null}),t):null}catch(t){return Td(e,this.getProfile())&&this.update({problem:Dt(t)}),null}}async review(){return this.getProfile()?await this.exclusive(async()=>(await this.loadPreview(),this.current.preview))??null:null}async apply(){if(!this.current.preview){await this.review();return}await this.exclusive(()=>this.applyReviewed())}async syncNow(e={}){return this.getProfile()?this.current.busy||this.controller.isSyncing()?"busy":e.automatic&&this.current.paused?"paused":(!e.automatic&&this.current.paused&&this.update({paused:!1}),await this.exclusive(async()=>{let n=!1;for(let i=0;it.outcome!=="unresolved")}safety(){let e=this.current.preview;return e!==this.safetyPreview&&(this.safetyPreview=e,this.previewSafety=e?Nx(e):null),this.previewSafety}cancel(){this.update({paused:!0}),this.controller.isSyncing()&&(this.controller.cancelSync(),this.update({message:"Stopping\u2026"}))}async reconnect(){return await this.exclusive(async()=>{try{let t=await this.controller.reconnect();return this.update({status:t,problem:null,message:"Connection restored."}),await this.recordEvent({summary:"Collection reconnected",message:"Connect credentials were renewed and the mirror checkpoint was preserved.",tone:"success"}),"connected"}catch(t){let n=Dt(t);return this.update({problem:n,message:n.action==="reauthorize"?"":n.message}),n.action==="reauthorize"?"reauthorize":"failed"}})??"failed"}async reauthorize(e){let t=await this.controller.reauthorize(e);this.update({status:t,problem:null,message:"Approval restored. The mirror checkpoint was preserved."}),await this.recordEvent({summary:"Connect approval restored",message:"The existing mirror checkpoint and local files were preserved.",tone:"success"})}async disconnect(e,t){let n=await this.controller.disconnect(t),i=t?`${n.removed.length} unchanged synced ${n.removed.length===1?"file was":"files were"} removed. ${n.preserved.length} locally changed ${n.preserved.length===1?"file was":"files were"} preserved.`:"All local files were retained as an unsynced copy.";return this.reset(),this.update({message:`Disconnected from ${e.name}. ${i}`}),n}async configureSelectiveSync(e){await this.controller.configureSelectiveSync(e),this.update({preview:null,message:"Sync settings updated."})}async resolveConflict(e,t,n){let i=null;try{n&&(i=await this.controller.preserveConflictCopy(e.path??"")),this.update({preview:null});let s=await W$(this.controller,e.object_id,e.decision_id,t),o=i?`Local copy saved to ${i}. Sync to apply the hosted version.`:"Conflict resolved. Sync to continue.";return this.update({status:s.status,preview:s.preview,problem:null,message:o}),await this.recordEvent({summary:i?"Conflict kept as two files":`Conflict resolved with ${t==="local"?"local":"hosted"} version`,message:o,...e.path?{path:e.path}:{},tone:"info"}),!0}catch(s){let o=Dt(s);return i&&(o.message=`The local copy at ${i} is safe, but the original changed again. Review the newest versions before deciding.`),this.update({problem:o,message:o.message}),o.code==="conflict_decision_stale"&&(this.update({preview:null}),await this.refreshStatus()),await this.recordEvent({summary:o.title,message:o.message,...e.path?{path:e.path}:{},tone:"attention",needsAcknowledgement:!0}),!1}}reportProblem(e){let t=Dt(e);return this.update({problem:t,message:t.message}),t}async exclusive(e,t=!1){if(!this.current.busy){this.update({busy:!0,...t?{}:{message:""}});try{return await e()}finally{this.update({busy:!1})}}}async loadPreview(){let e=this.getProfile();if(!e)return null;try{let{preview:t,status:n}=await this.controller.inspect();return Td(e,this.getProfile())?(this.update({preview:t,status:n,problem:null}),t):null}catch(t){if(!Td(e,this.getProfile()))return null;let n=Dt(t);return this.update({problem:n,message:n.message}),null}}async applyReviewed(){let e=this.current.preview;if(!e)return"failed";let t=this.getProfile()?.collectionId,n=new Date().toISOString(),i=[],s="failed",o;try{let a=await this.controller.sync(e,h=>this.update({progress:h}),h=>this.update({fileProgress:h}),(h,m)=>{let y=Hx(h,m,new Date().toISOString());y&&i.push(y)});s=a.status,o=a.failure?.message;let{preview:c,status:l}=await this.controller.inspect(),u=a.status==="cancelled"?Dt(new DOMException("Synchronization stopped.","AbortError")):a.status==="failed"||a.status==="blocked"?F$(a.failure??{code:"sync_failed",message:"Synchronization stopped."}):null,d=a.status==="applied"?"Sync complete.":a.status==="attention"?a.applied>0?"Available changes synced. Remaining items need attention.":"No available changes. Resolve the listed items and review again.":a.status==="cancelled"?`Sync paused after ${a.applied} ${a.applied===1?"change":"changes"}. Resume to finish the rest.`:a.status==="stale"?"Files changed during sync; checking again.":u?.message??`Sync stopped: ${a.failure?.message??a.status}.`;this.update({status:l,preview:c.plan.actions.length||c.entries.length?c:null,problem:u,message:d,...a.status==="applied"&&a.pending===0?{localChangeObserved:!1}:{}});let f=u?`${u.kind}:${u.code}`:null,p=a.status==="stale"||u?.kind==="offline"||a.status==="attention"&&l.conflicts.length>0||f!==null&&f===this.pinnedFailure;return a.status==="applied"?this.pinnedFailure=null:f&&!p&&(this.pinnedFailure=f),!p&&(a.status!=="applied"||!i.length)&&await this.recordEvent({summary:a.status==="applied"?`Synchronized ${a.applied} ${a.applied===1?"change":"changes"}`:a.status==="cancelled"?"Synchronization paused safely":a.applied>0?"Synced available changes":"Synchronization needs attention",message:d,tone:a.status==="applied"?"success":"attention",needsAcknowledgement:a.status!=="applied"&&a.status!=="attention"},t),a.status==="blocked"?"failed":a.status}catch(a){let c=Dt(a);s=c.kind==="paused"?"cancelled":"failed",o=c.message,this.update({problem:c,message:c.message});let l=`${c.kind}:${c.code}`;return c.kind!=="offline"&&l!==this.pinnedFailure&&(this.pinnedFailure=l,await this.recordEvent({summary:c.title,message:c.message,tone:c.kind==="paused"?"attention":"error",needsAcknowledgement:c.kind!=="paused"},t)),c.kind==="paused"?"cancelled":"failed"}finally{if(this.update({progress:null,fileProgress:null}),t&&i.length&&this.history){try{await this.history.append({id:crypto.randomUUID(),collectionId:t,startedAt:n,finishedAt:new Date().toISOString(),outcome:s,files:i,...o?{message:o}:{}})}catch(a){console.error("mdbase: could not save sync history",a)}this.update({})}}}};function Td(r,e){return r?.collectionId===e?.collectionId&&r?.replicaId===e?.replicaId&&r?.enrollmentId===e?.enrollmentId}function uj(r){let e=r.path.split("/").pop()??r.path;switch(r.outcome){case"merged":return{summary:`Merged edits to ${e}`,message:"Changes made here and on another device were combined.",path:r.path,tone:"success"};case"kept_both":return{summary:`Kept both versions of ${e}`,message:`The same part was edited on two devices. The other device's version is in place and this device's version was saved as ${r.copyPath??"a copy"}.`,path:r.path,tone:"attention",needsAcknowledgement:!0};case"restored":return{summary:`Restored ${e}`,message:"It was deleted here but edited on another device, so the edited version was kept.",path:r.path,tone:"info"};case"kept_local":return{summary:`Kept ${e}`,message:"It was deleted on another device but edited here, so this version was uploaded again.",path:r.path,tone:"info"};case"took_hosted":return{summary:`Settled ${e}`,message:"The hosted version was kept.",path:r.path,tone:"info"};case"unresolved":return{summary:`Couldn't sync ${e}`,message:r.reason??"This change needs a decision.",path:r.path,tone:"attention",needsAcknowledgement:!0}}}var fj={localQuietMs:3e3,localMaxWaitMs:2e4,probeVisibleMs:3e4,probeHiddenMs:5*6e4,safetyNetMs:15*6e4,retryBaseMs:5e3,retryMaxMs:5*6e4,unexpectedRetryMaxMs:30*6e4},ay=new Set(["auth","device","paused"]),Od=class{constructor(e,t=pj,n=fj){this.host=e;this.clock=t;this.timing=n;this.timer=null;this.dueAt=null;this.dueIsDebounce=!1;this.firstLocalChangeAt=null;this.changed=!0;this.failures=0;this.running=!1;this.rerun=!1;this.visible=!0;this.stopped=!0;this.lastSyncAt=t.now()}start(){this.stopped=!1,this.schedule(this.clock.now())}stop(){this.stopped=!0,this.timer!==null&&this.clock.clearTimeout(this.timer),this.timer=null,this.dueAt=null}noteLocalChange(){let e=this.clock.now();(this.firstLocalChangeAt===null||e0&&(this.changed=!0),this.failures=0,this.host.setRetryAt(null),this.schedule(this.clock.now())}requestSoon(){this.changed=!0,this.schedule(this.clock.now())}async tick(){if(this.stopped)return;if(this.running){this.rerun=!0;return}this.running=!0,this.dueAt=null;let e=null;try{e=await this.decide()}catch(t){this.host.reportProblem(t);let n=this.host.problemKind();e=n&&ay.has(n)?this.settled():this.failed(ks(t))}finally{this.running=!1;let t=this.clock.now();this.rerun?(this.rerun=!1,this.schedule(t)):e!==null?this.schedule(t+e):this.schedule(t+(this.visible?this.timing.probeVisibleMs:this.timing.probeHiddenMs))}}async decide(){if(!this.host.connected())return null;let e=this.host.problemKind();if(e&&ay.has(e))return null;let t=this.clock.now(),n=this.changed;if(this.changed=!1,this.firstLocalChangeAt=null,!this.host.automatic())return(n||await this.probe()===!0)&&await this.host.refreshStatus(),null;let i=n||this.failures>0||t=this.timing.safetyNetMs;if(!i){let o=await this.probe();if(o===null)return this.failed(!0);i=o}if(!i)return null;this.lastSyncAt=t;let s=await this.host.autoSync();if(s==="busy"||s==="pending")return this.changed||=n||s==="pending",2e3;if(s==="failed"){this.changed||=n;let o=this.host.problemKind();return o&&ay.has(o)?this.settled():this.failed(o==="offline")}return this.settled()}async probe(){try{return await this.host.remoteChangesWaiting()}catch(e){return this.host.reportProblem(e),ks(e)?null:!0}}failed(e){let t=Cm(this.failures,{baseDelayMs:this.timing.retryBaseMs,maxDelayMs:e?this.timing.retryMaxMs:this.timing.unexpectedRetryMaxMs,random:()=>this.clock.random()});return this.failures+=1,this.host.setRetryAt(this.clock.now()+t),t}settled(){return this.failures=0,this.host.setRetryAt(null),null}schedule(e,t=!1){if(this.stopped)return;let n=this.timer===null?null:this.dueAt;n!==null&&n<=e&&!(t&&this.dueIsDebounce)||(this.timer!==null&&this.clock.clearTimeout(this.timer),this.dueAt=e,this.dueIsDebounce=t,this.timer=this.clock.setTimeout(()=>{this.timer=null,this.dueAt=null,this.tick()},Math.max(0,e-this.clock.now())))}},pj={now:()=>Date.now(),setTimeout:(r,e)=>window.setTimeout(r,e),clearTimeout:r=>window.clearTimeout(r),random:()=>Math.random()};function Y$(r){let{profile:e,state:t}=r,n=["mdbase sync diagnostics",`Generated: ${r.generatedAt}`,`Plugin ${r.pluginVersion} \xB7 Obsidian ${r.obsidianVersion} \xB7 ${r.platform}`,"","Connection"];e?n.push(` Collection: ${e.collectionId}`,` Replica: ${e.replicaId} (${e.mode})`,` Connect: ${J$(e.controlUrl)} \xB7 sync ${J$(e.syncUrl)}`,` Access token expires: ${e.accessTokenExpiresAt}`,` Enrolled on this device: ${r.otherDevice?"no \u2014 copied from another device or vault":"yes"}`,` File classes: ${e.selectiveSync?.file_classes.join(", ")||"notes only"}`,` Excluded folders: ${e.selectiveSync?.excluded_folders.length??0}`):n.push(" Not connected"),n.push(` Automatic sync: ${r.automatic?"on":"off"}${t.paused?" (paused)":""}`,` Other sync services on this vault: ${r.otherSyncServices.join(", ")||"none detected"}`,"","State",` Engine state: ${t.status?.state??"unknown"} \xB7 pending ${t.status?.pending??"?"} \xB7 conflicts ${t.status?.conflicts.length??0} \xB7 local issues ${t.status?.local_issues.length??0}`,` Last synced: ${t.status?.last_synced_at??"never"}`,` Problem: ${t.problem?`${t.problem.kind}/${t.problem.code} \u2014 ${t.problem.message}`:"none"}`,` Next automatic attempt: ${t.retryAt?new Date(t.retryAt).toISOString():"not scheduled"}`,` Plan on screen: ${t.preview?`${t.preview.plan.kind}, ${t.preview.plan.actions.length} actions, ${t.preview.plan.summary.blocking_issues} blocking issues`:"none"}`,` Checkpoint: ${r.checkpoint?`cursor ${r.checkpoint.cursor}, generation ${r.checkpoint.generation}`:"none"}`,` Interrupted batch: ${r.checkpoint?.batch??"none"}${r.checkpoint?.failure?` (${r.checkpoint.failure})`:""}`,"","Recent history (newest first)");let i=[...r.history].sort((s,o)=>o.finishedAt.localeCompare(s.finishedAt)).slice(0,25);i.length||n.push(" none");for(let s of i){let o=s.summary??`${s.files.length} ${s.files.length===1?"file":"files"}`;n.push(` ${s.finishedAt} \xB7 ${s.outcome}${s.tone?`/${s.tone}`:""} \xB7 ${o}${s.message?` \u2014 ${s.message}`:""}`)}return`${n.join(` `)} -`}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} +`}function J$(r){try{return new URL(r).host}catch{return"invalid URL"}}var X$={validateOnSave:!0,validateOnOpen:!0,showNoticeOnSave:!1,interopEnabled:!1,mirrorProfile:null,typeDrafts:{},archivedTypeDrafts:[],autoSync:!0,syncSettingsVersion:2},Q$="mdbase-sync-device-id";function hj(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Dd=class extends L.Plugin{constructor(t,n){super(t,n);this.issueMap=new Map;this.validation=new Ia;this.validationAbort=null;this.sortedIssuesCache=null;this.noteStatusVersion=0;this.syncScheduler=null;this.recordCache=null;this.recordCacheSettings="";this.recordList=null;this.recordLoadPromise=null;this.dirtyRecordPaths=new Set;this.schemaCache=null;this.schemaLoadPromise=null;this.saveValidationDebounceMs=2e3;this.schemaRefreshDebounceMs=2e3;this.saveValidations=new Pa(this.saveValidationDebounceMs,async(t,n)=>{try{await this.validateFileAndStore(t,"save",n)}catch(i){console.error("mdbase: background validation failed",i)}});this.schemaRefreshes=new Pa(this.schemaRefreshDebounceMs,async()=>{this.invalidateSchemaCache(),this.refreshWorkspaceViews()});this.connectSync=new pd(t,{getMirrorProfile:()=>this.getMirrorProfile(),saveMirrorProfile:async i=>{this.settings.mirrorProfile=i,await this.saveSettings(),i?this.requestSync():this.sync?.reset()},deviceId:()=>this.deviceId()}),this.interopBridge=new Hc(t,()=>this.settings?.interopEnabled===!0),this.api={apiVersion:1,interop:this.interopBridge,getInteropStatus:()=>({enabled:this.settings?.interopEnabled===!0,profileVersion:"0.1"})}}async onload(){await this.loadSettings(),await this.connectSync.initialize(),await this.createSyncSession(),(0,L.addIcon)($a,S$),this.statusBarEl=this.addStatusBarItem(),this.statusBarEl.addClass("mdbase-status-bar"),this.statusBarEl.setAttr("role","button"),this.statusBarEl.setAttr("tabindex","0"),this.registerDomEvent(this.statusBarEl,"click",()=>void this.openStatusDestination()),this.registerDomEvent(this.statusBarEl,"keydown",n=>{n.key!=="Enter"&&n.key!==" "||(n.preventDefault(),this.openStatusDestination())}),this.noteStatusEl=this.addStatusBarItem(),this.noteStatusEl.addClass("mdbase-note-status"),this.noteStatusEl.setAttr("role","button"),this.noteStatusEl.setAttr("tabindex","0"),this.noteStatusEl.hide(),this.registerDomEvent(this.noteStatusEl,"click",()=>void this.openNoteStatusDestination()),this.registerDomEvent(this.noteStatusEl,"keydown",n=>{n.key!=="Enter"&&n.key!==" "||(n.preventDefault(),this.openNoteStatusDestination())}),this.updateStatusBar(),this.registerView(Lr,n=>new Cd(n,this)),this.addSettingTab(new Rd(this.app,this)),this.ribbonEl=this.addRibbonIcon($a,"Open mdbase",()=>void this.onRibbonClick()),this.ribbonEl.addClass("mdbase-ribbon"),this.updateStatusBar(),vw(this),this.registerVaultEvents(),this.registerEvent(this.app.workspace.on("file-open",n=>{this.settings.validateOnOpen&&(!(n instanceof L.TFile)||n.extension!=="md"||this.validateFileAndStore(n,"open"))})),this.registerEvent(this.app.workspace.on("active-leaf-change",()=>void this.updateNoteStatus())),this.registerEvent(this.app.metadataCache.on("changed",n=>{n.path===this.app.workspace.getActiveFile()?.path&&this.updateNoteStatus()})),this.registerEvent(this.app.workspace.on("editor-change",(n,i)=>{let s=i.file;s instanceof L.TFile&&(this.saveValidations.has(s.path)&&this.scheduleSaveValidation(s),this.schemaRefreshes.has("schema")&&this.isSchemaRelevantPath(s.path)&&this.scheduleSchemaRefresh())}));try{await jd(this.app)}catch(n){new L.Notice(`Contract pack recovery needs attention: ${String(n)}`,0)}let t=this.app.workspace.getActiveFile();t&&this.settings.validateOnOpen&&this.validateFileAndStore(t,"open"),this.startSyncScheduler()}startSyncScheduler(){this.syncScheduler=new Od({connected:()=>this.getMirrorProfile()!==null,automatic:()=>this.settings.autoSync,problemKind:()=>this.sync.state.paused?"paused":this.sync.state.problem?.kind??null,autoSync:()=>this.sync.autoSync(),refreshStatus:()=>this.sync.refreshStatus(),remoteChangesWaiting:()=>this.connectSync.remoteChangesWaiting(),reportProblem:n=>{this.sync.reportProblem(n)},setRetryAt:n=>this.sync.setRetryAt(n)}),this.registerDomEvent(window,"online",()=>this.syncScheduler?.noteOnline()),this.registerDomEvent(window,"focus",()=>this.syncScheduler?.noteVisibility(!0));let t=window.document;this.registerDomEvent(t,"visibilitychange",()=>{this.syncScheduler?.noteVisibility(t.visibilityState==="visible")}),this.syncScheduler.start()}requestSync(){this.syncScheduler?.requestSoon()}deviceId(){let t=this.app.loadLocalStorage(Q$);if(typeof t=="string"&&t)return t;let n=crypto.randomUUID();return this.app.saveLocalStorage(Q$,n),n}onunload(){this.validationAbort?.abort(),this.syncScheduler?.stop(),this.connectSync.dispose(),this.interopBridge.dispose().catch(t=>{console.error("mdbase: failed to dispose the interoperability bridge",t)}),this.app.workspace.getLeavesOfType(Lr).forEach(t=>t.detach()),this.saveValidations.clear(),this.schemaRefreshes.clear()}async loadSettings(){let t=await this.loadData();this.settings=Object.assign({},X$,t);let n=typeof t?.syncSettingsVersion=="number"&&Number.isSafeInteger(t.syncSettingsVersion)&&t.syncSettingsVersion>=1?t.syncSettingsVersion:1;this.settings.syncSettingsVersion=Math.max(2,n),this.settings.autoSync=n<2||typeof t?.autoSync!="boolean"?X$.autoSync:t.autoSync,this.settings.mirrorProfile=o$(this.settings.mirrorProfile),(!this.settings.typeDrafts||typeof this.settings.typeDrafts!="object"||Array.isArray(this.settings.typeDrafts))&&(this.settings.typeDrafts={}),this.settings.archivedTypeDrafts=Array.isArray(this.settings.archivedTypeDrafts)?this.settings.archivedTypeDrafts:[]}async saveSettings(){await this.saveData(this.settings)}getIssues(){return this.sortedIssuesCache??=Array.from(this.issueMap.values()).flat().sort((t,n)=>t.path.localeCompare(n.path)||t.severity.localeCompare(n.severity)||t.code.localeCompare(n.code)),this.sortedIssuesCache}getMirrorProfile(){return this.settings.mirrorProfile?JSON.parse(JSON.stringify(this.settings.mirrorProfile)):null}otherSyncServices(){let t=[],n=this.app,i=n.internalPlugins?.getEnabledPluginById?.("sync");typeof i?.vaultId=="string"&&i.vaultId&&t.push("Obsidian Sync");let s={"obsidian-livesync":"Self-hosted LiveSync","remotely-save":"Remotely Save","obsidian-git":"Obsidian Git"};for(let[l,u]of Object.entries(s))n.plugins?.enabledPlugins?.has(l)&&t.push(u);let o=this.app.vault.adapter,a=typeof L.FileSystemAdapter=="function"&&o instanceof L.FileSystemAdapter?o.getBasePath():"",c=[[/Mobile Documents|iCloud/i,"iCloud Drive"],[/[\\/]Dropbox[\\/]/i,"Dropbox"],[/[\\/]OneDrive/i,"OneDrive"],[/Google ?Drive|GoogleDrive/i,"Google Drive"]];for(let[l,u]of c)l.test(a)&&t.push(u);return t}async copySyncDiagnostics(){let t=this.getMirrorProfile(),n=null;try{n=await this.connectSync.checkpointSummary()}catch(s){console.error("mdbase: could not read the sync checkpoint for diagnostics",s)}let i=Y$({generatedAt:new Date().toISOString(),pluginVersion:this.manifest.version,obsidianVersion:L.apiVersion,platform:L.Platform.isIosApp?"iOS":L.Platform.isAndroidApp?"Android":L.Platform.isMacOS?"macOS":L.Platform.isWin?"Windows":L.Platform.isLinux?"Linux":"unknown",profile:t,otherDevice:this.connectSync.isOtherDevice(t),automatic:this.settings.autoSync,otherSyncServices:this.otherSyncServices(),state:this.sync.state,checkpoint:n,history:this.sync.historyRuns()});await navigator.clipboard.writeText(i),new L.Notice("Copied sync diagnostics. They name the collection and recent files but contain no note text or credentials.")}openNoteSyncHistory(t){new Md(this.app,t,this.sync.historyRuns()).open()}openSettings(){let t=this.app.setting;t?.open(),t?.openTabById(this.manifest.id)}async createSyncSession(){let t=this.manifest.dir??`${this.app.vault.configDir}/plugins/${this.manifest.id}`,n=new ld(this.app.vault.adapter,(0,L.normalizePath)(`${t}/sync-history.jsonl`));try{await n.load(),await this.migrateSyncActivity(n)}catch(i){console.error("mdbase: could not load sync history",i)}this.sync=new Id(this.connectSync,()=>this.getMirrorProfile(),n,i=>{new L.Notice(`mdbase: ${i}`,1e4)}),this.register(this.sync.subscribe(()=>this.updateStatusBar()))}async migrateSyncActivity(t){let n=j$(this.settings.syncActivity),i=this.settings.mirrorProfile?.collectionId;if(i)for(let s of n)await t.append(dd(i,{summary:s.summary,tone:s.tone,...s.detail?{message:s.detail}:{},...s.path?{path:s.path}:{},...s.requiresAcknowledgement?{needsAcknowledgement:!0}:{}},s.occurredAt));this.settings.syncActivity!==void 0&&(delete this.settings.syncActivity,await this.saveSettings())}async loadWorkspaceSchema(t=!1){return this.getConfigAndTypes(t)}async loadTypeModel(t){let n=this.app.vault.getAbstractFileByPath((0,L.normalizePath)(t));if(!(n instanceof L.TFile))throw new Error(`Type file not found: ${t}`);let i=await this.app.vault.cachedRead(n),s=Me(i);if(!s.hasFrontmatter||s.error)throw new Error(`Invalid type frontmatter: ${s.error??"frontmatter is missing"}`);let o=bd(s.frontmatter,s.body,n.basename);return o.sourceRevision=Xm(i),o}loadTypeDraft(t){let n=this.settings.typeDrafts[t??"__new__"];return n?JSON.parse(JSON.stringify(n)):null}async saveTypeDraft(t){let n=this.loadTypeDraft(t.path);n&&n.sourceRevision!==t.sourceRevision&&this.settings.archivedTypeDrafts.push(n),this.settings.typeDrafts[t.path??"__new__"]=JSON.parse(JSON.stringify(t)),await this.saveSettings()}getArchivedTypeDrafts(t){return this.settings.archivedTypeDrafts.filter(n=>n.path===t)}async discardArchivedTypeDraft(t){this.settings.archivedTypeDrafts=this.settings.archivedTypeDrafts.filter(n=>n.path!==t.path||n.updatedAt!==t.updatedAt||n.sourceRevision!==t.sourceRevision),await this.saveSettings()}async clearTypeDraft(t){let n=t??"__new__";n in this.settings.typeDrafts&&(delete this.settings.typeDrafts[n],await this.saveSettings())}async saveTypeModel(t,n,i){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access. Re-enroll it with write access before editing types.");let s=await ci(this.app.vault);if(!s)throw new Error("No mdbase.yaml found.");if(!s.spec_version.startsWith("0.3."))throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let o=n?this.app.vault.getAbstractFileByPath((0,L.normalizePath)(n)):null;if(o!=null&&!(o instanceof L.TFile))throw new Error(`Type file not found: ${n}`);let a=await this.writeTypeDefinition(s,t,o,i);return this.refreshWorkspaceViews(!0),a}getValidationSummary(){let t=this.schemaCache?.config,n=this.app.vault.getMarkdownFiles().filter(i=>!t||!bt(i.path,t)).map(i=>i.path);return this.validation.summary(n)}isValidating(){return this.validationAbort!==null}cancelValidation(){this.validationAbort?.abort()}async openContractCatalog(){if(this.getMirrorProfile())throw new Error("Install packs at the hosted collection authority using mdbase editor.");let t=await this.getConfigAndTypes();if(!t||!t.config.spec_version.startsWith("0.3."))throw new Error("Initialize or migrate this collection first.");if(t.config.settings.types_folder!=="_types"||(t.config.settings.contracts_folder??"_contracts")!=="_contracts")throw new Error("Catalog packs require the standard _types and _contracts folders. Use mdbase editor for custom target mappings.");new Ta(this.app,()=>{if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile())throw new Error("The vault role changed. Install at the collection authority instead.")},async n=>{this.invalidateSchemaCache();let i=await this.openWorkspace("types");await i.refresh(!0);let s=await this.getConfigAndTypes(),o=n?s?.types.get(n):null;o&&await i.editType(o.filePath),new L.Notice("Installed contract pack. Edit its type or create a note to try it.")}).open()}async createNoteFromType(t){await Bp(this,t)}async initializeCollection(){this.connectSync.assertLocalAuthorityWritable();let{created:t}=await xo(this.app.vault,{seedNoteType:!1});this.invalidateSchemaCache(),new L.Notice(t.length?`Initialized mdbase collection: ${t.join(", ")}`:"mdbase collection already initialized."),this.refreshWorkspaceViews(!0)}async validateCollection(){await this.runCollectionValidation(!1)}analyzeMigration(){if(this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");return u$(this.app.vault)}async applyMigration(t,n){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");let i=await f$(this.app.vault,t,{allowLossy:n});if(!i.applied)throw new Error(i.restored?`Migration failed and all writes were rolled back. ${i.error??""}`.trim():`Migration needs manual recovery. See ${i.manifestPath}. ${i.error??""}`.trim());this.invalidateSchemaCache(),new L.Notice(`Migrated to mdbase v0.3. Recovery manifest: ${i.manifestPath}`),this.refreshWorkspaceViews(!0)}async openIssue(t){await this.openFileByPath(t.path,t.field)}getQuickFixLabel(t){return Sw(t)}async applyQuickFix(t){this.connectSync.assertLocalAuthorityWritable();let n=this.app.vault.getAbstractFileByPath(t.path);if(!(n instanceof L.TFile)){new L.Notice(`File not found: ${t.path}`);return}if(this.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access.");let i=!1;await this.app.vault.process(n,s=>{this.connectSync.assertLocalAuthorityWritable();let o=Up(s,t);return i=o.changed,o.content}),new L.Notice(i?`Updated '${t.field??"field"}' in ${n.basename}`:"The field changed or no safe quick fix is available. Revalidate the note."),await this.validateFileAndStore(n,"manual")}async applyQuickFixes(t){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access.");let n=0,i=0,s=new Map;for(let o of t){let a=this.app.vault.getAbstractFileByPath(o.path);if(!(a instanceof L.TFile)){i+=1;continue}let c=!1;await this.app.vault.process(a,l=>{this.connectSync.assertLocalAuthorityWritable();let u=Up(l,o);return c=u.changed,u.content}),c?(n+=1,s.set(a.path,a)):i+=1}for(let o of s.values())await this.validateFileAndStore(o,"manual");return{changed:n,skipped:i}}async openFileByPath(t,n){let i=this.app.vault.getAbstractFileByPath(t);if(!(i instanceof L.TFile)){new L.Notice(`File not found: ${t}`);return}await this.app.workspace.getLeaf(!0).openFile(i),n&&this.revealFrontmatterField(i,n)}revealFrontmatterField(t,n){let i=this.app.workspace.getMostRecentLeaf();if(!i||!(i.view instanceof L.MarkdownView))return;let s=i.view;if(!(s.file instanceof L.TFile)||s.file.path!==t.path)return;let o=s.editor,a=o.lineCount();if(a<3)return;let c=Fp(n),l=new RegExp(`^\\s*${hj(c)}\\s*:`);if(o.getLine(0).trim()==="---")for(let u=1;ud.severity==="error").length,c=this.validation.isChecked(n.path),l=c?o.length?` \xB7 ${o.length} ${o.length===1?"issue":"issues"}`:" \xB7 checked":" \xB7 not checked";this.noteStatusEl.setText(`${s.join(", ")}${l}`),this.noteStatusEl.setAttr("data-state",c?a?"error":o.length?"warning":"valid":"unchecked"),this.noteStatusEl.setAttr("data-path",n.path);let u=o.length?`${n.basename}: ${o.length} ${o.length===1?"issue":"issues"}. Open issues for this note.`:`${n.basename} is a ${s.join(", ")} note. Edit the type.`;this.noteStatusEl.setAttr("aria-label",u),this.noteStatusEl.setAttr("title",u),this.noteStatusEl.show()}async openNoteStatusDestination(){let t=this.noteStatusEl.getAttr("data-path");if(!t)return;if(this.issueMap.get(t)?.length){(await this.openWorkspace("issues")).showIssuesForPath(t);return}let n=this.app.vault.getAbstractFileByPath(t),i=await this.getConfigAndTypes();if(!(n instanceof L.TFile)||!i)return;let[s]=Ge(t,this.app.metadataCache.getFileCache(n)?.frontmatter??{},i.config,i.types),o=s?i.types.get(s):void 0;if(!o)return;await(await this.openWorkspace("types")).editType(o.filePath)}markRecordChanged(t){this.validation.changed(t),this.recordCache&&(this.dirtyRecordPaths.add((0,L.normalizePath)(t)),this.recordList=null)}loadCollectionRecords(){return this.recordLoadPromise??=this.readRecords().finally(()=>{this.recordLoadPromise=null}),this.recordLoadPromise}async readRecords(){let t=await this.getConfigAndTypes();if(!t)return[];let n=JSON.stringify(t.config.settings);if(!this.recordCache||n!==this.recordCacheSettings){this.dirtyRecordPaths.clear();let i=await Pp(this.app.vault,t.config);this.recordCache=new Map(i.map(s=>[s.path,s])),this.recordCacheSettings=n,this.recordList=null}else if(this.dirtyRecordPaths.size){let i=[...this.dirtyRecordPaths];this.dirtyRecordPaths.clear();for(let s of i){this.recordCache.delete(s);let o=this.app.vault.getAbstractFileByPath(s);if(!(o instanceof L.TFile)||o.extension!=="md"||bt(s,t.config))continue;let a=Me(await this.app.vault.cachedRead(o));a.error||this.recordCache.set(s,{path:s,frontmatter:a.frontmatter})}this.recordList=null}return this.recordList??=[...this.recordCache.values()].sort((i,s)=>i.path.localeCompare(s.path)),this.recordList}syncIndicator(t){let n=this.sync.state,i=this.sync.safety();return L$({connected:this.getMirrorProfile()!==null,status:n.status,progress:n.progress,fileProgress:n.fileProgress,problem:n.problem,validationIssues:t,localChangeObserved:n.localChangeObserved,paused:n.paused,reviewChanges:i&&!i.safe?n.preview?.plan.actions.length??0:0})}async openStatusDestination(){await this.openWorkspace(this.syncIndicator(this.getIssues().length).destination)}async openIssuesView(){await this.openWorkspace("issues")}async openWorkspace(t="types"){let n=this.app.workspace.getLeavesOfType(Lr)[0];if(n){await this.app.workspace.revealLeaf(n);let s=n.view;return s.showDestination(t),await s.refresh(),s}let i=this.app.workspace.getLeaf(!0);return await i.setViewState({type:Lr,active:!0,state:{destination:t}}),await this.app.workspace.revealLeaf(i),i.view}refreshWorkspaceViews(t=!1){for(let n of this.app.workspace.getLeavesOfType(Lr)){let i=n.view;typeof i.refresh=="function"&&i.refresh(t)}}refreshIssueViews(){this.updateStatusBar(),this.refreshWorkspaceViews()}setFileIssues(t,n){n.length===0?this.issueMap.delete(t):this.issueMap.set(t,n),this.sortedIssuesCache=null,this.refreshIssueViews()}clearFileIssues(t){this.issueMap.has(t)&&(this.issueMap.delete(t),this.sortedIssuesCache=null,this.refreshIssueViews())}moveFileIssues(t,n){let i=this.issueMap.get(t);i&&(this.issueMap.delete(t),this.issueMap.set(n,i.map(s=>({...s,path:n}))),this.sortedIssuesCache=null,this.refreshIssueViews())}clearPendingSaveValidation(t){this.saveValidations.cancel(t)}scheduleSaveValidation(t){this.saveValidations.schedule(t.path,t)}scheduleSchemaRefresh(){this.schemaRefreshes.schedule("schema",void 0)}refreshSchemaNow(){this.schemaRefreshes.cancel("schema"),this.invalidateSchemaCache(),this.refreshWorkspaceViews()}isSchemaRelevantPath(t){let n=(0,L.normalizePath)(t);if(n==="mdbase.yaml")return!0;let i=new Set(["_types","_contracts"]);this.schemaCache&&(i.add((0,L.normalizePath)(this.schemaCache.config.settings.types_folder)),i.add((0,L.normalizePath)(this.schemaCache.config.settings.contracts_folder??"_contracts")));for(let s of i)if(n===s||n.startsWith(`${s}/`))return!0;return!1}invalidateSchemaCache(){this.validation.changed(),this.schemaCache=null,this.schemaLoadPromise=null}async getConfigAndTypes(t=!1){if(t&&this.invalidateSchemaCache(),this.schemaCache)return this.schemaCache;if(this.schemaLoadPromise)return this.schemaLoadPromise;this.schemaLoadPromise=(async()=>{let n=await ci(this.app.vault);if(!n)return null;let i=await Cp(this.app.vault,n),s=await Mp(this.app.vault,n);return{config:n,types:i,contracts:s}})();try{let n=await this.schemaLoadPromise;return n&&(this.schemaCache=n),n}finally{this.schemaLoadPromise=null}}async requireConfigAndTypes(t={}){let n=t.background??!1,i=await this.getConfigAndTypes(t.forceReload??!1);return i?(i.types.size===0&&!n&&new L.Notice(`No types found in ${i.config.settings.types_folder}`),i):(n||new L.Notice("No mdbase.yaml found. Run 'mdbase: Initialize collection' first."),null)}registerVaultEvents(){this.registerEvent(this.app.vault.on("modify",t=>{t instanceof L.TFile&&this.onVaultModify(t)})),this.registerEvent(this.app.vault.on("rename",(t,n)=>{t instanceof L.TFile?this.onVaultRename(t,n):t instanceof L.TFolder&&this.onVaultFolderChange(n,t.path)})),this.registerEvent(this.app.vault.on("delete",t=>{t instanceof L.TFile?this.onVaultDelete(t):t instanceof L.TFolder&&this.onVaultFolderChange(t.path)})),this.registerEvent(this.app.vault.on("create",t=>{t instanceof L.TFile&&this.onVaultCreate(t)}))}onVaultFolderChange(...t){for(let n of t)this.observeLocalMirrorChange(n);this.recordCache=null,this.recordList=null,this.dirtyRecordPaths.clear(),this.refreshSchemaNow()}onVaultModify(t){this.observeLocalMirrorChange(t.path),this.markRecordChanged(t.path),this.isSchemaRelevantPath(t.path)&&this.scheduleSchemaRefresh(),this.settings.validateOnSave&&t.extension==="md"&&this.scheduleSaveValidation(t)}onVaultRename(t,n){this.observeLocalMirrorChange(n),this.markRecordChanged(n),this.markRecordChanged(t.path),this.observeLocalMirrorChange(t.path),(this.isSchemaRelevantPath(n)||this.isSchemaRelevantPath(t.path))&&this.refreshSchemaNow(),t.extension==="md"&&(this.clearPendingSaveValidation(n),this.moveFileIssues(n,t.path),this.settings.validateOnSave&&this.scheduleSaveValidation(t))}onVaultDelete(t){this.observeLocalMirrorChange(t.path),this.markRecordChanged(t.path),this.isSchemaRelevantPath(t.path)&&this.refreshSchemaNow(),t.extension==="md"&&(this.clearPendingSaveValidation(t.path),this.clearFileIssues(t.path))}onVaultCreate(t){this.observeLocalMirrorChange(t.path),this.markRecordChanged(t.path),this.isSchemaRelevantPath(t.path)&&this.refreshSchemaNow()}observeLocalMirrorChange(t){if(!this.getMirrorProfile()||this.connectSync.consumeEngineWrite(t))return;let n=(0,L.normalizePath)(t);[this.app.vault.configDir,".mdbase",".trash",".git"].some(s=>n===s||n.startsWith(`${s}/`))||(this.sync.observeLocalChange(),this.syncScheduler?.noteLocalChange())}async validateFileAndStore(t,n,i=()=>!0){let s=await this.requireConfigAndTypes({background:n!=="manual"});if(!i())return[];if(!s)return n!=="manual"&&this.clearFileIssues(t.path),[];let o=this.validation.revision,a=await Sc(this.app.vault,t,s.config,s.types);return!i()||o!==this.validation.revision||(this.validation.markChecked(t.path),this.setFileIssues(t.path,a),n==="save"&&this.settings.showNoticeOnSave&&a.length>0&&new L.Notice(`mdbase: ${a.length} issue${a.length===1?"":"s"} in ${t.basename}`)),a}async runCollectionValidation(t){if(this.validationAbort)return;let n=await this.requireConfigAndTypes({background:!1});if(!n||this.validationAbort)return;let i=new AbortController;this.validationAbort=i,this.validation.cancelled=!1;let s=this.validation.revision,o=new Map;try{let a=await Ip(this.app.vault,n.config,n.types,{signal:i.signal,onProgress:c=>{if(this.validation.progress=c,c.completed===0)for(let l of this.app.workspace.getLeavesOfType(Lr))l.view.refreshValidationControls();else if(c.completed%25===0||c.phase==="uniqueness")for(let l of this.app.workspace.getLeavesOfType(Lr))l.view.updateValidationProgress()},onFile:(c,l)=>{s===this.validation.revision&&(this.validation.markChecked(c.path),o.set(c.path,l),l.length?this.issueMap.set(c.path,l):this.issueMap.delete(c.path),this.sortedIssuesCache=null)}});if(s!==this.validation.revision){new L.Notice("Files changed during validation. Validate again for a complete result.");return}o.clear();for(let c of a)o.set(c.path,[...o.get(c.path)??[],c]);this.issueMap=o,this.validation.lastCompletedAt=new Date().toISOString(),this.validation.completedRevision=s,t&&(new L.Notice(a.length?`Collection validation: ${a.length} issues`:"Collection validation passed with no issues."),a.length&&await this.openIssuesView())}catch(a){if(this.validation.cancelled=!0,s===this.validation.revision)for(let[c,l]of o)l.length?this.issueMap.set(c,l):this.issueMap.delete(c);new L.Notice(i.signal.aborted?"Validation stopped. Results are incomplete.":`Validation could not finish: ${String(a)}. Results are incomplete.`)}finally{this.validation.progress=null,this.validationAbort=null,this.sortedIssuesCache=null;for(let a of this.app.workspace.getLeavesOfType(Lr))a.view.refreshValidationControls();this.refreshIssueViews()}}async ensureFolderExists(t){let n=(0,L.normalizePath)(t).replace(/\/+$/,"");if(!n)return;let i=n.split("/"),s="";for(let o of i)s=s?`${s}/${o}`:o,await this.app.vault.adapter.exists(s)||await this.app.vault.createFolder(s)}async writeTypeDefinition(t,n,i,s){let o=n.name.trim();if(!o)throw new Error("Type name is required.");if(!t.spec_version.startsWith("0.3.")||n.specProfile!=="v0.3")throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let a=jn(n),c=n.body.trim()||`# ${o} -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&&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}}}; +Type definition for ${o}.`,l=`${gt(a,c)} +`,u=(0,L.normalizePath)(t.settings.types_folder),d=(0,L.normalizePath)(`${u}/${o}.md`);if(!i){if(await this.ensureFolderExists(u),await this.app.vault.adapter.exists(d))throw new Error(`Type already exists: ${d}`);let v=await this.app.vault.create(d,l);return this.invalidateSchemaCache(),v}let f=i.path,p=await this.app.vault.cachedRead(i);if(s&&Xm(p)!==s)throw new Error(`The source changed after this draft was opened: ${f}. Reopen the type and review both versions before saving.`);let h=i.path.lastIndexOf("/"),m=h>=0?i.path.slice(0,h):"",g=(0,L.normalizePath)(`${m?`${m}/`:""}${o}.md`)||d;if(g!==i.path&&await this.app.vault.adapter.exists(g))throw new Error(`Cannot rename type file to ${g}; file already exists.`);let b=!1;try{g!==i.path&&(await this.app.fileManager.renameFile(i,g),b=!0);let v=this.app.vault.getAbstractFileByPath(g);if(!(v instanceof L.TFile))throw new Error(`Unable to access updated type file: ${g}`);return await this.app.vault.modify(v,l),this.invalidateSchemaCache(),v}catch(v){try{let S=this.app.vault.getAbstractFileByPath(b?g:f);S instanceof L.TFile&&(await this.app.vault.modify(S,p),b&&await this.app.fileManager.renameFile(S,f))}catch(S){throw new Error(`Saving the type failed and automatic recovery also failed. Review '${f}' and '${g}'. ${v instanceof Error?v.message:String(v)}; recovery: ${S instanceof Error?S.message:String(S)}`)}throw v}}}; diff --git a/main.ts b/main.ts index 98cb880..d5f4429 100644 --- a/main.ts +++ b/main.ts @@ -12,6 +12,7 @@ import { Platform, Plugin, TFile, + TFolder, normalizePath, } from "obsidian"; import { ObsidianInteropBridge, type MdbaseObsidianInteropApi } from "./src/interopBridge"; @@ -121,6 +122,7 @@ export default class MdbasePlugin extends Plugin { private validationAbort: AbortController | null = null; private sortedIssuesCache: MdbaseIssue[] | null = null; private statusBarEl: HTMLElement | undefined; + private ribbonEl: HTMLElement | undefined; private noteStatusEl: HTMLElement; private noteStatusVersion = 0; sync: SyncSession; @@ -210,37 +212,13 @@ export default class MdbasePlugin extends Plugin { this.registerView(MDBASE_WORKSPACE_VIEW, (leaf) => new MdbaseWorkspaceView(leaf, this)); this.addSettingTab(new MdbaseSettingTab(this.app, this)); - this.addRibbonIcon(MDBASE_ICON_ID, "Open mdbase", () => void this.openWorkspace()); + this.ribbonEl = this.addRibbonIcon(MDBASE_ICON_ID, "Open mdbase", () => void this.onRibbonClick()); + this.ribbonEl.addClass("mdbase-ribbon"); + this.updateStatusBar(); registerCommands(this); - this.registerEvent( - this.app.vault.on("modify", (file) => { - if (!(file instanceof TFile)) return; - this.onVaultModify(file); - }), - ); - - this.registerEvent( - this.app.vault.on("rename", (file, oldPath) => { - if (!(file instanceof TFile)) return; - this.onVaultRename(file, oldPath); - }), - ); - - this.registerEvent( - this.app.vault.on("delete", (file) => { - if (!(file instanceof TFile)) return; - this.onVaultDelete(file); - }), - ); - - this.registerEvent( - this.app.vault.on("create", (file) => { - if (!(file instanceof TFile)) return; - this.onVaultCreate(file); - }), - ); + this.registerVaultEvents(); this.registerEvent( this.app.workspace.on("file-open", (file) => { @@ -284,7 +262,7 @@ export default class MdbasePlugin extends Plugin { this.syncScheduler = new SyncScheduler({ connected: () => this.getMirrorProfile() !== null, automatic: () => this.settings.autoSync, - problemKind: () => this.sync.state.problem?.kind ?? (this.sync.state.paused ? "paused" : null), + problemKind: () => this.sync.state.paused ? "paused" : this.sync.state.problem?.kind ?? null, autoSync: () => this.sync.autoSync(), refreshStatus: () => this.sync.refreshStatus(), remoteChangesWaiting: () => this.connectSync.remoteChangesWaiting(), @@ -334,10 +312,12 @@ export default class MdbasePlugin extends Plugin { this.settings = Object.assign({}, DEFAULT_SETTINGS, stored); // Before version 2 automatic sync was off by default and stopped for most // plans, so a stored `false` is almost always the old default, not a choice. - if (stored && (stored.syncSettingsVersion ?? 1) < 2) { - this.settings.autoSync = true; - this.settings.syncSettingsVersion = 2; - } + const version = typeof stored?.syncSettingsVersion === "number" + && Number.isSafeInteger(stored.syncSettingsVersion) && stored.syncSettingsVersion >= 1 + ? stored.syncSettingsVersion : 1; + this.settings.syncSettingsVersion = Math.max(2, version); + this.settings.autoSync = version < 2 || typeof stored?.autoSync !== "boolean" + ? DEFAULT_SETTINGS.autoSync : stored.autoSync; this.settings.mirrorProfile = normalizeMirrorProfile(this.settings.mirrorProfile); if (!this.settings.typeDrafts || typeof this.settings.typeDrafts !== "object" || Array.isArray(this.settings.typeDrafts)) { this.settings.typeDrafts = {}; @@ -714,16 +694,31 @@ export default class MdbasePlugin extends Plugin { } } + private async onRibbonClick(): Promise { + const indicator = this.syncIndicator(this.getIssues().length); + // Mobile has no status bar. Its ribbon is the direct way to inspect pending + // sync; a settled/local collection keeps Types as the primary destination. + if (Platform.isMobile && !["local", "synced"].includes(indicator.state)) await this.openStatusDestination(); + else await this.openWorkspace(); + } + private updateStatusBar(): void { - // The sync session can report before onload has created the status bar. - if (!this.statusBarEl) return; - const issues = this.getIssues(); - const indicator = this.syncIndicator(issues.length); - this.statusBarEl.setText(indicator.label); - this.statusBarEl.setAttr("aria-label", `${indicator.detail}. Open mdbase ${indicator.destination}.`); - this.statusBarEl.setAttr("title", indicator.detail); - this.statusBarEl.setAttr("data-state", indicator.state); - void this.updateNoteStatus(); + // The sync session can report before onload has created either indicator. + if (!this.statusBarEl && !this.ribbonEl) return; + const indicator = this.syncIndicator(this.getIssues().length); + if (this.statusBarEl) { + this.statusBarEl.setText(indicator.label); + this.statusBarEl.setAttr("aria-label", `${indicator.detail}. Open mdbase ${indicator.destination}.`); + this.statusBarEl.setAttr("title", indicator.detail); + this.statusBarEl.setAttr("data-state", indicator.state); + } + if (this.ribbonEl) { + const destination = Platform.isMobile && !["local", "synced"].includes(indicator.state) ? indicator.destination : "types"; + this.ribbonEl.setAttr("aria-label", `${indicator.label}. Open mdbase ${destination}.`); + this.ribbonEl.setAttr("title", indicator.detail); + this.ribbonEl.setAttr("data-state", indicator.state); + } + if (this.noteStatusEl) void this.updateNoteStatus(); } /** Type and issue count for the active note, beside the collection status. */ @@ -828,6 +823,7 @@ export default class MdbasePlugin extends Plugin { problem: state.problem, validationIssues, localChangeObserved: state.localChangeObserved, + paused: state.paused, reviewChanges: safety && !safety.safe ? state.preview?.plan.actions.length ?? 0 : 0, }); } @@ -850,12 +846,9 @@ export default class MdbasePlugin extends Plugin { return view; } const leaf = this.app.workspace.getLeaf(true); - await leaf.setViewState({ type: MDBASE_WORKSPACE_VIEW, active: true }); + await leaf.setViewState({ type: MDBASE_WORKSPACE_VIEW, active: true, state: { destination } }); await this.app.workspace.revealLeaf(leaf); - const view = leaf.view as MdbaseWorkspaceView; - await view.refresh(); - view.showDestination(destination); - return view; + return leaf.view as MdbaseWorkspaceView; } private refreshWorkspaceViews(forceReload = false): void { @@ -988,6 +981,33 @@ export default class MdbasePlugin extends Plugin { return loaded; } + private registerVaultEvents(): void { + this.registerEvent(this.app.vault.on("modify", (file) => { + if (file instanceof TFile) this.onVaultModify(file); + })); + this.registerEvent(this.app.vault.on("rename", (file, oldPath) => { + if (file instanceof TFile) this.onVaultRename(file, oldPath); + else if (file instanceof TFolder) this.onVaultFolderChange(oldPath, file.path); + })); + this.registerEvent(this.app.vault.on("delete", (file) => { + if (file instanceof TFile) this.onVaultDelete(file); + else if (file instanceof TFolder) this.onVaultFolderChange(file.path); + })); + this.registerEvent(this.app.vault.on("create", (file) => { + if (file instanceof TFile) this.onVaultCreate(file); + })); + } + + private onVaultFolderChange(...paths: string[]): void { + for (const path of paths) this.observeLocalMirrorChange(path); + // A folder event need not be accompanied by child-file events. The old + // descendant paths are no longer a valid incremental record/schema cache. + this.recordCache = null; + this.recordList = null; + this.dirtyRecordPaths.clear(); + this.refreshSchemaNow(); + } + private onVaultModify(file: TFile): void { this.observeLocalMirrorChange(file.path); this.markRecordChanged(file.path); 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 5ba24d6..7838e82 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 @@ -23,7 +23,7 @@ index dd5830c..868ba93 100644 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..ba68459 100644 +index a9018ff..647646c 100644 --- a/node_modules/@mdbase-dev/connect-sync/dist/directory-mirror.js +++ b/node_modules/@mdbase-dev/connect-sync/dist/directory-mirror.js @@ -8,6 +8,7 @@ import { checkpointMirrorStatus, mirrorStatusFromPlan } from "./mirror-status.js @@ -175,8 +175,53 @@ index a9018ff..ba68459 100644 : {}) }); return; +@@ -330,8 +358,15 @@ export class DirectoryMirror { + const path = conflict?.local.state === "exact" + ? conflict.local.object.path + : state.records[identity]?.path; +- if (path && await this.fileSystem.read(path) !== null) +- await this.fileSystem.remove(path); ++ if (path) { ++ const expected = await this.fileSystem.read(path); ++ if (expected !== null) { ++ if (conflict?.local.state !== "exact" ++ || runtimeDocumentRevision(expected, this.runtime) !== conflict.local.object.payload_revision) ++ throw staleConflict(); ++ await this.fileSystem.remove(path, expected); ++ } ++ } + delete state.records[identity]; + } + async installRemoteFile(state, identity, current) { +@@ -349,15 +384,23 @@ export class DirectoryMirror { + const localPath = state.local_bindings?.[identity]?.path; + await this.materializer.putFile(state, current, state, acceptedLocal); + if (localPath && localPath !== current.path) +- await this.fileSystem.remove(localPath); ++ await this.fileSystem.remove(localPath, acceptedLocal ?? null); + return; + } + const conflict = state.planned_conflicts?.[identity]; + const path = conflict?.local.state === "exact" + ? conflict.local.object.path + : state.files?.[identity]?.file.path; +- if (path && await this.fileSystem.inspectBinary(path) !== null) +- await this.fileSystem.remove(path); ++ if (path) { ++ const expected = await this.fileSystem.inspectBinary(path); ++ if (expected !== null) { ++ if (conflict?.local.state !== "exact" ++ || expected.content_digest !== conflict.local.object.payload_revision ++ || (conflict.local.object.size !== undefined && expected.size !== conflict.local.object.size)) ++ throw staleConflict(); ++ await this.fileSystem.remove(path, expected); ++ } ++ } + delete state.files?.[identity]; + } + async readState() { 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 +index 6936f79..491236e 100644 --- a/node_modules/@mdbase-dev/connect-sync/dist/mirror-materializer.js +++ b/node_modules/@mdbase-dev/connect-sync/dist/mirror-materializer.js @@ -28,12 +28,16 @@ export class MirrorMaterializer { @@ -209,6 +254,37 @@ index 6936f79..64b0670 100644 } state.records[record.record_id] = { path: record.path, +@@ -104,10 +108,10 @@ export class MirrorMaterializer { + } + } + if (!sameBinaryInfo(target, file)) { +- await this.fileSystem.writeBinary(file.path, verifiedFileBytes(this.blobStore.read(file.content_digest), file)); ++ await this.fileSystem.writeBinary(file.path, verifiedFileBytes(this.blobStore.read(file.content_digest), file), target); + } + if (prior && prior.file.path !== file.path) { +- await this.fileSystem.remove(prior.file.path); ++ await this.fileSystem.remove(prior.file.path, prior.file); + } + state.files[file.file_id] = { file }; + } +@@ -120,7 +124,7 @@ export class MirrorMaterializer { + throw new MirrorDivergenceError(fileId, entry.file.path); + } + if (local !== null) +- await this.fileSystem.remove(entry.file.path); ++ await this.fileSystem.remove(entry.file.path, local); + delete state.files[fileId]; + } + async remove(state, recordId, pathValue, options = {}) { +@@ -134,7 +138,7 @@ export class MirrorMaterializer { + throw new MirrorDivergenceError(recordId, entry.path); + } + if (existing !== null) +- await this.fileSystem.remove(path); ++ await this.fileSystem.remove(path, existing); + delete state.records[recordId]; + } + async putResource(state, resource, managedState) { @@ -145,7 +149,7 @@ export class MirrorMaterializer { && (!prior || this.runtime.digest(existing) !== prior.hash)) { throw new MirrorDivergenceError(`resource:${resource.path}`, resource.path); @@ -218,8 +294,17 @@ index 6936f79..64b0670 100644 state.resources ??= {}; state.resources[resource.path] = { path: resource.path, +@@ -159,7 +163,7 @@ export class MirrorMaterializer { + throw new MirrorDivergenceError(`resource:${pathValue}`, pathValue); + } + if (existing !== null) +- await this.fileSystem.remove(pathValue); ++ await this.fileSystem.remove(pathValue, existing); + if (state.resources) + delete state.resources[pathValue]; + } diff --git a/node_modules/@mdbase-dev/connect-sync/dist/mirror-state.d.ts b/node_modules/@mdbase-dev/connect-sync/dist/mirror-state.d.ts -index 7c7372e..ae211aa 100644 +index 7c7372e..f6445cf 100644 --- a/node_modules/@mdbase-dev/connect-sync/dist/mirror-state.d.ts +++ b/node_modules/@mdbase-dev/connect-sync/dist/mirror-state.d.ts @@ -85,6 +85,8 @@ export interface MirrorState { @@ -231,7 +316,7 @@ index 7c7372e..ae211aa 100644 }>; /** Temporary stable-identity bindings when local paths differ from the base. */ local_bindings?: Record; /** Exact UTF-8 read, preserving a leading BOM; expected I/O failures reject as `SyncError("file_read_failed")`. */ readText(path: string): Promise; @@ -242,7 +327,16 @@ index 7c7372e..ae211aa 100644 + pathKind?(path: string): Promise<"file" | "folder" | null>; /** Atomically rename one managed path without changing its bytes. */ move(source: string, target: string): Promise; - remove(path: string): Promise; +- remove(path: string): Promise; ++ remove(path: string, expected?: string | MirrorBinaryInfo | null): Promise; + listMarkdown(excluded: ReadonlySet): Promise; + inspectBinary(path: string): Promise; + /** Atomically install a fully-drained byte stream at path. */ +- writeBinary(path: string, source: AsyncIterable): Promise; ++ writeBinary(path: string, source: AsyncIterable, expected?: MirrorBinaryInfo | null): Promise; + /** Writable-file adapters enumerate only eligible non-Markdown regular files. */ + listBinary?(excluded: ReadonlySet): Promise; + /** Opens a fresh stream for a stable path snapshot. */ diff --git a/node_modules/@mdbase-dev/connect-sync/dist/mirror-state.js b/node_modules/@mdbase-dev/connect-sync/dist/mirror-state.js index 5a3bad2..c4207b7 100644 --- a/node_modules/@mdbase-dev/connect-sync/dist/mirror-state.js @@ -258,7 +352,7 @@ index 5a3bad2..c4207b7 100644 validatePortableMirrorPath(conflict.local.object.path); if (conflict.remote.state === "exact") diff --git a/node_modules/@mdbase-dev/connect-sync/dist/sync-executor.js b/node_modules/@mdbase-dev/connect-sync/dist/sync-executor.js -index 599bcb8..30c92d0 100644 +index 599bcb8..22e1bf6 100644 --- a/node_modules/@mdbase-dev/connect-sync/dist/sync-executor.js +++ b/node_modules/@mdbase-dev/connect-sync/dist/sync-executor.js @@ -1,7 +1,7 @@ @@ -341,7 +435,24 @@ index 599bcb8..30c92d0 100644 await this.materializer.putFile(state, file, state); this.installPathOwner(action.target); return { action_id: action.action_id, status: "completed" }; -@@ -372,12 +389,17 @@ export class PlanOnlySyncExecutor { +@@ -196,8 +213,14 @@ export class PlanOnlySyncExecutor { + const entry = state.resources?.[action.target.identity]; + if (entry) + await this.materializer.removeResource(state, action.target.path, entry); +- else +- await this.ports.fileSystem.remove(action.target.path); ++ else { ++ const expected = await this.ports.fileSystem.read(action.target.path); ++ if (expected !== null) { ++ if (runtimeDocumentRevision(expected, this.ports.runtime) !== action.target.payload_revision) ++ throw stale(`${action.target.path} changed before removal.`); ++ await this.ports.fileSystem.remove(action.target.path, expected); ++ } ++ } + } + else { + await this.materializer.removeFile(state, action.target.identity); +@@ -372,12 +395,17 @@ export class PlanOnlySyncExecutor { : action.expected_remote; state.planned_conflicts ??= {}; const conflictKind = receipt.status === "rejected" ? "rejected" : "both_changed"; diff --git a/patches/README.md b/patches/README.md index d4824ce..541f216 100644 --- a/patches/README.md +++ b/patches/README.md @@ -28,6 +28,27 @@ addition is the optional `ancestor_document` below): guarantee applies to this plugin's conditional-write implementation. This uses Obsidian's serialized read/modify/write contract, not an OS-wide lock against arbitrary external writers. +- `mirror-materializer.js` / `mirror-state.d.ts`: pass the inspected binary + destination to `writeBinary(path, source, expected)`. `null` requires absence; + otherwise the plugin rechecks digest/size after draining the stream. This + prevents a competing create/edit between SDK preflight and adapter invocation + from becoming the overwrite baseline. Existing adapters may ignore this + optional argument. Obsidian has no binary `Vault.process`, so this is a + pre-write check rather than an OS-wide atomic compare-and-swap. This API still + needs an upstream SDK source port before removing/upgrading the patch. + Regression: `test/syncReliability.test.ts` SDK binary preflight race. +- `mirror-materializer.js` / `mirror-state.d.ts`: pass inspected text/binary + expectations to managed-file removal (`remove(path, expected)`) and recheck + them in the plugin before trashing. This rejects competing edits between SDK + preflight and adapter removal. Like binary writes, it is a pre-trash check, + not an OS-wide atomic delete. The optional argument is backward compatible + with old adapters and needs an upstream SDK source port. Regression: + `test/syncReliability.test.ts` SDK delete preflight race and binary removal. + `directory-mirror.js` also binds hosted-deletion conflict resolution to the + inspected local revision and passes its expected bytes to removal; binary + binding cleanup does likewise. `sync-executor.js` checks the expected resource + revision before its missing-metadata removal branch. These close the same gap + outside MirrorMaterializer; the final trash API still is not atomic. - `sync-inspector.js` / `mirror-state.d.ts`: optional physical `pathKind` detects destination directories and ancestor files. Blocking issues enter the normal planner/fingerprint instead of creating an impossible transfer. No local file diff --git a/scripts/profile-large-sync.mjs b/scripts/profile-large-sync.mjs new file mode 100644 index 0000000..838e352 --- /dev/null +++ b/scripts/profile-large-sync.mjs @@ -0,0 +1,96 @@ +// Isolated, generated data only: no Obsidian CLI, vault directories or network. +// Run after `npm run test:unit`: +// node --expose-gc --loader ./test/obsidian-loader.mjs scripts/profile-large-sync.mjs [10000 20000 50000] +import assert from "node:assert/strict"; +import { performance } from "node:perf_hooks"; +import { resolve } from "node:path"; +import { pathToFileURL } from "node:url"; +const sdkRoot = process.env.MDBASE_PROFILE_SDK_ROOT; +const { MemoryAuthority } = await import(sdkRoot + ? pathToFileURL(resolve(sdkRoot, "dist/index.js")).href : "@mdbase-dev/connect-sync"); +const { WritableDirectoryMirror } = await import(sdkRoot + ? pathToFileURL(resolve(sdkRoot, "dist/mirror.js")).href : "@mdbase-dev/connect-sync/mirror"); +import { MemoryVault } from "../.test-dist/test/memoryVault.js"; +import { IndexedDbMirrorStateStore, ObsidianMirrorFileSystem } from "../.test-dist/src/connectSync.js"; +import { indexedDB } from "fake-indexeddb"; + +Object.assign(globalThis, { indexedDB }); +const sizes = process.argv.slice(2).map(Number); +if (!sizes.length) sizes.push(10_000, 20_000, 50_000); +assert.ok(sizes.every((size) => Number.isSafeInteger(size) && size > 0)); +const measure = async (operation) => { + globalThis.gc?.(); + const heap = process.memoryUsage().heapUsed; + const start = performance.now(); + const value = await operation(); + return { value, ms: +(performance.now() - start).toFixed(2), heap_delta: process.memoryUsage().heapUsed - heap }; +}; +const output = ({ ms, heap_delta }) => ({ ms, heap_delta }); + +for (const count of sizes) { + const authority = new MemoryAuthority({ snapshotPageSize: 200 }); + const records = Array.from({ length: count }, (_, index) => ({ + record_id: `record-${index}`, path: `notes/${String(index).padStart(5, "0")}.md`, + frontmatter: { title: `Note ${index}`, status: "open" }, body: `${"Generated note body. ".repeat(40)}\n`, types: [], + })); + authority.seed(records); + const replica = authority.registerReplica({ name: "Generated benchmark", mode: "read_write" }); + const vault = new MemoryVault(); + for (const record of authority.serialize().records) await vault.create(record.path, record.document); + for (let index = 0; index < 50; index++) await vault.createBinary(`attachments/${index}.png`, new Uint8Array(32_768).buffer); + const transport = authority.transport(replica); + const calls = { snapshot: 0, changes: 0, readText: 0, writes: 0, write_bytes: 0 }; + const trackedTransport = { ...transport, + snapshot: async (...args) => { calls.snapshot++; return transport.snapshot(...args); }, + changes: async (...args) => { calls.changes++; return transport.changes(...args); }, + }; + const fileSystem = new ObsidianMirrorFileSystem(vault); + const readText = fileSystem.readText.bind(fileSystem); + fileSystem.readText = async (...args) => { calls.readText++; return readText(...args); }; + let state = null; + const stateStore = { + read: async () => state, + write: async (next) => { state = structuredClone(next); calls.writes++; calls.write_bytes += Buffer.byteLength(JSON.stringify(next)); }, + }; + const mirror = new WritableDirectoryMirror(replica, trackedTransport, { fileSystem, stateStore }); + const initial = await measure(() => mirror.review()); + const initialCalls = { ...calls }; + const initialApply = await measure(() => mirror.apply(initial.value.plan)); + assert.equal(initialApply.value.status, "applied"); + const reset = () => { for (const key of Object.keys(calls)) calls[key] = 0; }; + reset(); + const unchanged = await measure(() => mirror.review()); + assert.equal(unchanged.value.plan.actions.length, 0); + const unchangedCalls = { ...calls }; + const first = vault.files.get(records[0].path); + await vault.modify(first.file, first.content + "One local edit.\n"); + reset(); + const incremental = await measure(() => mirror.review()); + assert.equal(incremental.value.plan.summary.uploads, 1); + const incrementalCalls = { ...calls }; + reset(); + const incrementalApply = await measure(() => mirror.apply(incremental.value.plan)); + assert.equal(incrementalApply.value.status, "applied"); + const applyCalls = { ...calls }; + reset(); + const probe = await measure(() => trackedTransport.changes(state.cursor, 1)); + const stateBytes = Buffer.byteLength(JSON.stringify(state)); + const idb = new IndexedDbMirrorStateStore(`generated-${count}`); + const idbWrite = await measure(() => idb.write(state)); + const idbRead = await measure(() => idb.read()); + const idbProbe = await measure(async () => { + const checkpoint = await idb.readCheckpoint(); + return trackedTransport.changes(checkpoint.cursor, 1); + }); + // This is fake-indexeddb's structured-clone cost, not Chromium disk latency. + assert.equal(Object.keys(idbRead.value.records).length, count); + idb.close(); + console.log(JSON.stringify({ count, attachments: 50, generated_document_bytes: records[0].body.length, + initial: { ...output(initial), actions: initial.value.plan.actions.length, calls: initialCalls }, + initial_apply: output(initialApply), unchanged: { ...output(unchanged), calls: unchangedCalls }, + incremental: { ...output(incremental), calls: incrementalCalls }, + incremental_apply: { ...output(incrementalApply), calls: applyCalls }, + probe: output(probe), state_bytes: stateBytes, fake_idb_write: output(idbWrite), fake_idb_read: output(idbRead), + fake_idb_probe: output(idbProbe), + })); +} diff --git a/scripts/test-sync-layout.cjs b/scripts/test-sync-layout.cjs index 780e923..ba21318 100644 --- a/scripts/test-sync-layout.cjs +++ b/scripts/test-sync-layout.cjs @@ -25,10 +25,12 @@ fs.mkdirSync(shots, {recursive:true}); 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 states=['healthy','scope','local-issue','offline','auth','copied','paused','internal','progress','first-sync','deletions','rebuild','conflict','conflict-local-absent','conflict-hosted-absent','history','enrollment','upload','away-offline','away-auth','away-copied','away-paused','away-internal']; const results=[]; for(const state of states) { await page.evaluate(state=>{ + const away=state.startsWith('away-'); + if(away)state=state.slice(5); 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:[]}}; @@ -42,6 +44,8 @@ fs.mkdirSync(shots, {recursive:true}); 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(state==='scope')p.settings.mirrorProfile.selectiveSync.excluded_folders=[longPath.replace('.md','')]; + if(state==='local-issue')p.sync.update({status:{state:'attention',conflicts:[],local_issues:[{code:'file_read_failed',path:longPath,message:'Could not read this file. Open it to inspect the problem.'}]}}); 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}}); @@ -55,9 +59,9 @@ fs.mkdirSync(shots, {recursive:true}); 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') { + if(state.startsWith('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'}}); + view.sync.conflictComparisons.set('record:decision',{entity:'record',objectId:'record',decisionId:'decision',local:state==='conflict-local-absent'?{state:'absent'}:{state:'exact',document:'Line from this device'},remote:state==='conflict-hosted-absent'?{state:'absent'}:{state:'exact',document:'Line from another device'}}); } if(state==='history') { const at=new Date().toISOString(); @@ -67,15 +71,17 @@ fs.mkdirSync(shots, {recursive:true}); p.settings.mirrorProfile=null; if(state==='upload')view.schema={config:{spec_version:'0.3.0'},types:new Map(),contracts:new Map()}; } + view.destination=away?'issues':'sync'; 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 checks=await page.locator('.mdbase-sync-document, .mdbase-issues-document').evaluate(el=>{ const content=el.closest('.mdbase-workspace-content'); - const buttons=[...el.querySelectorAll('.mod-cta, .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 buttons=[...el.querySelectorAll('.mod-cta, .mod-warning, .mdbase-conflict-row button, .mdbase-activity-row > button')].map(b=>({text:b.textContent,height:b.getBoundingClientRect().height})); + const topbar=el.closest('.mdbase-workspace').querySelector('.mdbase-topbar'); + return {topbarOverflow:topbar.scrollWidth>topbar.clientWidth+1,tabStatus:topbar.querySelector('.mdbase-nav-status')?.textContent,paneWidth:content.clientWidth,headingWidth:el.querySelector('.mdbase-sync-heading')?.getBoundingClientRect().width,scrollWidth:content.scrollWidth,overflow:content.scrollWidth>content.clientWidth+1,buttons}; }); const box=await page.locator('.mdbase-workspace').boundingBox(); const cdp=await page.context().newCDPSession(page); @@ -83,6 +89,8 @@ fs.mkdirSync(shots, {recursive:true}); 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(checks.topbarOverflow)failures.push('Destination bar overflow'); + if(state.startsWith('away-')&&!checks.tabStatus)failures.push('Problem hidden outside Sync'); if(width===390&&checks.headingWidth!=null&&checks.headingWidthb.height<43.5))failures.push('Primary/dismiss target below 44px'); results.push({state,width,theme,...checks,failures}); diff --git a/src/connectSync.ts b/src/connectSync.ts index ce831fc..7240900 100644 --- a/src/connectSync.ts +++ b/src/connectSync.ts @@ -6,6 +6,7 @@ import { stringifyYaml, TFile, TFolder, + type TAbstractFile, Vault, } from "obsidian"; import picomatch from "picomatch"; @@ -784,7 +785,10 @@ class BinaryPartReader { const count = Math.min(length - offset, this.remainder.byteLength); output.set(this.remainder.subarray(0, count), offset); offset += count; - this.remainder = this.remainder.slice(count); + // The source chunk was copied on receipt, so a view of its unread tail is + // safe. Copying each tail makes small multipart uploads quadratic. Drop + // the exhausted view to release its backing buffer during the last PUT. + this.remainder = count === this.remainder.byteLength ? new Uint8Array() : this.remainder.subarray(count); } return output; } @@ -852,7 +856,8 @@ function reservedWriteFolders(vault: Vault): string[] { function safeMirrorPath(vault: Vault, input: string): string { const path = normalizeSafeRelativePath(input); - if (reservedWriteFolders(vault).some((folder) => path === folder || path.startsWith(`${folder}/`))) { + const key = portablePathKey(path); + if (reservedWriteFolders(vault).some((folder) => key === portablePathKey(folder) || key.startsWith(`${portablePathKey(folder)}/`))) { throw new SyncError("unsafe_mirror_path", `The collection authority attempted to write a reserved path: ${path}`); } return path; @@ -928,6 +933,23 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { private readonly observeWrite: (path: string) => void = () => undefined, ) {} + /** Resolve a disk alias only after proving its physical name is unambiguous. */ + private async cachedEntry(path: string): Promise { + const exact = this.vault.getAbstractFileByPath(path); + if (exact || !await this.vault.adapter.exists(path)) return exact; + const slash = path.lastIndexOf("/"); + const listing = await this.vault.adapter.list(slash < 0 ? "" : path.slice(0, slash)); + const key = portablePathKey(path); + const aliases = [...listing.files, ...listing.folders].filter((candidate) => portablePathKey(candidate) === key); + if (aliases.length !== 1) throw new SyncError("mirror_path_collision", `More than one physical spelling blocks ${path}.`); + const diskEntry = this.vault.getAbstractFileByPath(aliases[0]); + if (diskEntry) return diskEntry; + // APFS can report NFC while Obsidian's cache still holds NFD (or vice versa). + const cached = this.vault.getAllLoadedFiles().filter((entry) => portablePathKey(entry.path) === key); + if (cached.length > 1) throw new SyncError("mirror_path_collision", `More than one cached spelling blocks ${path}.`); + return cached[0] ?? null; + } + async exists(input: string): Promise { const path = safeMirrorPath(this.vault, input); return this.vault.getAbstractFileByPath(path) !== null || await this.vault.adapter.exists(path); @@ -941,6 +963,8 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { async readText(input: string): Promise { const path = safeMirrorPath(this.vault, input); + // Byte reads already follow the filesystem's aliases. Only writes/renames + // need a cache lookup; avoid listing disk paths for ordinary text scans. const file = this.vault.getAbstractFileByPath(path); if (file instanceof TFolder) { throw new SyncError("mirror_path_collision", `Expected a file at ${path}.`); @@ -994,17 +1018,19 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { } const slash = path.lastIndexOf("/"); if (slash >= 0) await ensureFolder(this.vault, path.slice(0, slash)); - const existing = this.vault.getAbstractFileByPath(path); + const existing = await this.cachedEntry(path); if (existing instanceof TFolder) { throw new SyncError("mirror_path_collision", `A folder blocks the mirror file ${path}.`); } this.assertActive(); if (existing instanceof TFile) { + const spelling = existing.path; await this.vault.process(existing, (current) => { this.assertActive(); - if (existing.path !== path || this.vault.getAbstractFileByPath(path) !== existing) throw stale(); + if (existing.path !== spelling || this.vault.getAbstractFileByPath(spelling) !== existing) throw stale(); if (current !== before && current !== value) throw stale(); this.observeWrite(path); + this.observeWrite(spelling); return value; }); } else { @@ -1019,30 +1045,44 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { async move(sourceInput: string, targetInput: string): Promise { const source = safeMirrorPath(this.vault, sourceInput); const target = safeMirrorPath(this.vault, targetInput); - const file = this.vault.getAbstractFileByPath(source); + const file = await this.cachedEntry(source); if (!(file instanceof TFile)) { throw new SyncError("mirror_path_collision", `Expected a file at ${source}.`); } - if (this.vault.getAbstractFileByPath(target) !== null || await this.vault.adapter.exists(target)) { + const destination = await this.cachedEntry(target); + const sameFile = destination === file && portablePathKey(source) === portablePathKey(target); + if (!sameFile && (destination !== null || await this.vault.adapter.exists(target))) { throw new SyncError("mirror_path_collision", `A file or folder blocks the mirror path ${target}.`); } const slash = target.lastIndexOf("/"); if (slash >= 0) await ensureFolder(this.vault, target.slice(0, slash)); this.assertActive(); this.observeWrite(source); + this.observeWrite(file.path); this.observeWrite(target); await this.vault.rename(file, target); } - async remove(input: string): Promise { + async remove(input: string, expected?: string | MirrorBinaryInfo | null): Promise { const path = safeMirrorPath(this.vault, input); - const existing = this.vault.getAbstractFileByPath(path); + if (expected !== undefined) { + let exact: boolean; + if (expected === null) exact = !await this.exists(path); + else if (typeof expected === "string") exact = await this.read(path) === expected; + else { + const current = await this.inspectBinary(path); + exact = current?.content_digest === expected.content_digest && current?.size === expected.size; + } + if (!exact) throw new SyncError("sync_plan_stale", `${path} changed before it could be removed. Review sync again.`); + } + const existing = await this.cachedEntry(path); if (existing == null) return; if (!(existing instanceof TFile)) { throw new SyncError("mirror_path_collision", `Expected a file at ${path}.`); } this.assertActive(); this.observeWrite(path); + this.observeWrite(existing.path); await this.trashFile(existing); } @@ -1051,13 +1091,13 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { .map((file) => normalizePath(file.path)) .filter((path) => MIRROR_RECORD_PATH.test(path) && !excluded.has(path)) .filter((path) => !reservedWriteFolders(this.vault) - .some((folder) => path === folder || path.startsWith(`${folder}/`))) + .some((folder) => portablePathKey(path) === portablePathKey(folder) || portablePathKey(path).startsWith(`${portablePathKey(folder)}/`))) .sort(); } async inspectBinary(input: string): Promise { - const path = assertVisibleBinaryPath(input); - const file = this.vault.getAbstractFileByPath(path); + const path = assertVisibleBinaryPath(safeMirrorPath(this.vault, input)); + const file = await this.cachedEntry(path); if (file == null) return null; if (!(file instanceof TFile)) throw new SyncError("mirror_path_collision", `Expected a file at ${path}.`); assertBinarySize(file.stat.size); @@ -1067,7 +1107,7 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { } async writeBinary(input: string, source: AsyncIterable, expected?: MirrorBinaryInfo | null): Promise { - const path = assertVisibleBinaryPath(input); + const path = assertVisibleBinaryPath(safeMirrorPath(this.vault, input)); // A stream can take seconds to consume. Remember its destination before // reading any bytes, then recheck it after staging and folder creation. const before = expected === undefined ? await this.inspectBinary(path) : expected; @@ -1078,11 +1118,14 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { if (current?.content_digest !== before?.content_digest || current?.size !== before?.size) { throw new SyncError("sync_plan_stale", `${path} changed before it could be written. Review sync again.`); } - const existing = this.vault.getAbstractFileByPath(path); + const existing = await this.cachedEntry(path); if (existing instanceof TFolder) throw new SyncError("mirror_path_collision", `A folder blocks the mirror file ${path}.`); this.assertActive(); this.observeWrite(path); - if (existing instanceof TFile) await this.vault.modifyBinary(existing, bytes); + if (existing instanceof TFile) { + this.observeWrite(existing.path); + await this.vault.modifyBinary(existing, bytes); + } else await this.vault.createBinary(path, bytes); } @@ -1092,7 +1135,7 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { .filter((path) => !MIRROR_RECORD_PATH_ANY_CASE.test(path) && !excluded.has(path)) .filter((path) => { try { - assertVisibleBinaryPath(path); + assertVisibleBinaryPath(safeMirrorPath(this.vault, path)); return true; } catch { return false; @@ -1102,8 +1145,8 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { } async readBinary(input: string): Promise | null> { - const path = assertVisibleBinaryPath(input); - const file = this.vault.getAbstractFileByPath(path); + const path = assertVisibleBinaryPath(safeMirrorPath(this.vault, input)); + const file = await this.cachedEntry(path); if (file == null) return null; if (!(file instanceof TFile)) throw new SyncError("mirror_path_collision", `Expected a file at ${path}.`); assertBinarySize(file.stat.size); @@ -1285,7 +1328,15 @@ export class IndexedDbMirrorBlobStore implements MirrorBlobStore { if (!request.result.objectStoreNames.contains(BLOB_CHUNK_STORE)) request.result.createObjectStore(BLOB_CHUNK_STORE); }; request.onerror = () => reject(indexedDbError(request.error, "binary store open")); - request.onsuccess = () => resolve(request.result); + request.onsuccess = () => { + const database = request.result; + const forget = () => { if (this.database === opening) this.database = null; }; + // WebKit can close a connection while the app is suspended. Do not + // cache the dead handle forever; the scheduler's next retry reopens it. + database.onclose = forget; + database.onversionchange = () => { database.close(); forget(); }; + resolve(database); + }; }); this.database = opening; void opening.catch(() => { @@ -1295,45 +1346,113 @@ export class IndexedDbMirrorBlobStore implements MirrorBlobStore { } } +export interface MirrorCheckpointSummary { + cursor: number; + scope_epoch: number; + recovery_required: boolean; +} + +function mirrorCheckpointSummary(state: MirrorState | null): MirrorCheckpointSummary | null { + return state ? { cursor: state.cursor, scope_epoch: state.scope_epoch, recovery_required: Boolean(state.batch) } : null; +} + +type CheckpointReadingStateStore = MirrorStateStore & { + readCheckpoint?(): Promise; +}; + export class IndexedDbMirrorStateStore implements MirrorStateStore { private database: Promise | null = null; + private checkpointReady = false; constructor(private readonly key: string) {} + // Array keys cannot collide with the string keys used by existing state. + // Keeping the same object store avoids an incompatible database upgrade. + private get checkpointKey(): string[] { return [this.key, "checkpoint"]; } + async read(): Promise { const database = await this.open(); + const refreshCheckpoint = !this.checkpointReady; return new Promise((resolve, reject) => { - const request = database.transaction(STATE_STORE, "readonly").objectStore(STATE_STORE).get(this.key); - request.onsuccess = () => resolve((request.result as MirrorState | undefined) ?? null); - request.onerror = () => reject(indexedDbError(request.error, "mirror state read")); + const transaction = database.transaction(STATE_STORE, refreshCheckpoint ? "readwrite" : "readonly"); + const store = transaction.objectStore(STATE_STORE); + const request = store.get(this.key); + let state: MirrorState | null = null; + request.onsuccess = () => { + state = (request.result as MirrorState | undefined) ?? null; + if (refreshCheckpoint) { + if (state) store.put(mirrorCheckpointSummary(state), this.checkpointKey); + else store.delete(this.checkpointKey); + } + }; + transaction.oncomplete = () => { + if (refreshCheckpoint) this.checkpointReady = true; + resolve(state); + }; + transaction.onerror = () => reject(indexedDbError(transaction.error, "mirror state read")); + transaction.onabort = () => reject(indexedDbError(transaction.error, "mirror state read")); + }); + } + + /** No document clone on repeated probes. One initial read also repairs legacy summaries. */ + async readCheckpoint(): Promise { + // Revalidate once per adapter lifetime: an older plugin may have written or + // cleared state without knowing about the summary. Normal startup inspection + // already reads the state and primes this, so polling stays tiny thereafter. + if (!this.checkpointReady) return mirrorCheckpointSummary(await this.read()); + const database = await this.open(); + const result = await new Promise<{ exists: boolean; checkpoint: MirrorCheckpointSummary | null }>((resolve, reject) => { + const transaction = database.transaction(STATE_STORE, "readonly"); + const store = transaction.objectStore(STATE_STORE); + const checkpoint = store.get(this.checkpointKey); + const stateKey = store.getKey(this.key); + transaction.oncomplete = () => resolve({ + exists: stateKey.result !== undefined, + checkpoint: (checkpoint.result as MirrorCheckpointSummary | undefined) ?? null, + }); + transaction.onerror = () => reject(indexedDbError(transaction.error, "mirror checkpoint read")); + transaction.onabort = () => reject(indexedDbError(transaction.error, "mirror checkpoint read")); }); + if (!result.exists) return null; + if (!result.checkpoint) { + this.checkpointReady = false; + return mirrorCheckpointSummary(await this.read()); + } + return result.checkpoint; } async write(state: MirrorState): Promise { const database = await this.open(); await new Promise((resolve, reject) => { const transaction = database.transaction(STATE_STORE, "readwrite"); - transaction.objectStore(STATE_STORE).put(state, this.key); + const store = transaction.objectStore(STATE_STORE); + store.put(state, this.key); + store.put(mirrorCheckpointSummary(state), this.checkpointKey); transaction.oncomplete = () => resolve(); transaction.onerror = () => reject(indexedDbError(transaction.error, "mirror state write")); transaction.onabort = () => reject(indexedDbError(transaction.error, "mirror state write")); }); + this.checkpointReady = true; } async clear(): Promise { const database = await this.open(); await new Promise((resolve, reject) => { const transaction = database.transaction(STATE_STORE, "readwrite"); - transaction.objectStore(STATE_STORE).delete(this.key); + const store = transaction.objectStore(STATE_STORE); + store.delete(this.key); + store.delete(this.checkpointKey); transaction.oncomplete = () => resolve(); transaction.onerror = () => reject(indexedDbError(transaction.error, "mirror state clear")); transaction.onabort = () => reject(indexedDbError(transaction.error, "mirror state clear")); }); + this.checkpointReady = true; } close(): void { void this.database?.then((database) => database.close(), () => undefined); this.database = null; + this.checkpointReady = false; } private open(): Promise { @@ -1349,7 +1468,13 @@ export class IndexedDbMirrorStateStore implements MirrorStateStore { } }; request.onerror = () => reject(indexedDbError(request.error, "mirror state store open")); - request.onsuccess = () => resolve(request.result); + request.onsuccess = () => { + const database = request.result; + const forget = () => { if (this.database === opening) this.database = null; }; + database.onclose = forget; + database.onversionchange = () => { database.close(); forget(); }; + resolve(database); + }; }); this.database = opening; void opening.catch(() => { @@ -1365,6 +1490,16 @@ export class DeviceMirrorLease implements MirrorLease { constructor(private readonly key: string) {} async runExclusive(operation: () => Promise): Promise { + // Static fields only protect one plugin/renderer instance. Web Locks share + // the same origin/storage scope as IndexedDB, including popout windows and + // independently evaluated plugin bundles. + const locks = typeof navigator === "undefined" ? null : navigator.locks; + if (locks) { + return locks.request(`mdbase-mirror:${this.key}`, { ifAvailable: true }, async (lock) => { + if (!lock) throw new SyncError("mirror_busy", "Another window is synchronizing this vault."); + return operation(); + }); + } if (DeviceMirrorLease.active.has(this.key)) { throw new SyncError("mirror_busy", "A mirror operation is already running for this vault."); } @@ -1758,11 +1893,14 @@ export class ConnectSyncController { */ async remoteChangesWaiting(): Promise { const profile = this.requireProfile(); - const state = await this.stateStoreFor(profile).read(); - if (!state || state.batch) return true; + const store: CheckpointReadingStateStore = this.stateStoreFor(profile); + const checkpoint = store.readCheckpoint + ? await store.readCheckpoint() + : mirrorCheckpointSummary(await store.read()); + if (!checkpoint || checkpoint.recovery_required) return true; const transport = await this.transportFor(profile); - const page = await transport.changes(state.cursor, 1); - return page.reset_required || page.scope_epoch !== state.scope_epoch || page.head > state.cursor; + const page = await transport.changes(checkpoint.cursor, 1); + return page.reset_required || page.scope_epoch !== checkpoint.scope_epoch || page.head > checkpoint.cursor; } /** The durable mirror checkpoint, for diagnostics. */ @@ -2128,7 +2266,10 @@ export class ConnectSyncController { async disconnect(removeSyncedFiles: boolean): Promise { if (this.isSyncing()) throw new SyncError("mirror_busy", "Stop the current synchronization before disconnecting."); - return this.withMirrorOperation(() => this.disconnectActive(removeSyncedFiles)); + return this.withMirrorOperation(async () => { + const profile = this.requireProfile(); + return this.leaseFor(profile).runExclusive(() => this.disconnectActive(removeSyncedFiles)); + }); } private async disconnectActive(removeSyncedFiles: boolean): Promise { @@ -2691,8 +2832,7 @@ export class ConnectSyncController { fileSystem: this.fileSystem, blobStore: this.blobStoreFor(profile), selectiveSync: normalizeSelectiveSync(profile.selectiveSync), - lease: this.options.leaseFactory?.(profile) - ?? new DeviceMirrorLease(`${profile.collectionId}:${profile.replicaId}`), + lease: this.leaseFor(profile), onProgress, }; return profile.mode === "read_write" @@ -2700,6 +2840,10 @@ export class ConnectSyncController { : new DirectoryMirror(profile.replicaId, transport, mirrorOptions); } + private leaseFor(profile: MirrorProfile): MirrorLease { + return this.options.leaseFactory?.(profile) ?? new DeviceMirrorLease(`${profile.collectionId}:${profile.replicaId}`); + } + private requireProfile(): MirrorProfile { this.assertActive(); const profile = this.settingsHost.getMirrorProfile(); diff --git a/src/pathGlob.ts b/src/pathGlob.ts index 3cb6e76..e046995 100644 --- a/src/pathGlob.ts +++ b/src/pathGlob.ts @@ -10,53 +10,91 @@ export function portableGlobMatch(pattern: string, path: string): boolean { return matchComponents(path.split("/"), pattern.split("/")); } +/** Retry only the most recent wildcard, not every possible suffix recursively. */ function matchComponents(path: string[], pattern: string[]): boolean { - if (pattern.length === 0) return path.length === 0; - const [first, ...rest] = pattern; - if (first === "**") { - return matchComponents(path, rest) || (path.length > 0 && matchComponents(path.slice(1), pattern)); + let text = 0; + let token = 0; + let star = -1; + let retry = 0; + while (text < path.length) { + if (pattern[token] === "**") { + star = token++; + retry = text; + } else if (token < pattern.length && matchSegment(path[text], pattern[token])) { + text++; + token++; + } else if (star >= 0) { + token = star + 1; + text = ++retry; + } else return false; } - if (path.length === 0) return false; - return matchSegment([...path[0]], [...first]) && matchComponents(path.slice(1), rest); + while (pattern[token] === "**") token++; + return token === pattern.length; } -function matchSegment(text: string[], pattern: string[]): boolean { - if (pattern.length === 0) return text.length === 0; - const [head, ...rest] = pattern; - if (head === "*") { - return matchSegment(text, rest) || (text.length > 0 && matchSegment(text.slice(1), pattern)); +interface CharacterClass { + negated: boolean; + ranges: Array<[number, number]>; +} +type SegmentToken = string | CharacterClass; + +function matchSegment(value: string, pattern: string): boolean { + const text = [...value]; + const tokens = segmentTokens([...pattern]); + let character = 0; + let token = 0; + let star = -1; + let retry = 0; + while (character < text.length) { + if (tokens[token] === "*") { + star = token++; + retry = character; + } else if (matchesCharacter(tokens[token], text[character])) { + character++; + token++; + } else if (star >= 0) { + token = star + 1; + character = ++retry; + } else return false; } - if (head === "?") return text.length > 0 && matchSegment(text.slice(1), rest); - if (head === "[") { - const parsed = parseClass(rest); + while (tokens[token] === "*") token++; + return token === tokens.length; +} + +function matchesCharacter(token: SegmentToken | undefined, character: string): boolean { + if (token === undefined) return false; + if (typeof token === "string") return token === "?" || token === character; + const point = codePoint(character); + return token.ranges.some(([low, high]) => low <= point && point <= high) !== token.negated; +} + +function segmentTokens(pattern: string[]): SegmentToken[] { + const tokens: SegmentToken[] = []; + for (let index = 0; index < pattern.length;) { + const parsed = pattern[index] === "[" ? parseClass(pattern, index + 1) : undefined; if (parsed) { - return text.length > 0 && parsed.matches(text[0]) && matchSegment(text.slice(1), parsed.after); - } + tokens.push(parsed.token); + index = parsed.after; + } else tokens.push(pattern[index++]); } - return text[0] === head && matchSegment(text.slice(1), rest); + return tokens; } -/** Parse a class body after `[`, returning its matcher and the pattern after `]`. */ -function parseClass(body: string[]): { matches: (c: string) => boolean; after: string[] } | undefined { - const negated = body[0] === "!"; +/** Parse after `[`. An incomplete class remains literal, as the spec requires. */ +function parseClass(pattern: string[], start: number): { token: CharacterClass; after: number } | undefined { + const negated = pattern[start] === "!"; const ranges: Array<[number, number]> = []; - let index = negated ? 1 : 0; + let index = start + (negated ? 1 : 0); let first = true; - while (index < body.length) { - const c = body[index]; - if (c === "]" && !first) { - const matches = (candidate: string) => { - const point = codePoint(candidate); - return ranges.some(([low, high]) => low <= point && point <= high) !== negated; - }; - return { matches, after: body.slice(index + 1) }; - } - if (index + 2 < body.length && body[index + 1] === "-" && body[index + 2] !== "]") { - ranges.push([codePoint(c), codePoint(body[index + 2])]); + while (index < pattern.length) { + const c = pattern[index]; + if (c === "]" && !first) return { token: { negated, ranges }, after: index + 1 }; + if (index + 2 < pattern.length && pattern[index + 1] === "-" && pattern[index + 2] !== "]") { + ranges.push([codePoint(c), codePoint(pattern[index + 2])]); index += 3; } else { ranges.push([codePoint(c), codePoint(c)]); - index += 1; + index++; } first = false; } diff --git a/src/syncHistory.ts b/src/syncHistory.ts index b46d902..f4d276a 100644 --- a/src/syncHistory.ts +++ b/src/syncHistory.ts @@ -197,17 +197,24 @@ export function pruneRuns( } export function parseHistory(source: string): SyncHistoryRun[] { + return parseHistoryLog(source).runs; +} + +function parseHistoryLog(source: string): { runs: SyncHistoryRun[]; needsRepair: boolean } { const runs: SyncHistoryRun[] = []; + let needsRepair = source.length > 0 && !source.endsWith("\n"); for (const line of source.split("\n")) { if (!line.trim()) continue; try { const value: unknown = JSON.parse(line); if (isRun(value)) runs.push(value); + else needsRepair = true; } catch { // A torn final line from an interrupted append is skipped, not fatal. + needsRepair = true; } } - return runs.sort((a, b) => a.finishedAt.localeCompare(b.finishedAt)); + return { runs: runs.sort((a, b) => a.finishedAt.localeCompare(b.finishedAt)), needsRepair }; } function isRun(value: unknown): value is SyncHistoryRun { @@ -246,10 +253,11 @@ export class SyncHistoryStore { async load(): Promise { 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); + const parsed = parseHistoryLog(source); + const loaded = pruneRuns(parsed.runs, this.limits); // Drop corrupt/torn lines before append can join a new entry to them. - if (source !== repaired) await this.adapter.write(this.path, repaired); + // An intact log needs no second serialization of every recorded transfer. + if (parsed.needsRepair || loaded.length !== parsed.runs.length) await this.rewrite(loaded); this.runs = loaded; }); } diff --git a/src/syncHttp.ts b/src/syncHttp.ts index 38309d7..9830455 100644 --- a/src/syncHttp.ts +++ b/src/syncHttp.ts @@ -164,7 +164,7 @@ export async function fetchSend( StackAbortController: typeof AbortController = AbortController, readHeaders: FetchStack["headers"] = (headers) => Object.fromEntries(headers), ): Promise { - const { signal, dispose } = deadline(request.signal, request.timeoutMs ?? DEFAULT_TIMEOUT_MS); + const { signal, check, dispose } = deadline(request.signal, request.timeoutMs ?? DEFAULT_TIMEOUT_MS); // The stack's own controller is aborted whenever ours is, without a reason // object: ours records why, and a reason need not cross a process boundary. const stack = new StackAbortController(); @@ -184,6 +184,8 @@ export async function fetchSend( } catch (error) { throw networkFailure(error, request.signal, signal); } + check(); + if (signal.aborted) throw networkFailure(signal.reason, request.signal, signal); const text = new TextDecoder().decode(arrayBuffer); if (request.throw !== false && response.status >= 400) { throw new HttpStatusError(`http_${response.status}`, `Request failed with status ${response.status}`, response.status); @@ -204,16 +206,22 @@ export async function requestUrlSend( send: (request: RequestUrlParam) => Promise = (input) => requestUrl(input), ): Promise { const { signal, timeoutMs, ...param } = request; - const { signal: limit, dispose } = deadline(signal, timeoutMs ?? DEFAULT_TIMEOUT_MS); + const { signal: limit, check, dispose } = deadline(signal, timeoutMs ?? DEFAULT_TIMEOUT_MS); + let removeAbort = () => {}; try { return await new Promise((resolve, reject) => { const onAbort = () => reject(networkFailure(limit.reason, signal, limit)); if (limit.aborted) return onAbort(); limit.addEventListener("abort", onAbort, { once: true }); - send(param).then(resolve, (error: unknown) => reject(networkFailure(error, signal, limit))) - .finally(() => limit.removeEventListener("abort", onAbort)); + removeAbort = () => limit.removeEventListener("abort", onAbort); + send(param).then((response) => { + check(); + if (limit.aborted) onAbort(); + else resolve(response); + }, (error: unknown) => reject(networkFailure(error, signal, limit))); }); } finally { + removeAbort(); dispose(); } } @@ -257,14 +265,19 @@ function isAbort(error: unknown): boolean { } /** Combines the caller's cancellation with a per-attempt deadline. */ -function deadline(parent: AbortSignal | undefined, timeoutMs: number): { signal: AbortSignal; dispose: () => void } { +function deadline(parent: AbortSignal | undefined, timeoutMs: number): { signal: AbortSignal; check: () => void; dispose: () => void } { const controller = new AbortController(); + const expiresAt = Date.now() + timeoutMs; const onParentAbort = () => controller.abort(abortError()); if (parent?.aborted) onParentAbort(); else parent?.addEventListener("abort", onParentAbort, { once: true }); - const timer = window.setTimeout(() => controller.abort(new NetworkError("network_timeout", "Connect did not respond in time.")), timeoutMs); + const timeout = () => controller.abort(new NetworkError("network_timeout", "Connect did not respond in time.")); + const timer = window.setTimeout(timeout, timeoutMs); return { signal: controller.signal, + // Mobile can freeze JS while native networking continues. The response + // microtask may run before an overdue timer on resume; check wall time too. + check: () => { if (!controller.signal.aborted && Date.now() >= expiresAt) timeout(); }, dispose: () => { window.clearTimeout(timer); parent?.removeEventListener("abort", onParentAbort); diff --git a/src/syncScheduler.ts b/src/syncScheduler.ts index 90abf47..c0bc67f 100644 --- a/src/syncScheduler.ts +++ b/src/syncScheduler.ts @@ -87,7 +87,7 @@ export class SyncScheduler { /** The person edited, renamed or deleted something in the mirrored folder. */ noteLocalChange(): void { const now = this.clock.now(); - this.firstLocalChangeAt ??= now; + if (this.firstLocalChangeAt === null || now < this.firstLocalChangeAt) this.firstLocalChangeAt = now; this.changed = true; this.schedule(Math.min(now + this.timing.localQuietMs, this.firstLocalChangeAt + this.timing.localMaxWaitMs), true); } @@ -163,7 +163,7 @@ export class SyncScheduler { if (local || await this.probe() === true) await this.host.refreshStatus(); return null; } - let due = local || this.failures > 0 || now - this.lastSyncAt >= this.timing.safetyNetMs; + let due = local || this.failures > 0 || now < this.lastSyncAt || now - this.lastSyncAt >= this.timing.safetyNetMs; if (!due) { const remote = await this.probe(); if (remote === null) return this.failed(true); diff --git a/src/syncUx.ts b/src/syncUx.ts index fe2a934..64be6c7 100644 --- a/src/syncUx.ts +++ b/src/syncUx.ts @@ -107,6 +107,8 @@ export function syncIndicator(input: { problem: SyncProblem | null; validationIssues: number; localChangeObserved: boolean; + /** Automatic sync stays off after the person stops it, even with a healthy checkpoint. */ + paused?: boolean; /** Changes in a plan that stopped for review instead of applying automatically. */ reviewChanges?: number; }): SyncIndicator { @@ -141,6 +143,9 @@ export function syncIndicator(input: { destination: "sync", }; } + if (input.paused && !problem) { + return { state: "paused", label: "mdbase: Paused", detail: "Changes wait until you resume sync", destination: "sync" }; + } if (problem && problem.kind !== "busy") { return { state: problem.kind === "paused" ? "paused" : problem.kind === "offline" ? "offline" : "attention", @@ -236,7 +241,7 @@ export function syncProblem(error: unknown): SyncProblem { actionLabel: "Resume sync", }; } - if (["stale", "stale_mirror_plan", "mirror_plan_stale", "sync_plan_stale", "conflict_decision_stale"].includes(code)) { + if (["stale", "stale_mirror_plan", "mirror_plan_stale", "sync_plan_stale", "conflict_decision_stale", "mirror_conflict_copy_missing"].includes(code)) { return { code, kind: "decision", diff --git a/src/workspace/syncPane.ts b/src/workspace/syncPane.ts index 7e5b638..dc38e49 100644 --- a/src/workspace/syncPane.ts +++ b/src/workspace/syncPane.ts @@ -269,7 +269,14 @@ 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(); + copy.disabled = this.ctx.busy; + copy.onclick = () => void this.ctx.perform(async () => { + try { + await this.ctx.host.copySyncDiagnostics(); + } finally { + this.ctx.pendingFocusKey = "sync-diagnostics"; + } + }); } } @@ -1016,18 +1023,24 @@ export class SyncPane { }; if (comparison) { for (const resolution of ["local", "remote"] as const) { + const destructive = comparison[resolution].state === "absent"; const button = actions.createEl("button", { - text: resolution === "local" ? "Keep local" : "Use hosted", + text: resolution === "local" + ? destructive ? "Delete from Connect" : "Keep local" + : destructive ? "Move local file to trash" : "Use hosted", + cls: destructive ? "mod-warning" : "", }); + button.setAttr("data-focus-key", `resolve-${comparisonKey}-${resolution}`); button.disabled = this.ctx.busy; button.onclick = () => void this.resolveMirrorConflict(conflict, resolution, false); } - if (conflict.path) { - const keepBoth = actions.createEl("button", { text: "Keep both" }); + if (conflict.path && comparison.local.state === "exact") { + const keepBoth = actions.createEl("button", { text: comparison.remote.state === "absent" ? "Keep a local copy" : "Keep both" }); + keepBoth.setAttr("data-focus-key", `resolve-${comparisonKey}-both`); keepBoth.disabled = this.ctx.busy; keepBoth.onclick = () => void this.resolveMirrorConflict(conflict, "remote", true); } - this.renderConflictComparison(row, comparison); + this.renderConflictComparison(row, comparison, Boolean(conflict.path)); } } } @@ -1062,8 +1075,15 @@ export class SyncPane { } } - private renderConflictComparison(container: HTMLElement, comparison: MirrorConflictComparison): void { + private renderConflictComparison(container: HTMLElement, comparison: MirrorConflictComparison, canKeepCopy = false): void { const comparisonEl = container.createDiv({ cls: "mdbase-conflict-comparison" }); + if (comparison.local.state === "absent") comparisonEl.createDiv({ cls: "mdbase-muted", text: "No local version." }); + if (comparison.remote.state === "absent") comparisonEl.createDiv({ + cls: "mdbase-muted", + text: canKeepCopy && comparison.local.state === "exact" + ? "No hosted version. Keeping a local copy saves this device's version before moving the original to trash." + : "No hosted version.", + }); if (comparison.entity === "record") { const diff = boundedLineDiff(comparison.local.document ?? "", comparison.remote.document ?? ""); const legend = comparisonEl.createDiv({ cls: "mdbase-conflict-legend" }); @@ -1127,11 +1147,12 @@ export class SyncPane { }); for (const issue of status.local_issues) { const row = section.createDiv({ cls: "mdbase-conflict-row" }); - const text = row.createDiv(); + const text = row.createDiv({ cls: "mdbase-conflict-summary" }); text.createEl("strong", { text: issue.path }); text.createDiv({ text: issue.message }); const actions = row.createDiv({ cls: "mdbase-actions" }); const open = actions.createEl("button", { text: "Open file" }); + open.setAttr("data-focus-key", `issue-open-${issue.path}`); open.disabled = this.ctx.busy; open.onclick = () => void this.ctx.host.openFileByPath(issue.path); } diff --git a/src/workspaceView.ts b/src/workspaceView.ts index 30c6f92..f1f9f80 100644 --- a/src/workspaceView.ts +++ b/src/workspaceView.ts @@ -105,7 +105,8 @@ export class MdbaseWorkspaceView extends ItemView implements WorkspaceContext { if (this.destination === "sync") this.render(); else this.renderTopbarOnly(); }); - await this.refresh(true); + // Obsidian calls setState after onOpen. Load there, once the restored or + // requested destination is known, rather than scanning Types before Sync. } async onClose(): Promise { @@ -224,6 +225,17 @@ export class MdbaseWorkspaceView extends ItemView implements WorkspaceContext { return changes ? { count: changes, label: `${changes} ${changes === 1 ? "change needs" : "changes need"} review` } : null; } + /** Mobile has no status bar; trouble must remain discoverable outside Sync. */ + private syncTabStatus(): { label: string; detail: string; kind: string } | null { + if (this.destination === "sync" || !this.host.getMirrorProfile()) return null; + const { problem, paused, status, progress, fileProgress } = this.host.sync.state; + if (progress || fileProgress) return null; + const kind = problem?.kind ?? (paused ? "paused" : status?.recovery_required ? "recovery" : null); + if (!kind || kind === "busy") return null; + const labels = { offline: "Offline", auth: "Sign in", device: "Set up", internal: "Error", decision: "Review", recovery: "Review", paused: "Paused" }; + return { kind, label: labels[kind], detail: problem?.title ?? (paused ? "Sync is paused" : "Synchronization needs recovery") }; + } + /** Refresh tab badges without rebuilding the active pane (and losing its focus). */ private renderTopbarOnly(): void { const topbar = this.containerEl.querySelector(".mdbase-topbar"); @@ -324,11 +336,19 @@ export class MdbaseWorkspaceView extends ItemView implements WorkspaceContext { const issueCount = this.host.getIssues().length; const count = button.createSpan({ cls: "mdbase-count", text: compactCount(issueCount) }); count.setAttr("title", `${issueCount} issues`); + button.setAttr("aria-label", `Issues · ${issueCount} validation ${issueCount === 1 ? "issue" : "issues"}`); } + const tabStatus = destination === "sync" ? this.syncTabStatus() : null; const attention = destination === "sync" ? this.syncAttention() : null; - if (attention) { + if (tabStatus) { + const indicator = button.createSpan({ cls: "mdbase-count mdbase-nav-status", text: tabStatus.label }); + indicator.setAttr("data-kind", tabStatus.kind); + indicator.setAttr("title", tabStatus.detail); + button.setAttr("aria-label", `Sync · ${tabStatus.detail}`); + } else if (attention) { const count = button.createSpan({ cls: "mdbase-count", text: compactCount(attention.count) }); count.setAttr("title", attention.label); + button.setAttr("aria-label", `Sync · ${attention.label}`); } button.onclick = () => this.showDestination(destination); button.onkeydown = (event) => { diff --git a/styles.css b/styles.css index b1b18b8..a9b105b 100644 --- a/styles.css +++ b/styles.css @@ -58,6 +58,25 @@ .mdbase-status-bar[data-state="paused"] { color: var(--text-warning); } .mdbase-status-bar[data-state="offline"] { color: var(--text-muted); } +/* Mobile has no status bar: keep trouble discoverable on its existing ribbon. */ +.is-mobile .mdbase-ribbon { position: relative; } + +.is-mobile .mdbase-ribbon[data-state="attention"]::after, +.is-mobile .mdbase-ribbon[data-state="paused"]::after, +.is-mobile .mdbase-ribbon[data-state="offline"]::after { + content: ""; + position: absolute; + top: 3px; + right: 3px; + width: 6px; + height: 6px; + border-radius: 50%; + background: var(--text-warning); + pointer-events: none; +} + +.is-mobile .mdbase-ribbon[data-state="offline"]::after { background: var(--text-muted); } + .mdbase-note-status { cursor: pointer; color: var(--text-muted); @@ -172,6 +191,16 @@ line-height: 16px; } +.mdbase-nav-status { + color: var(--text-warning); + white-space: nowrap; +} + +.mdbase-nav-status[data-kind="offline"], +.mdbase-nav-status[data-kind="paused"] { + color: var(--text-muted); +} + .mdbase-workspace-content { min-height: 0; flex: 1; @@ -2043,6 +2072,7 @@ button.mdbase-match-row:hover { align-items: baseline; gap: 4px 12px; margin-top: 2px; + overflow-wrap: anywhere; } .mdbase-review-reasons { @@ -2056,6 +2086,7 @@ button.mdbase-match-row:hover { align-items: baseline; gap: 4px 12px; font-size: var(--font-ui-small); + overflow-wrap: anywhere; } .mdbase-enrollment-actions { diff --git a/test/binaryLimits.test.ts b/test/binaryLimits.test.ts index 8941808..cf86798 100644 --- a/test/binaryLimits.test.ts +++ b/test/binaryLimits.test.ts @@ -17,7 +17,7 @@ test("oversized local binaries are rejected before the Vault allocates their con }); test("oversized incoming streams never reach a Vault write", async () => { - const adapter = new ObsidianMirrorFileSystem({ getAbstractFileByPath: () => null } as never); + const adapter = new ObsidianMirrorFileSystem({ getAbstractFileByPath: () => null, adapter: { exists: async () => false } } as never); await assert.rejects(adapter.writeBinary("large.mp4", (async function* () { const chunk = new Uint8Array(1024 * 1024); for (let i = 0; i < 33; i++) yield chunk; @@ -29,6 +29,7 @@ test("unload during download prevents materialization after the stream completes let writes = 0; const adapter = new ObsidianMirrorFileSystem({ getAbstractFileByPath: () => null, + adapter: { exists: async () => false }, createBinary: () => { writes++; }, } as never, undefined, () => { if (disposed) throw new Error("unloaded"); }); await assert.rejects(adapter.writeBinary("image.png", (async function* () { diff --git a/test/connectSync.portability.test.ts b/test/connectSync.portability.test.ts new file mode 100644 index 0000000..d80a34c --- /dev/null +++ b/test/connectSync.portability.test.ts @@ -0,0 +1,101 @@ +import * as assert from "node:assert/strict"; +import { test } from "node:test"; +import { TFile, type TAbstractFile } from "obsidian"; +import { ObsidianMirrorFileSystem } from "../src/connectSync"; +import { portablePathKey } from "../src/adoptionPaths"; +import { MemoryVault } from "./memoryVault"; + +/** Exact Obsidian cache spellings, with an APFS-like aliasing disk adapter. */ +class AliasingVault extends MemoryVault { + configDir = ".obsidian"; + constructor() { + super(); + const disk = this.adapter; + const actual = (path: string) => [...this.files.keys(), ...this.binaryFiles.keys(), ...this.folders.keys()] + .find((candidate) => portablePathKey(candidate) === portablePathKey(path)) ?? path; + const adapter = { ...disk, + exists: async (path: string) => disk.exists(actual(path)), + stat: async (path: string) => disk.stat(actual(path)), + readBinary: async (path: string) => disk.readBinary(actual(path)), + list: async (folder: string) => { + const immediate = (path: string) => portablePathKey(path.slice(0, Math.max(0, path.lastIndexOf("/")))) === portablePathKey(folder); + return { files: [...this.files.keys(), ...this.binaryFiles.keys()].filter(immediate), folders: [...this.folders.keys()].filter(immediate) }; + }, + }; + this.adapter = adapter; + } + getAllLoadedFiles(): TAbstractFile[] { return [...this.getFiles(), ...this.folders.values()]; } +} + +test("reserved folder protection includes case and canonical-Unicode aliases", async () => { + const vault = new AliasingVault(); + const fs = new ObsidianMirrorFileSystem(vault as never); + for (const path of [".OBSIDIAN/settings.json", ".MDBASE/connect-role.json", ".GIT/config", ".TRASH/note.md"]) { + await assert.rejects(fs.write(path, "must not write", null), /reserved/); + } + vault.configDir = "Café Config"; + for (const path of ["CAFÉ CONFIG/settings.json", "Cafe\u0301 Config/settings.json"]) { + await assert.rejects(fs.write(path, "must not write", null), /reserved/); + } + assert.equal(vault.getFiles().length, 0); + await vault.create("CAFÉ CONFIG/private.md", "private config"); + await vault.createBinary("Cafe\u0301 Config/icon.png", new Uint8Array([1]).buffer); + assert.deepEqual(await fs.listMarkdown(new Set()), []); + assert.deepEqual(await fs.listBinary(new Set()), []); + await assert.rejects(fs.inspectBinary("CAFÉ CONFIG/icon.png"), /reserved/); + await assert.rejects(fs.writeBinary("Cafe\u0301 Config/icon.png", (async function* () { yield new Uint8Array([2]); })()), /reserved/); +}); + +for (const [source, target] of [["note.md", "Note.md"], ["cafe\u0301.md", "café.md"]]) { + test(`a same-file physical rename ${source} → ${target} is not mistaken for a collision`, async () => { + const vault = new AliasingVault(); + await vault.create(source!, "exact bytes 🥒\n"); + const fs = new ObsidianMirrorFileSystem(vault as never); + await fs.move(source!, target!); + assert.equal(vault.read(target!), "exact bytes 🥒\n"); + assert.deepEqual(vault.getFiles().map((file) => file.path), [target]); + }); +} + +test("a distinct case-sensitive destination is never accepted as the source alias", async () => { + const vault = new AliasingVault(); + await vault.create("note.md", "source\n"); + await vault.create("Note.md", "unrelated destination\n"); + const fs = new ObsidianMirrorFileSystem(vault as never); + await assert.rejects(fs.move("note.md", "Note.md"), /blocks|collision/); + assert.equal(vault.read("note.md"), "source\n"); + assert.equal(vault.read("Note.md"), "unrelated destination\n"); +}); + +test("an uncached distinct case-sensitive destination is not mistaken for the source", async () => { + const vault = new AliasingVault(); + await vault.create("note.md", "source\n"); + await vault.create("Note.md", "uncached destination\n"); + const lookup = vault.getAbstractFileByPath.bind(vault); + vault.getAbstractFileByPath = (path) => path === "Note.md" ? null : lookup(path); + const fs = new ObsidianMirrorFileSystem(vault as never); + await assert.rejects(fs.move("note.md", "Note.md"), /blocks/); + assert.equal(vault.read("note.md"), "source\n"); + assert.equal(vault.read("Note.md"), "uncached destination\n"); +}); + +test("a hosted spelling can conditionally update and remove an aliased cached TFile", async () => { + const vault = new AliasingVault(); + await vault.create("cafe\u0301.md", "before\n"); + const fs = new ObsidianMirrorFileSystem(vault as never); + assert.equal(await fs.read("café.md"), "before\n"); + await fs.write("café.md", "after\n", "before\n"); + assert.equal(vault.read("cafe\u0301.md"), "after\n"); + await fs.remove("CAFÉ.md"); + assert.equal(vault.getFiles().length, 0); +}); + +test("binary inspection and writes use the aliased TFile rather than declaring it absent", async () => { + const vault = new AliasingVault(); + await vault.createBinary("cafe\u0301.png", new Uint8Array([0, 255, 128]).buffer); + const fs = new ObsidianMirrorFileSystem(vault as never); + assert.equal((await fs.inspectBinary("café.png"))?.size, 3); + await fs.writeBinary("café.png", (async function* () { yield new Uint8Array([1, 254]); })()); + assert.deepEqual(vault.readBytes("cafe\u0301.png"), new Uint8Array([1, 254])); + assert.ok(vault.getAbstractFileByPath("cafe\u0301.png") instanceof TFile); +}); diff --git a/test/connectSync.transport.test.ts b/test/connectSync.transport.test.ts index 30070be..f6063dc 100644 --- a/test/connectSync.transport.test.ts +++ b/test/connectSync.transport.test.ts @@ -1,7 +1,8 @@ import * as assert from "node:assert/strict"; import { createHash } from "node:crypto"; import { test } from "node:test"; -import type { CollectionFileDescriptor } from "@mdbase-dev/connect-protocol"; +import type { CollectionFileDescriptor, SyncMutation } from "@mdbase-dev/connect-protocol"; +import { MemoryAuthority } from "@mdbase-dev/connect-sync"; import { ObsidianSyncTransport } from "../src/connectSync"; import { abortableSleep, @@ -119,6 +120,38 @@ test("a mobile request that never answers is abandoned at its deadline", async ( ); }); +test("a mobile response queued during suspension cannot bypass its expired deadline", async () => { + const now = Date.now; + let time = 0; + Date.now = () => time; + let finish!: (value: ReturnType) => void; + const native = new Promise>((resolve) => { finish = resolve; }); + try { + const pending = requestUrlSend({ url: "https://connect.example/probe", timeoutMs: 30_000, throw: false }, () => native); + // Simulate an hour of JS suspension: wall time advances, but neither timeout + // callback nor response continuation has been allowed to run yet. + time += 60 * 60_000; + finish(response(200)); + await assert.rejects(pending, (error: unknown) => error instanceof NetworkError && error.code === "network_timeout"); + } finally { + Date.now = now; + } +}); + +test("fetch also checks elapsed deadline when a queued response beats the resumed timer", async () => { + const now = Date.now; + let time = 0; + Date.now = () => time; + try { + await assert.rejects(fetchSend({ url: "https://connect.example/probe", timeoutMs: 30_000 }, async () => { + time += 60 * 60_000; + return new Response("{}", { status: 200 }); + }), (error: unknown) => error instanceof NetworkError && error.code === "network_timeout"); + } finally { + Date.now = now; + } +}); + test("cancelling sync aborts the request in flight, not after it", async () => { const abort = new AbortController(); const hung = (_input: RequestInfo | URL, init?: RequestInit) => new Promise((_resolve, reject) => { @@ -129,6 +162,46 @@ test("cancelling sync aborts the request in flight, not after it", async () => { await assert.rejects(pending, (error: unknown) => error instanceof DOMException && error.name === "AbortError"); }); +test("an abandoned mobile mutation arriving after its retry has one authority effect", async () => { + const hosted = new MemoryAuthority({ id: authorityId }); + const replicaId = hosted.registerReplica({ name: "Mobile simulation", mode: "read_write" }); + const authority = hosted.transport(replicaId); + const bodies: string[] = []; + let deliverLate!: () => Promise; + const native = async (request: { body?: string | ArrayBuffer }) => { + bodies.push(String(request.body)); + const mutation = JSON.parse(String(request.body)) as SyncMutation; + if (bodies.length === 1) return new Promise>((resolve) => { + deliverLate = async () => { resolve(response(200, await authority.mutate(mutation))); }; + }); + return response(200, await authority.mutate(mutation)); + }; + const send = reliableSend((request) => requestUrlSend({ ...request, timeoutMs: bodies.length === 0 ? 5 : 30_000 }, native), + { ...noSleep, attempts: 2 }); + const transport = new ObsidianSyncTransport(syncUrl, "test-token", send); + const receipt = await transport.mutate({ mutation_id: crypto.randomUUID(), replica_id: replicaId, scope_epoch: 1, + record_id: crypto.randomUUID(), created_at: "2026-10-01T00:00:00.000Z", operation: "put", path: "mobile.md", document: "exact mobile edit\n" }); + assert.equal(receipt.status, "applied"); + await deliverLate(); + await Promise.resolve(); + assert.equal(bodies.length, 2); + assert.equal(bodies[0], bodies[1], "retry preserves the mutation ID and exact document"); + assert.equal(hosted.serialize().head, 1, "late native request does not apply a second write"); + assert.equal(hosted.serialize().records[0]?.document, "exact mobile edit\n"); + assert.equal(receipt.status, "applied", "the late receipt cannot replace the accepted retry receipt"); +}); + +test("an aborted mobile request ignores its eventual native response", async () => { + const abort = new AbortController(); + let finish!: (value: ReturnType) => void; + const native = new Promise>((resolve) => { finish = resolve; }); + const pending = requestUrlSend({ url: "https://connect.example/probe", signal: abort.signal }, () => native); + abort.abort(); + await assert.rejects(pending, (error: unknown) => error instanceof DOMException && error.name === "AbortError"); + finish(response(200)); + await Promise.resolve(); +}); + test("transient failures retry with backoff; client errors do not", async () => { const statuses = [503, 502, 200]; let calls = 0; @@ -257,6 +330,106 @@ test("Obsidian HTTP transport downloads bounded binary parts and cleans up the t ]); }); +test("multipart uploads do not repeatedly copy the whole unconsumed source tail", async () => { + const bytes = new Uint8Array(8 * 1024 * 1024).fill(7); + const file = descriptor("Media/large.png", bytes); + const transferId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; + const partSize = 512 * 1024; + let uploadedBytes = 0; + const send = async (request: { url: string; body?: string | ArrayBuffer }) => { + if (request.url.endsWith("/uploads")) return response(200, { + protocol_version: 1, type: "file_transfer", transfer_id: transferId, + direction: "upload", protection: "transport_tls", total_size: bytes.length, + strategy: { kind: "object_multipart", part_size: partSize }, received: [], uploaded_parts: [], + }); + if (request.url.endsWith("/parts")) { + const part = JSON.parse(String(request.body)) as { part_number: number; content_length: number }; + return response(200, { protocol_version: 1, type: "file_part", transfer_id: transferId, + part_index: part.part_number - 1, offset: (part.part_number - 1) * partSize, + content_length: part.content_length, method: "PUT", url: `https://objects.example/${part.part_number}`, + headers: {}, expires_at: "2099-01-01T00:00:00.000Z" }); + } + if (request.url.startsWith("https://objects.example/")) { + const part = new Uint8Array(request.body as ArrayBuffer); + assert.equal(part.length, partSize); + assert.ok(part.every((byte) => byte === 7)); + uploadedBytes += part.length; + return response(200, {}, new ArrayBuffer(0), { etag: `part-${uploadedBytes}` }); + } + if (request.url.endsWith("/commit")) return response(200, { + protocol_version: 1, type: "file_upload_committed", transfer_id: transferId, file, + }); + throw new Error("unexpected test request"); + }; + const transport = new ObsidianSyncTransport(syncUrl, "test-token", send as never); + const slice = Uint8Array.prototype.slice; + let slicedBytes = 0; + Uint8Array.prototype.slice = function (...args: Parameters) { + const copy = slice.apply(this, args); + slicedBytes += copy.byteLength; + return copy; + }; + try { + await transport.uploadFile({ protocol_version: 1, type: "open_file_upload", transfer_id: transferId, + path: file.path, size: file.size, content_digest: file.content_digest, media_type: file.media_type }, + (async function* () { yield bytes; })()); + } finally { + Uint8Array.prototype.slice = slice; + } + assert.equal(uploadedBytes, bytes.length); + assert.ok(slicedBytes <= bytes.length, `an 8 MB source caused ${slicedBytes / 1024 / 1024} MB of tail copies`); +}); + +test("multipart reads do not copy the entire remaining source chunk for every part", async () => { + const bytes = Uint8Array.from({ length: 256 * 1024 }, (_, index) => index % 251); + const expected = Uint8Array.from(bytes); + const file = descriptor("Media/large.png", bytes); + const partSize = 4 * 1024; + const transferId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; + const uploaded = new Uint8Array(bytes.length); + let parts = 0; + const send = async (request: { url: string; body?: string | ArrayBuffer }) => { + if (request.url.endsWith("/files/uploads")) return response(200, { + protocol_version: 1, type: "file_transfer", transfer_id: transferId, direction: "upload", + protection: "transport_tls", strategy: { kind: "object_multipart", part_size: partSize }, + total_size: file.size, expires_at: "2099-01-01T00:00:00.000Z", received: [], uploaded_parts: [], + }); + if (request.url.endsWith(`/uploads/${transferId}/parts`)) { + const part = JSON.parse(String(request.body)) as { part_number: number; content_length: number }; + const index = part.part_number - 1; + return response(200, { + protocol_version: 1, type: "file_part", transfer_id: transferId, part_index: index, + offset: index * partSize, content_length: part.content_length, method: "PUT", + url: `https://objects.example/part/${index}`, headers: {}, expires_at: "2099-01-01T00:00:00.000Z", + }); + } + if (request.url.startsWith("https://objects.example/part/")) { + uploaded.set(new Uint8Array(request.body as ArrayBuffer), parts * partSize); + return response(200, {}, new ArrayBuffer(0), { etag: `part-${++parts}` }); + } + return response(200, { protocol_version: 1, type: "file_upload_committed", transfer_id: transferId, file }); + }; + const transport = new ObsidianSyncTransport(syncUrl, "fixture-token", send as never); + const slice = Uint8Array.prototype.slice; + let copiedBytes = 0; + Uint8Array.prototype.slice = function (...args: Parameters) { + const result = slice.apply(this, args); + copiedBytes += result.byteLength; + return result; + }; + try { + await transport.uploadFile({ + protocol_version: 1, type: "open_file_upload", transfer_id: transferId, path: file.path, + size: file.size, content_digest: file.content_digest, media_type: file.media_type, + }, (async function* () { yield bytes; bytes.fill(0); })()); + } finally { + Uint8Array.prototype.slice = slice; + } + assert.deepEqual(uploaded, expected, "source reuse must not mutate queued upload bytes"); + assert.equal(parts, file.size / partSize); + assert.ok(copiedBytes <= file.size, `Expected bounded copies, not ${copiedBytes} bytes of sliced tails`); +}); + test("Obsidian HTTP transport uploads exact multipart bytes without forwarding credentials", async () => { const bytes = Uint8Array.of(9, 8, 7, 6, 5); const file = descriptor("Media/upload.png", bytes); diff --git a/test/indexedDb.test.ts b/test/indexedDb.test.ts index ae285a7..eda08cb 100644 --- a/test/indexedDb.test.ts +++ b/test/indexedDb.test.ts @@ -1,9 +1,135 @@ import "fake-indexeddb/auto"; +import { forceCloseDatabase } from "fake-indexeddb"; import assert from "node:assert/strict"; import test from "node:test"; import { IndexedDbMirrorBlobStore, IndexedDbMirrorStateStore } from "../src/connectSync"; import type { MirrorState } from "@mdbase-dev/connect-sync/mirror"; +type CheckpointStore = IndexedDbMirrorStateStore & { + readCheckpoint(): Promise<{ cursor: number; scope_epoch: number; recovery_required: boolean } | null>; +}; + +test("change probes read only the tiny checkpoint summary, not 20k stored records", async () => { + const key = crypto.randomUUID(); + const store = new IndexedDbMirrorStateStore(key) as CheckpointStore; + const state = { + replica_id: key, cursor: 12, scope_epoch: 7, + records: Object.fromEntries(Array.from({ length: 20_000 }, (_, index) => [String(index), { + path: `${index}.md`, revision: "revision", hash: "hash", record: { document: "Generated body. ".repeat(40) }, + }])), + } as unknown as MirrorState; + await store.write(state); + const get = IDBObjectStore.prototype.get; + let fullReads = 0; + IDBObjectStore.prototype.get = function (requested) { + if (requested === key) fullReads++; + return get.call(this, requested); + }; + try { + for (let index = 0; index < 20; index++) assert.deepEqual(await store.readCheckpoint(), { + cursor: 12, scope_epoch: 7, recovery_required: false, + }); + assert.equal(fullReads, 0, "polling must not structured-clone the stored documents"); + } finally { + IDBObjectStore.prototype.get = get; + } + await store.write({ ...state, cursor: 13, scope_epoch: 8, batch: { phase: "prepared" } } as MirrorState); + assert.deepEqual(await store.readCheckpoint(), { cursor: 13, scope_epoch: 8, recovery_required: true }); + await store.clear(); + assert.equal(await store.readCheckpoint(), null); + assert.equal(await store.read(), null); + store.close(); +}); + +test("probe summaries observe another adapter's atomic write and clear, not a cached cursor", async () => { + const key = crypto.randomUUID(); + const reader = new IndexedDbMirrorStateStore(key) as CheckpointStore; + const writer = new IndexedDbMirrorStateStore(key); + await reader.write({ cursor: 1, scope_epoch: 2, records: {} } as MirrorState); + assert.deepEqual(await reader.readCheckpoint(), { cursor: 1, scope_epoch: 2, recovery_required: false }); + await writer.write({ cursor: 3, scope_epoch: 4, records: {}, batch: { phase: "prepared" } } as MirrorState); + assert.deepEqual(await reader.readCheckpoint(), { cursor: 3, scope_epoch: 4, recovery_required: true }); + await writer.clear(); + assert.equal(await reader.readCheckpoint(), null); + reader.close(); + writer.close(); +}); + +test("a reopened adapter repairs summaries left stale or missing by older plugins once", async () => { + const key = crypto.randomUUID(); + const original = new IndexedDbMirrorStateStore(key); + await original.write({ cursor: 1, scope_epoch: 2, records: {} } as MirrorState); + original.close(); + // Older versions write only the string-keyed full state, leaving a stale summary. + const database = await new Promise((resolve, reject) => { + const request = indexedDB.open("mdbase-obsidian-connect", 1); + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + }); + await new Promise((resolve, reject) => { + const transaction = database.transaction("mirrors", "readwrite"); + transaction.objectStore("mirrors").put({ cursor: 9, scope_epoch: 10, records: {} }, key); + transaction.oncomplete = () => resolve(); + transaction.onabort = () => reject(transaction.error); + }); + database.close(); + const store = new IndexedDbMirrorStateStore(key) as CheckpointStore; + const get = IDBObjectStore.prototype.get; + let fullReads = 0; + IDBObjectStore.prototype.get = function (requested) { + if (requested === key) fullReads++; + return get.call(this, requested); + }; + try { + assert.deepEqual(await store.readCheckpoint(), { cursor: 9, scope_epoch: 10, recovery_required: false }); + assert.deepEqual(await store.readCheckpoint(), { cursor: 9, scope_epoch: 10, recovery_required: false }); + assert.equal(fullReads, 1, "legacy reconciliation happens once, not on every poll"); + } finally { + IDBObjectStore.prototype.get = get; + store.close(); + } +}); + +test("a summary write failure rolls back both state and its probe checkpoint", async () => { + const store = new IndexedDbMirrorStateStore(crypto.randomUUID()) as CheckpointStore; + const before = { cursor: 1, scope_epoch: 2, records: {} } as MirrorState; + await store.write(before); + const put = IDBObjectStore.prototype.put; + IDBObjectStore.prototype.put = function (...args: Parameters) { + const request = put.apply(this, args); + if (Array.isArray(args[1])) this.transaction.abort(); + return request; + }; + try { + await assert.rejects(store.write({ ...before, cursor: 3, scope_epoch: 4 })); + } finally { + IDBObjectStore.prototype.put = put; + } + assert.deepEqual(await store.read(), before); + assert.deepEqual(await store.readCheckpoint(), { cursor: 1, scope_epoch: 2, recovery_required: false }); + store.close(); +}); + +test("a summary clear failure cannot leave state and probe metadata disagreeing", async () => { + const store = new IndexedDbMirrorStateStore(crypto.randomUUID()) as CheckpointStore; + const before = { cursor: 1, scope_epoch: 2, records: {} } as MirrorState; + await store.write(before); + const remove = IDBObjectStore.prototype.delete; + IDBObjectStore.prototype.delete = function (key) { + const request = remove.call(this, key); + if (Array.isArray(key)) this.transaction.abort(); + return request; + }; + try { + await assert.rejects(store.clear()); + } finally { + IDBObjectStore.prototype.delete = remove; + } + assert.deepEqual(await store.read(), before); + assert.deepEqual(await store.readCheckpoint(), { cursor: 1, scope_epoch: 2, recovery_required: false }); + store.close(); +}); + test("aborted IndexedDB writes reject without replacing the last durable checkpoint", async () => { const key = crypto.randomUUID(); const store = new IndexedDbMirrorStateStore(key); @@ -50,6 +176,37 @@ test("a transient IndexedDB open failure does not poison either adapter forever" } }); +test("a connection closed while the app was suspended is reopened without losing checkpoints or blobs", async () => { + const key = crypto.randomUUID(); + const stateStore = new IndexedDbMirrorStateStore(key); + const blobStore = new IndexedDbMirrorBlobStore(key); + const state = { replica_id: key, generation: 7 } as MirrorState; + const connections = new Set(); + const transaction = IDBDatabase.prototype.transaction; + IDBDatabase.prototype.transaction = function (...args: Parameters) { + connections.add(this); + return transaction.apply(this, args); + }; + try { + await stateStore.write(state); + await blobStore.write(digest, bytes()); + } finally { + IDBDatabase.prototype.transaction = transaction; + } + // fake-indexeddb's declaration incorrectly names the constructor type here; + // the implementation accepts the live database instance. + await Promise.all([...connections].map((database) => new Promise((resolve) => { + database.addEventListener("close", () => resolve(), { once: true }); + forceCloseDatabase(database as unknown as Parameters[0]); + }))); + assert.deepEqual(await stateStore.read(), state); + const result: number[] = []; + for await (const chunk of blobStore.read(digest)) result.push(...chunk); + assert.deepEqual(result, [0, 1, 255]); + stateStore.close(); + blobStore.close(); +}); + test("old binary-stage cleanup failure cannot corrupt a published replacement", async () => { const store = new IndexedDbMirrorBlobStore(crypto.randomUUID()); await store.write(digest, bytes()); @@ -84,6 +241,24 @@ test("IndexedDB checkpoint survives adapter recreation and isolates replicas", a assert.equal(await new IndexedDbMirrorStateStore(key).read(), null); }); +test("binary staging tolerates suspended sources without keeping an IndexedDB transaction alive", async () => { + const store = new IndexedDbMirrorBlobStore(crypto.randomUUID()); + await store.write(digest, (async function* () { + yield Uint8Array.of(0, 1); + // IndexedDB auto-commits transactions across event-loop turns. A mobile + // source can take far longer; each chunk must use a fresh short transaction. + await new Promise((resolve) => setImmediate(resolve)); + yield Uint8Array.of(255); + })()); + const result: number[] = []; + for await (const chunk of store.read(digest)) { + result.push(...chunk); + await new Promise((resolve) => setImmediate(resolve)); + } + assert.deepEqual(result, [0, 1, 255]); + store.close(); +}); + test("IndexedDB binary snapshot survives restart and an interrupted replacement", async () => { const key = crypto.randomUUID(); const store = new IndexedDbMirrorBlobStore(key); diff --git a/test/main.syncEvents.test.ts b/test/main.syncEvents.test.ts new file mode 100644 index 0000000..72f6801 --- /dev/null +++ b/test/main.syncEvents.test.ts @@ -0,0 +1,91 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { TFile, TFolder } from "obsidian"; +import MdbasePlugin from "../main"; +import { MemoryVault, TestFolder } from "./memoryVault"; + +function fixture() { + const vault = new MemoryVault(); + const handlers = new Map void>(); + const plugin = new MdbasePlugin({ + vault: Object.assign(vault, { + configDir: ".obsidian", + on: (event: string, callback: (file: TFile | TFolder, oldPath?: string) => void) => { handlers.set(event, callback); }, + }), + workspace: { getLeavesOfType: () => [] }, + } as never, { id: "mdbase", version: "test" } as never); + plugin.settings = { + autoSync: true, validateOnSave: false, validateOnOpen: false, showNoticeOnSave: false, interopEnabled: false, + typeDrafts: {}, archivedTypeDrafts: [], + mirrorProfile: { version: 1, collectionId: "c", replicaId: "r", enrollmentId: "e", mode: "read_write", name: "Notes", syncUrl: "https://example.com", controlUrl: "https://example.com", accessTokenExpiresAt: "2099-01-01" }, + }; + let observed = 0; + let scheduled = 0; + plugin.sync = { observeLocalChange: () => { observed++; } } as never; + const internal = plugin as unknown as { + registerVaultEvents(): void; + syncScheduler: { noteLocalChange(): void }; + recordCache: Map | null; + recordList: unknown[] | null; + }; + internal.syncScheduler = { noteLocalChange: () => { scheduled++; } }; + internal.registerVaultEvents(); + return { plugin, internal, handlers, observed: () => observed, scheduled: () => scheduled }; +} + +test("folder-only rename events schedule sync and invalidate cached descendant records", () => { + const f = fixture(); + f.internal.recordCache = new Map([["Old/note.md", { path: "Old/note.md" }]]); + f.internal.recordList = [{ path: "Old/note.md" }]; + f.handlers.get("rename")!(new TestFolder("New"), "Old"); + assert.ok(f.observed() > 0, "folder events must not be dropped when Obsidian emits no child events"); + assert.ok(f.scheduled() > 0); + assert.equal(f.internal.recordCache, null); + assert.equal(f.internal.recordList, null); + f.plugin.connectSync.dispose(); +}); + +test("malformed settings versions cannot silently retain the pre-automatic-sync default", async () => { + for (const version of [null, "bad", "2", {}, [], -1, 1.5, NaN]) { + const f = fixture(); + f.plugin.loadData = async () => ({ autoSync: false, syncSettingsVersion: version }); + await f.plugin.loadSettings(); + assert.equal(f.plugin.settings.autoSync, true, `malformed version ${JSON.stringify(version)} migrates safely`); + assert.equal(f.plugin.settings.syncSettingsVersion, 2); + f.plugin.connectSync.dispose(); + } +}); + +test("automatic sync normalizes corrupt booleans but respects an explicit version-2 opt-out", async () => { + for (const autoSync of [null, "false", 0, {}, undefined, false]) { + const f = fixture(); + f.plugin.loadData = async () => ({ autoSync, syncSettingsVersion: 2 }); + await f.plugin.loadSettings(); + assert.equal(f.plugin.settings.autoSync, autoSync === false ? false : true); + f.plugin.connectSync.dispose(); + } +}); + +test("paused sync takes precedence over a previous offline problem in scheduler wiring", () => { + const f = fixture(); + f.plugin.sync = { state: { paused: true, problem: { kind: "offline" } } } as never; + const internal = f.plugin as unknown as { + startSyncScheduler(): void; + syncScheduler: { host: { problemKind(): string | null }; stop(): void }; + }; + internal.startSyncScheduler(); + // Clear the real timer immediately; this is a wiring test, not a live sync. + internal.syncScheduler.stop(); + assert.equal(internal.syncScheduler.host.problemKind(), "paused"); + f.plugin.connectSync.dispose(); +}); + +test("folder-only deletion events schedule sync while reserved folders stay ignored", () => { + const f = fixture(); + f.handlers.get("delete")!(new TestFolder("Notes")); + assert.ok(f.scheduled() > 0); + const before = f.scheduled(); + f.handlers.get("delete")!(new TestFolder(".obsidian")); + assert.equal(f.scheduled(), before); + f.plugin.connectSync.dispose(); +}); diff --git a/test/mobileIndicators.test.ts b/test/mobileIndicators.test.ts new file mode 100644 index 0000000..007a3a9 --- /dev/null +++ b/test/mobileIndicators.test.ts @@ -0,0 +1,68 @@ +import * as assert from "node:assert/strict"; +import { test } from "node:test"; +import { JSDOM } from "jsdom"; +import { Platform } from "obsidian"; +import MdbasePlugin from "../main"; +import type { SyncIndicator } from "../src/syncUx"; + +function fixture(state: SyncIndicator["state"]) { + const dom = new JSDOM(""); + const ribbon = dom.window.document.getElementById("ribbon") as unknown as HTMLElement; + ribbon.setAttr = (name, value) => ribbon.setAttribute(name, String(value)); + const calls: string[] = []; + const indicator: SyncIndicator = { state, label: `mdbase: ${state}`, detail: `Sync is ${state}`, destination: "sync" }; + const plugin = Object.assign(Object.create(MdbasePlugin.prototype) as { + updateStatusBar(): void; onRibbonClick(): Promise; + }, { + ribbonEl: ribbon, + statusBarEl: undefined, + noteStatusEl: undefined, + getIssues: () => [], + syncIndicator: () => indicator, + updateNoteStatus: async () => undefined, + openWorkspace: async () => { calls.push("types"); }, + openStatusDestination: async () => { calls.push("sync"); }, + }); + return { plugin, ribbon, calls, dom }; +} + +test("mobile ribbon reports sync state even without a status bar", () => { + const previous = Platform.isMobile; + Platform.isMobile = true; + try { + const f = fixture("offline"); + f.plugin.updateStatusBar(); + assert.equal(f.ribbon.getAttribute("data-state"), "offline"); + assert.match(f.ribbon.getAttribute("aria-label") ?? "", /offline/i); + assert.match(f.ribbon.getAttribute("title") ?? "", /offline/i); + f.dom.window.close(); + } finally { Platform.isMobile = previous; } +}); + +test("mobile ribbon opens pending sync instead of making the person hunt behind Types", async () => { + const previous = Platform.isMobile; + Platform.isMobile = true; + try { + for (const state of ["offline", "paused", "attention", "syncing", "waiting"] as const) { + const f = fixture(state); + await f.plugin.onRibbonClick(); + assert.deepEqual(f.calls, ["sync"], state); + f.dom.window.close(); + } + const settled = fixture("synced"); + await settled.plugin.onRibbonClick(); + assert.deepEqual(settled.calls, ["types"], "settled sync keeps Types as the primary surface"); + settled.dom.window.close(); + } finally { Platform.isMobile = previous; } +}); + +test("desktop ribbon retains its Types destination when the status bar can handle sync", async () => { + const previous = Platform.isMobile; + Platform.isMobile = false; + try { + const f = fixture("offline"); + await f.plugin.onRibbonClick(); + assert.deepEqual(f.calls, ["types"]); + f.dom.window.close(); + } finally { Platform.isMobile = previous; } +}); diff --git a/test/obsidian-mock.cjs b/test/obsidian-mock.cjs index 469f802..6e33de2 100644 --- a/test/obsidian-mock.cjs +++ b/test/obsidian-mock.cjs @@ -57,6 +57,15 @@ class TFolder { } class Vault {} +class Plugin { + constructor(app, manifest) { this.app = app; this.manifest = manifest; } + registerEvent() {} + registerDomEvent() {} +} +class FileSystemAdapter {} +class MarkdownView {} +const apiVersion = "1.12.0"; +function addIcon() {} class ItemView { constructor(leaf) { @@ -149,6 +158,7 @@ async function requestUrl() { throw new Error("requestUrl is not configured in this unit test."); } + module.exports = { normalizePath, getFrontMatterInfo, @@ -157,6 +167,11 @@ module.exports = { TFile, TFolder, Vault, + Plugin, + FileSystemAdapter, + MarkdownView, + apiVersion, + addIcon, ItemView, Menu, Modal, diff --git a/test/pathGlob.test.ts b/test/pathGlob.test.ts new file mode 100644 index 0000000..158dd72 --- /dev/null +++ b/test/pathGlob.test.ts @@ -0,0 +1,49 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { portableGlobMatch } from "../src/pathGlob"; + +test("wildcard matching does not recursively copy exponentially many suffixes", () => { + const slice = Array.prototype.slice; + let copies = 0; + Array.prototype.slice = function(start?: number, end?: number) { + copies++; + return slice.call(this, start, end); + }; + try { + assert.equal(portableGlobMatch("*a".repeat(8) + "b", "a".repeat(14)), false); + assert.equal(portableGlobMatch("**/".repeat(8) + "missing", "a/".repeat(14) + "last"), false); + } finally { + Array.prototype.slice = slice; + } + assert.ok(copies < 1_000, `Expected bounded matching, not ${copies} copied suffixes`); +}); + +test("long literal patterns do not consume the JavaScript call stack", () => { + const path = "🙂".repeat(20_000); + assert.equal(portableGlobMatch("?".repeat(20_000), path), true); + assert.equal(portableGlobMatch("*".repeat(20_000) + "b", path), false); +}); + +test("portable wildcards retain Unicode, class and whole-component semantics", () => { + for (const [pattern, path, matches] of [ + ["notes/**/*.md", "notes/a.md", true], + ["notes/**/*.md", "notes/a/b.md", true], + ["notes/*.md", "notes/a/b.md", false], + ["*.md", "note.MD", false], + ["a?", "a🙂", true], + ["a?", "aé", false], + ["[😀-🙏]", "🙁", true], + ["[!a-c]", "b", false], + ["[!a-c]", "🙂", true], + ["[z-a]", "m", false], + ["[!z-a]", "m", true], + ["[]a]", "]", true], + ["[a", "[a", true], + ["[]", "[]", true], + ["[!]", "[!]", true], + ["**/**/a/**", "a", true], + ["ab**cd", "ab/x/cd", false], + ["ab**cd", "abXXXcd", true], + ["", "", true], + ] as const) assert.equal(portableGlobMatch(pattern, path), matches, `${pattern} against ${path}`); +}); diff --git a/test/syncHistory.test.ts b/test/syncHistory.test.ts index 1a0131d..e1dd520 100644 --- a/test/syncHistory.test.ts +++ b/test/syncHistory.test.ts @@ -191,6 +191,27 @@ class MemoryAdapter implements HistoryAdapter { } } +test("loading intact large history does not stringify every transfer again", async () => { + const adapter = new MemoryAdapter(); + const recent = new Date().toISOString(); + const large = run("initial-download", recent, Array.from({ length: 50_000 }, (_, index) => `${index}.md`)); + adapter.files.set("history.jsonl", `${JSON.stringify(large)}\n`); + const store = new SyncHistoryStore(adapter, "history.jsonl"); + const stringify = JSON.stringify; + let serializations = 0; + JSON.stringify = ((...args: Parameters) => { + serializations++; + return stringify(...args); + }) as typeof JSON.stringify; + try { + await store.load(); + } finally { + JSON.stringify = stringify; + } + assert.equal(store.list()[0].files.length, 50_000); + assert.equal(serializations, 0, "valid unpruned history only needs parsing, not a second full serialization"); +}); + test("the store appends one line per run, filters by collection and survives a reload", async () => { const adapter = new MemoryAdapter(); const recent = new Date().toISOString(); diff --git a/test/syncReliability.test.ts b/test/syncReliability.test.ts index a04728e..6be7ef8 100644 --- a/test/syncReliability.test.ts +++ b/test/syncReliability.test.ts @@ -4,13 +4,15 @@ import { test } from "node:test"; import type { TFile } from "obsidian"; import { MemoryAuthority, type SyncTransport } from "@mdbase-dev/connect-sync"; import { + DirectoryMirror, MemoryMirrorBlobStore, MemoryMirrorStateStore, + type MirrorBinaryInfo, type MirrorState, WritableDirectoryMirror, } from "@mdbase-dev/connect-sync/mirror"; import type { MirrorEnrollmentClient } from "@mdbase-dev/connect-sync/enrollment"; -import { ConnectSyncController, normalizeMirrorProfile, ObsidianMirrorFileSystem, type MirrorProfile } from "../src/connectSync"; +import { ConnectSyncController, DeviceMirrorLease, normalizeMirrorProfile, ObsidianMirrorFileSystem, type MirrorProfile } from "../src/connectSync"; import { MemoryVault } from "./memoryVault"; import { SyncSession } from "../src/syncSession"; @@ -91,6 +93,35 @@ async function device(hosted: MemoryAuthority, collectionId: string, options: De return { vault, controller, state, states, secrets, replicaId, profile: () => profile, syncOnce }; } +test("the remote change probe uses the state store's lean checkpoint port", async () => { + class ProbeState extends MemoryMirrorStateStore { + reads = 0; + checkpoint: { cursor: number; scope_epoch: number; recovery_required: boolean } | null = { + cursor: 0, scope_epoch: 1, recovery_required: false, + }; + override async read(): Promise { + this.reads++; + throw new Error("A probe must not read the full state"); + } + async readCheckpoint() { return this.checkpoint; } + } + const hosted = new MemoryAuthority(); + const state = new ProbeState(); + let changes = 0; + const here = await device(hosted, hosted.collectionId, { state, wrapTransport: transport => ({ + ...transport, changes: async (...args) => { changes++; return transport.changes(...args); }, + }) }); + assert.equal(await here.controller.remoteChangesWaiting(), false); + assert.equal(state.reads, 0); + assert.equal(changes, 1); + state.checkpoint!.recovery_required = true; + assert.equal(await here.controller.remoteChangesWaiting(), true, "a prepared batch must recover without probing Connect"); + state.checkpoint = null; + assert.equal(await here.controller.remoteChangesWaiting(), true, "an uninitialized mirror always has work"); + assert.equal(changes, 1); + here.controller.dispose(); +}); + /** A second device that edits through the bare SDK engine. */ function otherDevice(hosted: MemoryAuthority) { const replica = hosted.registerReplica({ name: "Other", mode: "read_write" }); @@ -375,6 +406,175 @@ test("a binary file created during a download is not silently overwritten", asyn assert.deepEqual(vault.readBytes("photo.png"), new Uint8Array([7, 8, 9])); }); +test("SDK binary preflight expectations protect a file created before adapter materialization", async () => { + const hosted = new MemoryAuthority(); + const replica = hosted.registerReplica({ name: "Binary reader", mode: "read_only" }); + const base = hosted.transport(replica); + const bytes = Uint8Array.of(4, 5, 6); + const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)); + const digest = `sha256:${Array.from(hash, (value) => value.toString(16).padStart(2, "0")).join("")}` as const; + const file = { + file_id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", path: "photo.png", revision: digest, + content_digest: digest, size: bytes.byteLength, media_class: "image" as const, + modified_at: "2026-01-01T00:00:00.000Z", + }; + const vault = new MemoryVault(); + class RacyFileSystem extends ObsidianMirrorFileSystem { + override async writeBinary(path: string, source: AsyncIterable, expected?: MirrorBinaryInfo | null): Promise { + await vault.createBinary(path, Uint8Array.of(7, 8, 9).buffer); + return super.writeBinary(path, source, expected); + } + } + const mirror = new DirectoryMirror(replica, { + ...base, + fileSnapshot: async (snapshotId, page) => ({ ...await base.fileSnapshot(snapshotId, page), files: [file] }), + downloadFile: async function* () { yield bytes; }, + }, { + fileSystem: new RacyFileSystem(vault as never), stateStore: new MemoryMirrorStateStore(), + blobStore: new MemoryMirrorBlobStore(), selectiveSync: { file_classes: ["image"], excluded_folders: [] }, + }); + const outcome = await mirror.apply(await mirror.inspect()); + assert.equal(outcome.status, "stale"); + assert.deepEqual(vault.readBytes("photo.png"), Uint8Array.of(7, 8, 9)); +}); + +test("SDK delete preflight expectations protect an edit made before adapter removal", async () => { + const hosted = new MemoryAuthority(); + hosted.seed([{ record_id: "a", path: "a.md", frontmatter: {}, body: "base\n", types: [] }]); + const replica = hosted.registerReplica({ name: "Reader", mode: "read_only" }); + const vault = new MemoryVault(); + class RacyFileSystem extends ObsidianMirrorFileSystem { + override async remove(path: string, expected?: string | MirrorBinaryInfo | null): Promise { + await edit(vault, path, "edited before trash\n"); + return super.remove(path, expected); + } + } + const mirror = new DirectoryMirror(replica, hosted.transport(replica), { + fileSystem: new RacyFileSystem(vault as never), stateStore: new MemoryMirrorStateStore(), + }); + await mirror.sync(); + const there = otherDevice(hosted); + await there.mirror.sync(); + await there.vault.delete(there.vault.getAbstractFileByPath("a.md") as TFile); + await there.mirror.sync(); + const outcome = await mirror.apply(await mirror.inspect()); + assert.equal(outcome.status, "stale"); + assert.equal(vault.read("a.md"), "edited before trash\n"); +}); + +test("conditional binary removal refuses changed bytes and still trashes an exact file", async () => { + const vault = new MemoryVault(); + const file = await vault.createBinary("photo.png", Uint8Array.of(1, 2, 3).buffer); + const fs = new ObsidianMirrorFileSystem(vault as never); + const expected = await fs.inspectBinary("photo.png"); + await vault.modifyBinary(file, Uint8Array.of(7, 8, 9).buffer); + await assert.rejects(fs.remove("photo.png", expected), (error: unknown) => + (error as { code?: string }).code === "sync_plan_stale"); + assert.deepEqual(vault.readBytes("photo.png"), Uint8Array.of(7, 8, 9)); + await fs.remove("photo.png", await fs.inspectBinary("photo.png")); + assert.equal(vault.readBytes("photo.png"), null); +}); + +test("a hosted deletion conflict decision cannot discard an edit made just before trash", async () => { + const hosted = new MemoryAuthority(); + hosted.seed([{ record_id: "a", path: "a.md", frontmatter: {}, body: "base\n", types: [] }]); + const replica = hosted.registerReplica({ name: "Writer", mode: "read_write" }); + const vault = new MemoryVault(); + let race = false; + class RacyFileSystem extends ObsidianMirrorFileSystem { + override async remove(path: string, expected?: string | MirrorBinaryInfo | null): Promise { + if (race) await edit(vault, path, "newer local edit\n"); + return super.remove(path, expected); + } + } + const mirror = new WritableDirectoryMirror(replica, hosted.transport(replica), { + fileSystem: new RacyFileSystem(vault as never), stateStore: new MemoryMirrorStateStore(), + }); + await mirror.sync(); + const there = otherDevice(hosted); + await there.mirror.sync(); + await there.vault.delete(there.vault.getAbstractFileByPath("a.md") as TFile); + await there.mirror.sync(); + await edit(vault, "a.md", "local edit\n"); + await mirror.sync(); + const conflict = (await mirror.status()).conflicts[0]!; + assert.ok(conflict); + race = true; + await assert.rejects(mirror.resolveConflict(conflict.object_id, conflict.decision_id, "remote"), (error: unknown) => + ["sync_plan_stale", "conflict_decision_stale"].includes((error as { code: string }).code)); + assert.equal(vault.read("a.md"), "newer local edit\n"); +}); + +test("independently loaded plugin windows share a browser mirror lease", async () => { + const descriptor = Object.getOwnPropertyDescriptor(globalThis, "navigator"); + const held = new Set(); + Object.defineProperty(globalThis, "navigator", { configurable: true, value: { locks: { + request: async (name: string, _options: unknown, callback: (lock: object | null) => Promise) => { + if (held.has(name)) return callback(null); + held.add(name); + try { return await callback({ name }); } finally { held.delete(name); } + }, + } } }); + const moduleUrl = new URL("../src/connectSync.js", import.meta.url); + moduleUrl.search = "?second-window"; + const other = await import(moduleUrl.href) as typeof import("../src/connectSync"); + const key = crypto.randomUUID(); + const first = new DeviceMirrorLease(key); + const second = new other.DeviceMirrorLease(key); + const gate = deferred(); + const running = first.runExclusive(() => gate.promise); + try { + await assert.rejects(second.runExclusive(async () => "concurrent writer"), (error: unknown) => + (error as { code?: string }).code === "mirror_busy"); + gate.release(); + await running; + assert.equal(await second.runExclusive(async () => "released"), "released"); + } finally { + gate.release(); + await running; + if (descriptor) Object.defineProperty(globalThis, "navigator", descriptor); + else Reflect.deleteProperty(globalThis, "navigator"); + } +}); + +test("disconnect cannot retire a mirror while another controller holds its SDK lease", async () => { + const hosted = new MemoryAuthority(); + const id = await collectionId(hosted); + const entered = deferred(); + const gate = deferred(); + const here = await device(hosted, id, { + wrapTransport: (transport) => ({ ...transport, openSession: async () => { + entered.release(); + await gate.promise; + return transport.openSession(); + } }), + }); + const running = here.controller.inspect(); + await entered.promise; + let otherProfile = structuredClone(here.profile()); + const other = new ConnectSyncController({ vault: here.vault, secretStorage: here.secrets } as never, { + getMirrorProfile: () => otherProfile, + saveMirrorProfile: async (next) => { otherProfile = next; }, + deviceId: () => "this-device", + }, { + stateStoreFactory: () => here.state, blobStoreFactory: () => new MemoryMirrorBlobStore(), + fileSystem: new ObsidianMirrorFileSystem(here.vault as never), + transportFactory: () => hosted.transport(here.replicaId), + }); + try { + await assert.rejects(other.disconnect(false), (error: unknown) => (error as { code?: string }).code === "mirror_busy"); + assert.ok(otherProfile); + assert.equal(await here.vault.adapter.exists(".mdbase/connect-role.json"), true); + } finally { + gate.release(); + await running; + } + await other.disconnect(false); + assert.equal(otherProfile, null); + here.controller.dispose(); + other.dispose(); +}); + test("a vault copied to another device or folder refuses to sync until it is set up there", async () => { const hosted = new MemoryAuthority(); hosted.seed([{ record_id: "a", path: "a.md", frontmatter: {}, body: "a\n", types: [] }]); diff --git a/test/syncScheduler.test.ts b/test/syncScheduler.test.ts index ff9426c..a02b8dc 100644 --- a/test/syncScheduler.test.ts +++ b/test/syncScheduler.test.ts @@ -8,11 +8,12 @@ import { NetworkError } from "../src/syncHttp"; /** A clock whose timers fire only when the test advances time. */ class FakeClock implements SchedulerClock { time = 0; + wallOffset = 0; private nextId = 1; private readonly timers = new Map void }>(); now(): number { - return this.time; + return this.time + this.wallOffset; } setTimeout(callback: () => void, ms: number): number { @@ -36,7 +37,9 @@ class FakeClock implements SchedulerClock { const due = [...this.timers.entries()].filter(([, timer]) => timer.at <= end).sort((a, b) => a[1].at - b[1].at)[0]; if (!due) break; this.timers.delete(due[0]); - this.time = due[1].at; + // An overdue timer after app suspension fires at resume time, never by + // rewinding the wall clock to when it would have fired in the background. + this.time = Math.max(this.time, due[1].at); due[1].callback(); for (let i = 0; i < 10; i++) await Promise.resolve(); } @@ -157,6 +160,29 @@ test("offline backoff is not shortened by the ordinary probe timer", async () => assert.equal(h.retryAt()! - h.clock.now(), SYNC_TIMING.retryMaxMs); }); +test("a backwards wall clock cannot extend the continuous-edit maximum wait", async () => { + const h = harness(); + h.scheduler.start(); + await h.clock.advance(0); + h.scheduler.noteLocalChange(); + await h.clock.advance(1_000); + h.clock.wallOffset -= 60 * 60_000; + for (let i = 0; i < 21; i++) { + h.scheduler.noteLocalChange(); + await h.clock.advance(1_000); + } + assert.ok(h.calls.autoSync >= 2, "sync must not wait an hour for the old edit timestamp to catch up"); +}); + +test("a backwards wall clock cannot postpone the safety net until it catches up", async () => { + const h = harness(); + h.scheduler.start(); + await h.clock.advance(0); + h.clock.wallOffset -= 60 * 60_000; + await h.clock.advance(SYNC_TIMING.probeVisibleMs); + assert.equal(h.calls.autoSync, 2, "a backwards timestamp needs a new baseline, not a suppressed safety net"); +}); + test("an unreachable probe counts as offline and is retried with backoff", async () => { const h = harness({ remoteChangesWaiting: async () => { @@ -222,6 +248,49 @@ test("turning automatic sync back on syncs edits already observed while it was o assert.equal(h.calls.autoSync, 1, "enabling automatic sync catches up without needing another edit"); }); +test("an hour-long mobile freeze expires retryAt without replaying every missed interval", async () => { + const h = harness(); + h.setResult("failed"); + h.setProblem("offline"); + h.scheduler.start(); + await h.clock.advance(0); + h.scheduler.noteVisibility(false); + const oldRetry = h.retryAt()!; + h.clock.time += 60 * 60_000; // JS/timers frozen while wall time advances. + assert.ok(oldRetry < h.clock.now()); + h.setResult("applied"); + h.setProblem(null); + h.scheduler.noteVisibility(true); + await h.clock.advance(0); + assert.equal(h.calls.autoSync, 2, "one catch-up, not all missed retries/probes"); + assert.equal(h.retryAt(), null); + await h.clock.advance(SYNC_TIMING.probeVisibleMs); + assert.equal(h.calls.autoSync, 2, "the successful catch-up restarts the normal cadence"); +}); + +test("foregrounding an in-flight mobile run coalesces one follow-up after thaw", async () => { + let release!: () => void; + let runs = 0; + const h = harness({ autoSync: async () => { + runs += 1; + if (runs === 1) await new Promise((resolve) => { release = resolve; }); + return "applied"; + } }); + h.scheduler.start(); + await h.clock.advance(0); + h.scheduler.noteVisibility(false); + h.clock.time += 60 * 60_000; + h.scheduler.noteVisibility(true); + await h.clock.advance(0); + assert.equal(runs, 1, "the original in-flight operation is not duplicated"); + release(); + for (let i = 0; i < 10; i++) await Promise.resolve(); + await h.clock.advance(0); + assert.equal(runs, 2, "one foreground catch-up follows completion"); + await h.clock.advance(0); + assert.equal(runs, 2); +}); + test("with automatic sync off, the scheduler only keeps status fresh", async () => { const h = harness({ automatic: () => false }); h.scheduler.start(); diff --git a/test/syncUx.test.ts b/test/syncUx.test.ts index c8dbb87..0b60ba1 100644 --- a/test/syncUx.test.ts +++ b/test/syncUx.test.ts @@ -111,6 +111,15 @@ test("sync indicator gives transfer, attention, waiting, and synced states stabl assert.match(transferring.detail, /large\.bin/); }); +test("an explicit pause cannot claim Synced just because the last checkpoint is healthy", () => { + const base = { connected: true, status: status(), progress: null, fileProgress: null, problem: null, validationIssues: 0, localChangeObserved: false, paused: true }; + const indicator = syncIndicator(base); + assert.equal(indicator.state, "paused"); + assert.equal(indicator.label, "mdbase: Paused"); + assert.match(indicator.detail, /resume/); + assert.equal(syncIndicator({ ...base, progress: { phase: "uploading", completed: 1, total: 2 } as never }).state, "syncing", "active progress remains honest until stopping finishes"); +}); + test("sync problems translate credentials, cancellation, busy work, stale decisions, and network failures", () => { assert.equal(syncProblem(Object.assign(new Error("missing"), { code: "mirror_credentials_missing" })).action, "reauthorize"); assert.equal(syncProblem(new DOMException("stopped", "AbortError")).action, "resume"); @@ -123,6 +132,14 @@ test("sync problems translate credentials, cancellation, busy work, stale decisi assert.equal(syncProblem(Object.assign(new Error("x"), { code: "mirror_enrollment_unreachable" })).kind, "offline"); }); +test("a local conflict version removed during review is stale, not an internal failure", () => { + const problem = syncProblem(Object.assign(new Error("No local file exists at note.md."), { code: "mirror_conflict_copy_missing" })); + assert.equal(problem.kind, "decision"); + assert.equal(problem.action, "review"); + assert.match(problem.message, /Review the newest/); + assert.doesNotMatch(problem.message, /diagnostics|unexpected/); +}); + test("credentials, copied vaults and unexpected failures are told apart from being offline", () => { assert.equal(syncProblem(new HttpStatusError("mirror_access_rejected", "no", 401)).kind, "auth"); assert.equal(syncProblem(Object.assign(new Error("gone"), { code: "mirror_pairing_not_found" })).kind, "auth"); diff --git a/test/workspaceView.test.ts b/test/workspaceView.test.ts index b46accb..d9af8b8 100644 --- a/test/workspaceView.test.ts +++ b/test/workspaceView.test.ts @@ -136,6 +136,24 @@ function button(root: HTMLElement, label: string): HTMLButtonElement { return result; } +test("opening waits for the requested destination before scanning collection records", async () => { + const f = fixture(true); + f.state.destination = "types"; + 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.onOpen(); + assert.equal(recordLoads, 0, "onOpen must not scan Types before setState can restore Sync"); + await f.view.setState({ destination: "sync" }, {} as never); + assert.equal(recordLoads, 0); + await f.view.setState({ destination: "types" }, {} as never); + assert.equal(recordLoads, 1, "opening Types still loads its statistics"); + await f.view.onClose(); + f.dom.window.close(); +}); + test("Sync and Issues refreshes do not parse all records or run type impact scans", async () => { const f = fixture(true); let recordLoads = 0; @@ -239,6 +257,21 @@ test("a stale reviewed plan cannot be applied before refreshing the newest chang f.dom.window.close(); }); +test("a diagnostics copy failure is reported and returns focus instead of an unhandled rejection", async () => { + const f = fixture(true); + f.host.sync.reportProblem(new Error("Sync stopped")); + f.host.copySyncDiagnostics = async () => { throw new Error("Clipboard is unavailable"); }; + f.state.render(); + button(f.root, "Copy diagnostics").focus(); + button(f.root, "Copy diagnostics").click(); + await settle(); + assert.match(f.text(), /Clipboard is unavailable/); + assert.equal(f.dom.window.document.activeElement, button(f.root, "Copy diagnostics")); + assert.equal(button(f.root, "Copy diagnostics").disabled, false); + assert.ok(button(f.root, "Try again")); + f.dom.window.close(); +}); + test("enrollment exposes only essential controls but retains the upload warning and advanced options", () => { const f = fixture(); f.state.render(); @@ -435,6 +468,7 @@ test("background sync badge updates preserve keyboard focus on the destination t f.state.destination = "issues"; Object.assign(f.host, { loadWorkspaceSchema: async () => null }); await f.view.onOpen(); + await f.view.setState({ destination: "issues" }, {} as never); 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 }); @@ -444,6 +478,40 @@ test("background sync badge updates preserve keyboard focus on the destination t f.dom.window.close(); }); +test("sync problems remain visible from other destinations, where mobile has no status bar", () => { + for (const scenario of [ + { code: "network_timeout", label: "Offline" }, + { code: "mirror_credentials_missing", label: "Sign in" }, + { code: "mirror_other_device", label: "Set up" }, + { code: "sync_failed", label: "Error" }, + ]) { + const f = fixture(true); + f.state.destination = "issues"; + const problem = f.host.sync.reportProblem(Object.assign(new Error("Fixture problem"), { code: scenario.code })); + f.host.sync.refreshStatus = async () => f.host.sync.state.status; + f.state.render(); + const tab = f.root.querySelector("[data-focus-key='destination-sync']")!; + assert.equal(tab.querySelector(".mdbase-nav-status")?.textContent, scenario.label); + assert.equal(tab.getAttribute("aria-label"), `Sync · ${problem.title}`); + tab.click(); + assert.equal(f.state.destination, "sync"); + assert.equal(f.root.querySelector(".mdbase-nav-status"), null, "the active pane already explains the problem"); + assert.match(f.text(), new RegExp(problem.actionLabel)); + f.dom.window.close(); + } +}); + +test("sync tab counts have descriptive accessible names, not bare badge numbers", () => { + const f = fixture(true); + f.state.mirrorStatus = { state: "attention", conflicts: [{ path: "note.md" }], local_issues: [] }; + f.host.getIssues = () => [{ path: "other.md", severity: "error", code: "schema_required", message: "Missing title" }]; + f.state.destination = "issues"; + f.state.render(); + assert.equal(f.root.querySelector("[data-focus-key='destination-sync']")?.getAttribute("aria-label"), "Sync · 1 sync conflict"); + assert.equal(f.root.querySelector("[data-focus-key='destination-issues']")?.getAttribute("aria-label"), "Issues · 1 validation issue"); + f.dom.window.close(); +}); + test("empty Issues has no redundant filters, counts, or empty panels", () => { const f = fixture(); f.state.destination = "issues"; @@ -470,6 +538,21 @@ test("blocking review shows the issue without a misleading apply button or dupli f.dom.window.close(); }); +test("opening a local sync issue preserves the path action's focus across redraw", () => { + const f = fixture(true); + const path = 'Projects/Long review "draft".md'; + f.state.mirrorStatus = { state: "attention", conflicts: [], local_issues: [{ code: "file_read_failed", path, message: "Could not read this file." }] }; + const opened: string[] = []; + Object.assign(f.host, { openFileByPath: async (path: string) => { opened.push(path); } }); + f.state.render(); + button(f.root, "Open file").focus(); + f.state.render(); + assert.equal(f.dom.window.document.activeElement, button(f.root, "Open file")); + button(f.root, "Open file").click(); + assert.deepEqual(opened, [path]); + f.dom.window.close(); +}); + test("conflicts reveal resolution actions only after loading the versions", async () => { const f = fixture(true); f.state.mirrorStatus = { state: "attention", local_issues: [], conflicts: [{ @@ -488,6 +571,35 @@ test("conflicts reveal resolution actions only after loading the versions", asyn f.dom.window.close(); }); +test("conflict choices respect absent versions and name destructive outcomes", async () => { + for (const absent of ["local", "remote"] as const) { + const f = fixture(true); + f.state.mirrorStatus = { state: "attention", local_issues: [], conflicts: [{ + entity: "record", object_id: "record", decision_id: "decision", path: "note.md", message: "The versions differ.", + }] }; + Object.assign(f.host.connectSync, { conflictComparison: async () => ({ + entity: "record", objectId: "record", decisionId: "decision", + local: absent === "local" ? { state: "absent" } : { state: "exact", document: "Unsynced local edit" }, + remote: absent === "remote" ? { state: "absent" } : { state: "exact", document: "Hosted edit" }, + }) }); + f.state.render(); + button(f.root, "Resolve…").click(); + await settle(); + if (absent === "local") { + assert.match(f.text(), /No local version/); + assert.doesNotMatch(f.text(), /Keep both|Keep a local copy/); + assert.ok(button(f.root, "Delete from Connect").classList.contains("mod-warning")); + assert.ok(button(f.root, "Use hosted")); + } else { + assert.match(f.text(), /No hosted version.*before moving the original to trash/); + assert.ok(button(f.root, "Move local file to trash").classList.contains("mod-warning")); + assert.ok(button(f.root, "Keep a local copy")); + assert.doesNotMatch(f.text(), /Use hosted|Keep both/); + } + f.dom.window.close(); + } +}); + test("the single save bar updates validity while typing without replacing the focused input", async () => { const f = fixture(); f.state.destination = "types";