@adhd/backlog 0.0.2 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js DELETED
@@ -1,191 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";var Cd=Object.create;var Ci=Object.defineProperty;var Rd=Object.getOwnPropertyDescriptor;var Md=Object.getOwnPropertyNames;var Dd=Object.getPrototypeOf,Ld=Object.prototype.hasOwnProperty;var Ud=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Md(t))!Ld.call(e,o)&&o!==n&&Ci(e,o,{get:()=>t[o],enumerable:!(r=Rd(t,o))||r.enumerable});return e};var Bd=(e,t,n)=>(n=e!=null?Cd(Dd(e)):{},Ud(t||!e||!e.__esModule?Ci(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const W=require("node:fs"),mr=require("node:url"),Ri=require("ts-morph"),F=require("node:path"),wt=require("ts-json-schema-generator"),Ie=require("pino"),Ho=require("ajv"),Jo=require("ajv-formats"),Fd=require("better-sqlite3"),Vd=require("@adhd/sox-graph-store"),Gt=require("node:os"),Kc=require("node:crypto"),Kd=require("fastify"),Mi=require("node:http"),qd=require("@modelcontextprotocol/sdk/server/index.js"),zd=require("@modelcontextprotocol/sdk/server/stdio.js"),Gd=require("@modelcontextprotocol/sdk/server/sse.js"),Hd=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),Di=require("@modelcontextprotocol/sdk/types.js"),Li=require("yaml");var Pe=typeof document<"u"?document.currentScript:null;function Jd(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const no=Jd(F),ro="$apigen";let Ui=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function Wd(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new Ui(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);t.set(n.id,n)},resolve(n){for(const r of t.values())if(r.matches(n))return r},get(n){return t.get(n)},ids(){return[...t.keys()]},freeze(){const n=new Map(t),r={register(){throw new Ui("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const s of n.values())if(s.matches(o))return s},get(o){return n.get(o)},ids(){return[...n.keys()]},freeze(){return r}};return r}}}const Wo="x-apigen-logical",Qo="x-apigen-codec",oo="x-apigen-ctor",so="x-apigen-tojson",Qd="0.1.0";function Bi(e,t){return{registry:e,resolve:n=>{throw new Error(`[apigen-logical] $ref "${n}" cannot be resolved in run-mode without a descriptor root. Supply a resolve() in the ctx override to handle $ref.`)},seen:new WeakSet,path:"",mode:"strict",...t}}function Rt(e,t,n){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Rt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=qc(e,s,t);return Rt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return Dr(e,t,n);const a=t.items;if(!a)return e.map(u=>bt(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?bt(u):Rt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Rt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return Dr(e,t,n);const a=t.properties;if(!a)return bt(e);const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Rt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?Dr(e,t,n):bt(e)}function Mt(e,t,n){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Mt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=qc(e,s,t);return Mt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return e;const a=t.items;if(!a)return e;const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?u:Mt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Mt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Mt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?Yd(e,n):e}function qc(e,t,n,r){const o=n.discriminator;if(o!=null&&o.propertyName){const s=e!==null&&typeof e=="object"?e[o.propertyName]:void 0;if(typeof s=="string"&&o.mapping){const i=o.mapping[s];if(i){const a=t.find(c=>c.$ref===i);if(a)return a}}}return t[0]??{}}function Dr(e,t,n){for(const r of n.registry.ids()){const o=n.registry.get(r);if(o)try{const s=o.encode(e,o.schema,n);return{[ro]:r,v:s}}catch{}}return bt(e)}function Yd(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&ro in e){const n=e,r=n[ro],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function bt(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(bt);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=bt(r));return t}return null}function Zd(e){return{encode(t,n,r){const o=Bi(e,r);return Rt(t,n,o)},decode(t,n,r){const o=Bi(e,r);return Mt(t,n,o)}}}const Yo={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},encode(e,t,n){return e.toISOString()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof e}`);return new Date(String(e))}if(n.mode==="strict"&&Number.isNaN(new Date(e).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(e)}`);return new Date(e)}},Zo={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},encode(e,t,n){return String(e)},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof e}`);try{return BigInt(Math.trunc(Number(e)))}catch{return BigInt(0)}}if(n.mode==="strict")return BigInt(e);if(/^-?\d+$/.test(e))try{return BigInt(e)}catch{return BigInt(0)}return BigInt(0)}},Xo={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(e){return e.type==="string"&&e.format==="decimal"},encode(e,t,n){return e},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e)}if(n.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(e))throw new TypeError(`[decimal] wire value "${e}" at "${n.path}" is not a valid decimal string`);return e}},es={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},encode(e,t,n){return Buffer.from(e).toString("base64")},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof e}`);return new Uint8Array(0)}if(n.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(e))throw new TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${e}"`);return new Uint8Array(Buffer.from(e,"base64"))}},Xd=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ts={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(e){return e.type==="string"&&e.format==="uuid"},encode(e,t,n){return e.toLowerCase()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e).toLowerCase()}if(n.mode==="strict"&&!Xd.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},io="NaN",ao="Infinity",co="-Infinity",ep=new Set([io,ao,co]),ns={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,n){return Number.isNaN(e)?io:e===1/0?ao:e===-1/0?co:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===io)return NaN;if(e===ao)return 1/0;if(e===co)return-1/0;const r=Number(e);if(!Number.isNaN(r))return r}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(e)}. Expected a number or one of ${[...ep].join(", ")}.`);return NaN}},tp=[Yo,Zo,Xo,es,ts,ns];function np(e,t={}){for(const n of tp)e.register(n,{override:t.override??!1})}Yo.id,Zo.id,Xo.id,es.id,ts.id,ns.id;const zc=Wd();np(zc);const Gc=Zd(zc.freeze());function Hc(e,t){var n;const r=((n=e.input)==null?void 0:n.properties)??{};return t in r}function uo(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data;return Object.keys((r==null?void 0:r.properties)??{})}function rp(e,t){var n,r,o;const s=(o=(r=(n=e.input)==null?void 0:n.properties)==null?void 0:r.data)==null?void 0:o.properties,i=s==null?void 0:s[t];return i!==void 0?i:void 0}function op(e,t){return t===void 0||e===void 0?e:Gc.decode(e,t)}function Lr(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:Gc.encode(e,n)}async function sp(e,t,n,r,o,s){const i=uo(n).map(c=>op(s[c],rp(n,c)));if(Hc(n,"session")&&t){const c=await t({session:o.session}),u=await e[r](c,...i);return Lr(u,n)}if(n.hasCtx){const c=t?await t(o):void 0,u=await e[r](c,...i);return Lr(u,n)}const a=await e[r](...i);return Lr(a,n)}let ip=class{constructor(){this._map=new Map}set(t,n){this._map.set(t,n)}get(t){return this._map.get(t)}has(t){return this._map.has(t)}};function ap(e=[]){return async function(t,n,r){const o=r.schemas[t];if(!o)throw new Error(`apigen/invoke: no schema found for operation "${t}"`);const s=()=>sp(r.fns,r.createClient,o,t,n.envelope,n.domainArgs);return e.reduceRight((i,a)=>()=>a(n,i),s)()}}const Fi=new Set(["string","number","boolean","integer"]);function cp(e){if(typeof e!="object"||e===null)return!1;const t=e;if(t.$ref!==void 0||t.oneOf||t.anyOf||t.allOf)return!1;const{type:n}=t;return typeof n=="string"?Fi.has(n):Array.isArray(n)?n.every(r=>Fi.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function up(e){if(!e||typeof e!="object")return!1;const t=e.properties;return t===void 0||typeof t!="object"||t===null?!1:Object.values(t).every(cp)}const lp={"decimal.js":"Decimal"};function fp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(lp).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${fp(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function dp(e={}){const t=e.level??"info",n=typeof e.destination=="string"&&e.destination.length>0,r=!n&&!!process.stderr.isTTY,o=e.format??(r?"pretty":"json"),s={level:t};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:e.destination,mkdir:!0}:{destination:2}}},Ie(s);const i=n?Ie.destination({dest:e.destination,mkdir:!0,sync:!0}):Ie.destination(2);return Ie(s,i)}function Jc(e){return e?e.type==="array"?`${Jc(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function pp(e){var t;const n=(t=((e==null?void 0:e.input)??{}).properties)==null?void 0:t.data,r=(n==null?void 0:n.properties)??{},o=new Set((n==null?void 0:n.required)??[]),s=Object.entries(r).map(([a,c])=>({name:a,type:Jc(c),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}let hp=class extends Error{constructor(t,n,r){super(n),this.name="ApiError",this.code=t,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const t={code:this.code,message:this.message};return this.details!==void 0&&(t.details=this.details),t}};const gr=new Ho({allErrors:!0});Jo(gr);for(const e of[Wo,Qo,oo,so,"discriminator"])gr.addKeyword({keyword:e,valid:!0});gr.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function mp(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function gp(e){return async function(t,n){const r=t.operation.id,o=e[r];if(o===void 0)return n();const s={data:t.domainArgs,...t.envelope},i=gr.compile(o.input);if(!i(s)){const a=i.errors??[];throw new hp("invalid_argument",`Validation failed: ${mp(a)}`,a)}return n()}}function yp(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}class ft extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}}function Ur(e){const t=e.discriminator;if(t===null||typeof t!="object"||Array.isArray(t))return;const n=t;if(typeof n.propertyName!="string")return;const r=n.mapping;if(!(r===null||typeof r!="object"||Array.isArray(r)))return{propertyName:n.propertyName,mapping:r}}function Wc(e,t){const n=e[Qo];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function vp(e,t,n){const r=Wc(t,n);return r?r.encode(e,t,n):e}function $p(e,t,n){const r=Wc(t,n);return r?r.decode(e,t,n):e}function wp(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[Wo]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:Ur(r)!==void 0},encode(r,o,s){const i=Ur(o);if(!i)throw new ft("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=i,u=r[a];if(u==null)throw new ft("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),f=c[l];if(!f)throw new ft("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const p=s.resolve(f);return vp(r,p,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let d;throw r===null?d="null":Array.isArray(r)?d="array":d=typeof r,new ft("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${d}.`)}const i=r,a=Ur(o);if(!a)throw new ft("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:u}=a,l=i[c];if(l==null)throw new ft("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const f=String(l),p=u[f];if(!p)throw new ft("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${f}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const h=s.resolve(p);return $p(r,h,{...s,path:`${s.path}[${f}]`})}}}const bp="x-apigen-instances";let In=class extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}};function Vi(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Sp(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Ki(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function Ep(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function Np(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[Wo]==="nominal"?!0:o[Qo]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new In("E_NOMINAL_CYCLE",`[${t}] cycle detected at "${i.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN §8.3); break the cycle or use 'lossy' mode.`);return null}i.seen.add(o);try{const a=Vi(s),c=typeof s[so]=="string"?s[so]:"toJSON",u=o[c];if(typeof u=="function"){const d=u.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const v={};for(const[m,g]of Object.entries(d))v[m]=Ki(g,a[m],{...i,path:`${i.path}/${m}`});return v}return d}const l={},f=Object.keys(a),p=o,h=f.length>0?f:Object.keys(p);for(const d of h){const v=p[d];v!==void 0&&(l[d]=Ki(v,a[d],{...i,path:`${i.path}/${d}`}))}return l}finally{i.seen.delete(o)}},decode(o,s,i){if(o===null||typeof o!="object"||Array.isArray(o)){let l;throw o===null?l="null":Array.isArray(o)?l="array":l=typeof o,new In("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of Sp(s))if(!(l in a))throw new In("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[bp]===!1)throw new In("E_NOMINAL_NONRECONSTRUCTABLE",`[${t}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=Vi(s),u={};for(const[l,f]of Object.entries(a))u[l]=Ep(f,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[oo]=="string"?s[oo]:"fromJSON",f=r[l];if(typeof f=="function")return f.call(r,u);const p=r;return new p(u)}return u}}}const Op=[Yo,Zo,Xo,es,ts,ns],_p={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},qi=Np({id:"ts.NominalSentinel",schema:_p}),kp={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},zi=wp({id:"ts.UnionSentinel",schema:kp});function Ap(){const e=[...Op.map(t=>[t.id,t]),[qi.id,qi],[zi.id,zi]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:Qd,codecs:Ap()});function Gi(e){return e.words.join("-")}function Hi(e){return e.words.map(Tp).join("")}function Ji(e){return e.words.join("_")}function jp(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||up(e.input)?"GET":"POST",i=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??s,a="/"+o.map(h=>Gi(h)).join("/"),c=o.map(h=>Ji(h)).join("_"),u=o.map(h=>Ji(h)).slice(0,-1).join("."),l=Hi(o[o.length-2]??o[0]),f=Hi(o[o.length-1]),p=o.map(h=>Gi(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function Ip(e,t){return`x-${e}-${t}`}function Pp(e,t){return`--${e}-${t}`}function xp(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function Tp(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Qc(e){return e.anyOf??e.oneOf}function Cp(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Qc(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function Rp(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Qc(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function Mp(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function Dp(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data,o=(r==null?void 0:r.properties)??{},s=(r==null?void 0:r.required)??[];return{props:o,required:s}}function Wi(e){return typeof e.handler=="function"}function Lp(e){var t;const n=((t=e.input)==null?void 0:t.properties)??{},r=e["x-apigen-envelope"],o=[];for(const s of Object.keys(n)){if(s==="data")continue;const i=(r==null?void 0:r[s])??"adhd",a=Ip(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:Pp(i,s),envVar:xp(i,s)})}return o}function Up(e,t){const n=new Map,{props:r}=Dp(e);for(const[o,s]of Object.entries(r)){let i="string";Rp(s)?i="boolean":Cp(s)&&(i="json"),n.set(Mp(o),{camelKey:o,kind:"domain",valueKind:i})}for(const o of t){const s=o.cliFlag.replace(/^--/,"");n.set(s,{camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar})}return n}function Yc(e){const{op:t,schema:n,transport:r,projection:o}=e,s=jp(t,o),i=n?Lp(n):[],a=n?Up(n,i):new Map,c=n?pp(n).params:void 0,u={op:t,transport:r,http:s.http,mcp:s.mcp,cli:s.cli,grpc:s.grpc,params:c,envelope:i,cliFlags:a,streaming:t.streaming,isMount:Wi(t)};if(Wi(t)){const l=t.handler;u.mountHandler=async f=>l(f)}return u}function Bp(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function Fp(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function Vp(e){return async function(t,n){const r=Object.assign(t,{data:t.domainArgs});return await e.layer(r,n)}}function Qi(e,t){var n;const r=[];for(const o of t){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(Vp(s))}return r.push(gp(e)),ap(r)}function Kp(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const qp={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function Yi(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new ip};if(e.isMount){const s=e.mountHandler;if(!s)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${e.op.id}" has isMount=true but no mountHandler`);const i={operation:e.op,data:n.domainArgs,envelope:n.envelope,ctx:Kp(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>s(i)},schemas:{[e.op.id]:qp}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}const zp={"decimal.js":"Decimal"};function Gp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(zp).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Gp(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Hp(e,t){return`--${e}-${t}`}function Jp(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function Zi(e){let t=e.replace(/[^a-zA-Z0-9_$]/g,"_");return(t===""||/^[0-9]/.test(t))&&(t=`_${t}`),t}const Wp=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],Xi={invalid_argument:2,unauthenticated:3,permission_denied:3,not_found:4,internal:1};class ir extends Error{constructor(t,n,r){super(n),this.name="ApiError",this.code=t,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const t={code:this.code,message:this.message};return this.details!==void 0&&(t.details=this.details),t}}function ea(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&Wp.includes(e.code)&&typeof e.toJSON=="function"}function Zc(e){return e.anyOf??e.oneOf}function Qp(e){var o;const t=((o=e.input)==null?void 0:o.properties)??{},n=e["x-apigen-envelope"],r=[];for(const s of Object.keys(t)){if(s==="data")continue;const i=(n==null?void 0:n[s])??"adhd";r.push({field:s,pluginId:i,flag:Hp(i,s),envVar:Jp(i,s)})}return r}function ta(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Zc(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function Yp(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Zc(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function na(e){var o,s;const t=(s=(o=e.input)==null?void 0:o.properties)==null?void 0:s.data,n=(t==null?void 0:t.properties)??{},r=(t==null?void 0:t.required)??[];return{props:n,required:r}}function Zp(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function Xp(e,t){if(!no.isAbsolute(t))return t;const n=no.relative(e,t);return!n.startsWith(".")&&!n.startsWith("/")?`./${n}`:n}const eh=["function __apigenParseJsonArg(flag: string, raw: unknown): unknown {"," if (raw === undefined) return undefined"," if (typeof raw !== 'string') return raw"," try {"," return JSON.parse(raw)"," } catch (err) {"," throw new Error(`Invalid JSON for --${flag}: ${(err as Error).message}`)"," }","}"].join(`
3
- `);function th(e){var s;const t=e.options.name??"cli",n=e.options.version??"0.1.0",r=e.packages.some(i=>Object.values(i.schemas).some(a=>{const{props:c}=na(a);return uo(a).some(u=>ta(c[u]))})),o=["#!/usr/bin/env node","// Auto-generated by @adhd/apigen-cli — do not edit","import { Command } from 'commander'","import { dispatch, buildFnTable } from '@adhd/apigen-engine-runtime'"];for(const i of e.packages){const a=Zi(i.id),c=Xp(e.outputDir,i.importPath);o.push(`import * as ${a}_ns from '${c}'`),o.push(`const ${a}_fns = buildFnTable(${a}_ns as Record<string, unknown>)`)}o.push(""),r&&(o.push(eh),o.push("")),o.push(`const schemas: Record<string, unknown> = ${JSON.stringify(Object.fromEntries(e.packages.flatMap(i=>Object.entries(i.schemas).map(([a,c])=>[`${i.id}:${a}`,c]))),null,2)}`),o.push(""),o.push(`const program = new Command().name('${t}').version('${n}')`),o.push("");for(const i of e.packages){const a=Zi(i.id);for(const[c,u]of Object.entries(i.schemas)){const l=uo(u),f=Hc(u,"session"),p=Qp(u),{props:h,required:d}=na(u);o.push("program"),o.push(` .command('${c}')`);for(const m of p){const g=m.flag.replace(/^--/,"");o.push(` .option('${m.flag} <${g}>', '${m.field} (env: ${m.envVar})')`)}f&&!p.some(m=>m.field==="session")&&o.push(" .option('--session <key>', 'Session key')");const v=Zp;for(const m of l){const g=v(m),$=Yp(h[m]),w=d.includes(m);$?(o.push(` .option('--${g}')`),((s=h[m])==null?void 0:s.default)===!0&&o.push(` .option('--no-${g}')`)):w?o.push(` .requiredOption('--${g} <${g}>')`):o.push(` .option('--${g} <${g}>')`)}if(o.push(" .action(async (opts: Record<string, unknown>) => {"),o.push(` const domainArgs: Record<string, unknown> = { ${l.map(m=>ta(h[m])?`'${m}': __apigenParseJsonArg('${v(m)}', opts['${m}'])`:`'${m}': opts['${m}']`).join(", ")} }`),p.length>0){const m=p.map(g=>{const w=g.flag.replace(/^--/,"").replace(/-([a-z])/g,(S,N)=>N.toUpperCase());return`'${g.field}': opts['${w}'] ?? process.env['${g.envVar}']`});o.push(` const envelope: Record<string, unknown> = { ${m.join(", ")} }`)}else f?o.push(" const envelope: Record<string, unknown> = { session: opts['session'] }"):o.push(" const envelope: Record<string, unknown> = {}");o.push(` const result = await dispatch(${a}_fns as any, undefined, schemas['${i.id}:${c}'] as any, '${c}', envelope, domainArgs)`),o.push(" console.log(JSON.stringify(result))"),o.push(" })")}}return o.push(""),o.push("program.parseAsync()"),{files:[{path:"cli.ts",content:o.join(`
4
- `)}]}}function nh(e){const t=[],n=/"([^"]*)"|'([^']*)'|(\S+)/g;let r;for(;r=n.exec(e);)t.push(r[1]??r[2]??r[3]);return t}function rh(e){const t=e.argv;return Array.isArray(t)?t.map(String):typeof t=="string"?nh(t):process.argv.slice(2)}function oh(e,t){return{id:e,host:"ts",namespace:{raw:e,words:[e]},path:[],kind:"action",async:!1,streaming:!1,safe:t["x-apigen-safe"]??!1,input:t.input??{},output:t.output??{},envelope:{},typeText:null}}function sh(e){const t=new Map;for(const r of e.operations??[]){const o=r.path[r.path.length-1];o&&t.set(`${r.namespace.raw}:${o.raw}`,r)}const n=new Map;for(const r of e.packages)for(const[o,s]of Object.entries(r.schemas)){const i=t.get(`${r.id}:${o}`)??oh(o,s),a=Yc({op:i,schema:s,transport:"cli"}),c=a.cli.path;n.set(c.join(" "),{pkgId:r.id,fnName:o,schema:s,cliPath:c,plan:a})}return n}function ih(e,t){let n=0;for(;n<e.length&&!e[n].startsWith("-");)n++;for(let r=n;r>=1;r--){const o=t.get(e.slice(0,r).join(" "));if(o)return{entry:o,rest:e.slice(r)}}return null}function Xc(e){return!e||e.length===0?"":e.map(t=>`${t.name}${t.required?"":"?"}: ${t.type}`).join(", ")}function ra(e){const t=["Available commands:",""],n=[...e.entries()].sort(([r],[o])=>r.localeCompare(o));for(const[r,{plan:o}]of n){const s=Xc(o.params);t.push(` ${r}${s?` { ${s} }`:""}`)}return t.join(`
5
- `)}function Pn(e){return new ir("invalid_argument",e)}function ah(e,t){var s;const n={},r={};let o=0;for(;o<e.length;){const i=e[o];if(!i.startsWith("--"))throw Pn(`Unexpected positional argument: "${i}"`);let a=i.slice(2),c;const u=a.indexOf("=");u!==-1&&(c=a.slice(u+1),a=a.slice(0,u));let l=!1,f=a;a.startsWith("no-")&&((s=t.get(a.slice(3)))==null?void 0:s.valueKind)==="boolean"&&(l=!0,f=a.slice(3));const p=t.get(f);if(!p)throw Pn(`Unknown option: --${a}. Available: ${[...t.keys()].sort().map(d=>`--${d}`).join(", ")}`);o++;let h;if(p.valueKind==="boolean")l?h=!1:c===void 0?h=!0:h=c!=="false";else{const d=c!==void 0?c:e[o++];if(d===void 0)throw Pn(`Missing value for --${a}`);if(p.valueKind==="json")try{h=JSON.parse(d)}catch(v){throw Pn(`Invalid JSON for --${a}: ${v.message}`)}else h=d}p.kind==="domain"?n[p.camelKey]=h:r[p.camelKey]=h}for(const i of t.values()){if(i.kind!=="envelope"||!i.envVar||r[i.camelKey]!==void 0)continue;const a=process.env[i.envVar];a!==void 0&&(r[i.camelKey]=a)}return{domainArgs:n,envelope:r}}function eu(e){const t=ea(e)?e.toJSON():{code:"internal",message:e instanceof Error?e.message:String(e)};console.error(JSON.stringify(t)),process.exitCode=ea(e)?Xi[e.code]:Xi.internal}class ch{constructor(t){this.signal=t,this.routes=new Map}registerRoute(t,n){this.routes.set(t.cli.path.join(" "),{plan:t,dispatch:n})}routeTable(){return this.routes}readCall(t,n){const{domainArgs:r,envelope:o}=ah(t.rest,n.cliFlags);return{domainArgs:r,envelope:o,signal:this.signal}}writeResult(t,n,r){if(yp(n))throw new ir("invalid_argument",`Command "${r.cli.path.join(" ")}" produced a streaming result, which is not supported over the cli transport.`);console.log(JSON.stringify(n===void 0?null:n))}writeError(t,n,r){eu(n)}}function uh(e,t,n,r){var i;const o=[],s={host:n,operations:r};for(const a of e){const c=(i=a.capabilities)==null?void 0:i.mount;if(!c)continue;const u=c.operations(s,t[a.id]);for(const l of u)l.transports&&!l.transports.includes("cli")||o.push(l)}return o}async function lh(e){var $,w;const t=e.logger??dp();if(($=e.signal)!=null&&$.aborted){t.info("cli run: signal already aborted before dispatch — skipping");return}let n=rh(e.options);n[0]==="--"&&(n=n.slice(1));const r=Bp(e.options),o=Fp(e.options),s=new ch(e.signal),i=sh(e),a=new Map;for(const S of i.values()){const N=a.get(S.pkgId);N?N.push(S):a.set(S.pkgId,[S])}for(const S of e.packages){const N=a.get(S.id);if(!N||N.length===0)continue;if(!S.fns)throw new Error(`apigen-plugin-cli-output: package "${S.id}" has no functions`);const x=S.fns,M={},q={};for(const ne of N)M[ne.plan.op.id]=ne.schema,q[ne.plan.op.id]=x[ne.fnName];const Q=Qi(M,r),te={fns:q,createClient:S.createClient,schemas:M};for(const ne of N)s.registerRoute(ne.plan,le=>Yi(ne.plan,Q,le,te))}const c=((w=e.packages[0])==null?void 0:w.id)??"ts",u=uh(r,o,c,e.operations??[]);if(u.length>0){const S=Qi({},r),N={fns:{},schemas:{}};for(const x of u){const M=Yc({op:x,transport:"cli"});s.registerRoute(M,q=>Yi(M,S,q,N))}}const l=s.routeTable();if(n.length===0||n[0]==="--help"||n[0]==="-h"){console.log(ra(l));return}const f=ih(n,l);if(!f){eu(new ir("not_found",`Unknown command: ${n.join(" ")}
6
-
7
- ${ra(l)}`));return}const{entry:p,rest:h}=f,{plan:d,dispatch:v}=p,m=d.cli.path.join(" ");if(h.includes("--help")||h.includes("-h")){const S=Xc(d.params);console.log(`${m}${S?` { ${S} }`:""}`);return}const g={rest:h};try{if(d.streaming)throw new ir("invalid_argument",`Command "${m}" is a streaming operation and is not supported over the cli transport (DEBT-APIGEN-SERVE-CORE-002 cli half).`);const S=await s.readCall(g,d),N=Date.now(),x=await v(S);await s.writeResult(g,x,d),t.info({command:m,ms:Date.now()-N},`→ ${m}`)}catch(S){t.error({command:m,err:S},`✗ ${m}`),await s.writeError(g,S,d)}}const fh={id:"cli",description:"Emit a Commander CLI program where each exported function becomes a subcommand",language:"ts",optionsSchema:{type:"object",properties:{name:{type:"string",default:"cli"},version:{type:"string",default:"0.1.0"},argv:{anyOf:[{type:"array",items:{type:"string"}},{type:"string"}]}}},generate(e){return th(e)},run(e){return lh(e)}},tu=Symbol.for("adhd.apigen.extraction-session");function nu(e,t){const n=[...e.getImportDeclarations().map(r=>r.getModuleSpecifierSourceFile()),...e.getExportDeclarations().map(r=>r.getModuleSpecifierSourceFile())];for(const r of n){if(!r)continue;const o=r.getFilePath();if(!o.includes("/node_modules/")&&!t.has(o)){t.add(o);try{r.refreshFromFileSystemSync()}catch{}nu(r,t)}}}function ru(e){try{const t=W.statSync(e);return`${t.mtimeMs}:${t.size}`}catch{return"nostat"}}const Gn=new Map,oa=new Map;function dh(e,t,n){const r=t??"",o=Gn.get(r);let s=n;if(o&&o.fileVersions.size>0){const c=[n],u=[...o.fileVersions.entries()].sort(([l],[f])=>l.localeCompare(f));for(const[l,f]of u)l!==e&&c.push(`${l}:${f}`);s=c.join("|")}const i=`${e}\0${t??""}`;let a=oa.get(i);return(!a||a.version!==s)&&(a={version:s,schemas:new Map},oa.set(i,a)),a.schemas}function ph(){const e={projectsBuilt:0,generatorsBuilt:0,schemaCacheHits:0,schemaCacheMisses:0},t=new Map;let n=!1;return{[tu]:!0,stats:e,schemaCache:new Map,aliasCache:new WeakMap,zodImportCache:new WeakMap,generatorCache:new Map,projectFor(r){if(n)throw new Error("apigen-core: ExtractionSession used after dispose()");const o=r??"",s=r?this.statVersion(r):"";let i=Gn.get(o);return i&&i.tsconfigVersion!==s&&(i=void 0),i||(i={project:r?new Ri.Project({tsConfigFilePath:r,skipAddingFilesFromTsConfig:!0}):new Ri.Project({skipAddingFilesFromTsConfig:!0}),tsconfigVersion:s,fileVersions:new Map},Gn.set(o,i),e.projectsBuilt++),i.project},sourceFileFor(r,o){const s=this.projectFor(o),i=Gn.get(o??""),a=this.statVersion(r);let c=s.getSourceFile(r);if(c===void 0?c=s.addSourceFileAtPath(r):i&&i.fileVersions.get(r)!==a&&c.refreshFromFileSystemSync(),i==null||i.fileVersions.set(r,a),i){const u=new Set([r]);nu(c,u);for(const l of u)l!==r&&i.fileVersions.set(l,this.statVersion(l))}return c},statVersion(r){let o=t.get(r);return o===void 0&&(o=ru(r),t.set(r,o)),o},dispose(){n=!0,this.schemaCache.clear(),this.generatorCache.clear(),t.clear()}}}function hh(e){const t=e;if(t[tu]!==!0)throw new Error("apigen-core: unknown ExtractionSession implementation — create sessions with createExtractionSession()");return t}const ar="x-apigen-logical";function sa(e,t){const n=new Set,r=[e];for(;r.length>0;){const o=r.pop();if(!o||n.has(o))continue;n.add(o);const s=o.$ref;if(typeof s=="string"){if(t){const f=t[s];if(!f){const p=Object.keys(t).join(", ")||"(none)";throw new Error(`[apigen-logical] $ref "${s}" cannot be resolved. Available $defs: ${p}`)}r.push(f)}continue}const i=o.oneOf;if(Array.isArray(i))for(const f of i)typeof f=="object"&&f!==null&&r.push(f);const a=o.properties;if(a)for(const f of Object.values(a))r.push(f);const c=o.items;if(Array.isArray(c))for(const f of c)typeof f=="object"&&f!==null&&r.push(f);else typeof c=="object"&&c!==null&&r.push(c);const u=o.additionalProperties;typeof u=="object"&&u!==null&&r.push(u);const l=o.propertyNames;typeof l=="object"&&l!==null&&r.push(l)}}const ia=new Set(["string","number","boolean","integer"]);function mh(e){if(typeof e!="object"||e===null)return!1;const t=e;if(t.$ref!==void 0||t.oneOf||t.anyOf||t.allOf)return!1;const{type:n}=t;return typeof n=="string"?ia.has(n):Array.isArray(n)?n.every(r=>ia.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function ou(e){if(!e||typeof e!="object")return!1;const t=e.properties;return t===void 0||typeof t!="object"||t===null?!1:Object.values(t).every(mh)}function gh(e){const t={},n=r=>{for(const o of["definitions","$defs"]){const s=r[o];if(s)for(const[i,a]of Object.entries(s)){const c=i.startsWith("#/")?i:`#/${o}/${i}`;t[c]=a}}};for(const r of Object.values(e.schemas))n(r.input),n(r.output);if(Object.keys(t).length!==0)for(const[r,o]of Object.entries(e.schemas))try{sa(o.input,t),sa(o.output,t)}catch(s){throw new Error(`[apigen-core-client] Schema validation failed for function "${r}": ${s.message}`)}}function yh(e,t){const n=['apigen calling convention: all domain parameters go inside a "data" envelope — e.g. { "data": { ... } }'+(t?".":" (an empty object for this zero-parameter tool).")];return e.length>0&&n.push(`Field(s) ${e.map(r=>`"${r}"`).join(", ")} are transport-level envelope metadata, NOT domain data — do not nest them under "data". Over MCP they are read from arguments._meta["x-<pluginId>-<field>"] (default pluginId "adhd"); see @adhd/apigen-engine-naming's envelopeMetaKey/envelopeCliFlag/envelopeEnvVar for the HTTP-header / CLI-flag / env-var equivalents.`),n.join(" ")}function vh(e,t,n){gh(e);const r={};for(const[o,s]of Object.entries(e.schemas)){const i={},a=s.input.properties??{},c=s.input.required??[],u={},l=[],f={};for(const m of t)if(m.envelope&&i[m.id]!==!1)for(const[g,$]of Object.entries(m.envelope))u[g]=$,f[g]=m.id,l.includes(g)||l.push(g);const p={type:"object",properties:a,additionalProperties:!1,...c.length>0?{required:c}:{}},h=s.safe===!0||ou(s.input),d=s.input.definitions,v=s.input.$defs;r[o]={input:{type:"object",properties:{...u,data:p},required:[...l,...c.length>0?["data"]:[]],additionalProperties:!1,description:yh(Object.keys(u),Object.keys(a).length>0),...d?{definitions:d}:{},...v?{$defs:v}:{}},output:s.output,...s.hasCtx?{hasCtx:!0}:{},"x-apigen-safe":h,...Object.keys(f).length>0?{"x-apigen-envelope":f}:{}}}return r}const $h=8;function wh(e,t){try{return t?e.getText(t):e.getText()}catch{try{return e.getText()}catch{return}}}let bh=0;async function Sh(e,t,n,r){const o=`__ApigenProbe_${process.pid}_${bh++}`;let s;try{s=t.addTypeAlias({name:o,type:n});const i=s.getType();return await r(i)}catch{return}finally{try{s==null||s.remove()}catch{}}}async function su(e,t,n){if(n>$h)return{};if(e.isString()||e.isStringLiteral())return e.isStringLiteral()?{type:"string",enum:[e.getLiteralValue()]}:{type:"string"};if(e.isNumber()||e.isNumberLiteral())return e.isNumberLiteral()?{type:"number",enum:[e.getLiteralValue()]}:{type:"number"};if(e.isBoolean())return{type:"boolean"};if(e.isBooleanLiteral())return{type:"boolean"};if(e.isNull()||e.isUndefined()||e.isVoid())return{type:"null"};if(e.isUnion()){const r=e.getUnionTypes();if(r.every(i=>i.isStringLiteral())&&r.length>0)return{type:"string",enum:r.map(i=>i.getLiteralValue())};if(r.every(i=>i.isNumberLiteral())&&r.length>0)return{type:"number",enum:r.map(i=>i.getLiteralValue())};const o=await Promise.all(r.map(i=>su(i,t,n+1))),s=rs(o);return{oneOf:o,...s?{discriminator:s}:{},[ar]:"union"}}if(e.isArray()){const r=e.getArrayElementType();return{type:"array",items:r?await t(r.getText()):{}}}if(e.isTuple()){const r=e.getTupleElements(),o=await Promise.all(r.map(s=>t(s.getText())));return{type:"array",items:o,minItems:o.length,maxItems:o.length}}if(e.isObject()){const r=e.getStringIndexType(),o=e.getNumberIndexType(),s=r??o,i=e.getProperties();if(s&&i.length===0)return{type:"object",additionalProperties:await t(s.getText())};const a={};for(const c of i){const u=c.getName(),l=c.getDeclarations()[0];let f;if(l)try{f=c.getTypeAtLocation(l)}catch{f=void 0}if(f!==void 0&&f.getCallSignatures().length>0)continue;const p=f!==void 0?wh(f,l):void 0;a[u]=p!==void 0?await t(p):{}}return Object.keys(a).length>0?{type:"object",properties:a}:{}}return{}}function rs(e){if(e.length<2)return;const t=[];for(const r of e){if(r.type!=="object")return;const o=r.properties;if(!o||typeof o!="object")return;t.push(o)}const n=Object.keys(t[0]).filter(r=>t.every(o=>Object.prototype.hasOwnProperty.call(o,r)));for(const r of n){const o=[];let s=!0;for(const a of t){const c=a[r],u=c&&(c.type==="string"||c.type==="number"),l=c==null?void 0:c.enum;if(!u||!Array.isArray(l)||l.length!==1){s=!1;break}o.push(String(l[0]))}if(!s||new Set(o).size!==o.length)continue;const i={};return o.forEach((a,c)=>{i[a]=`#/oneOf/${c}`}),{propertyName:r,mapping:i}}}function Hn(e,t,n){if(t>6)return{};const r=e.trim();if(r==="string")return{type:"string"};if(r==="number")return{type:"number"};if(r==="boolean")return{type:"boolean"};if(r==="null")return{type:"null"};if(r==="undefined")return{type:"null"};const o=lo[r];if(o!==void 0)return o;if(n!=null&&n.size){const s=n.get(r);if(s!==void 0){const i=lo[s];if(i!==void 0)return i}}if(r.endsWith("[]"))return{type:"array",items:Hn(r.slice(0,-2),t+1,n)};if(r.includes("|")){const s=r.split("|").map(c=>c.trim());if(s.every(c=>c.startsWith("'")))return{type:"string",enum:s.map(c=>c.replace(/'/g,""))};const i=s.map(c=>Hn(c,t+1,n)),a=rs(i);return{oneOf:i,...a?{discriminator:a}:{},[ar]:"union"}}if(r.startsWith("{")&&r.endsWith("}")){const s=r.slice(1,-1).trim(),i={};for(const a of s.split(";").filter(Boolean)){const[c,u]=a.split(":").map(l=>l.trim());c&&u&&(i[c.replace("?","")]=Hn(u,t+1,n))}return{type:"object",properties:i}}return{}}function iu(e){const t=[];let n=0,r=0;for(let s=0;s<e.length;s++){const i=e[s];i==="<"||i==="["||i==="{"||i==="("?n++:i===">"||i==="]"||i==="}"||i===")"?n--:i===","&&n===0&&(t.push(e.slice(r,s).trim()),r=s+1)}const o=e.slice(r).trim();return o.length>0&&t.push(o),t}function Eh(e){const t=/^(?:Readonly)?Map<(.+)>$/.exec(e);return t?t[1]:void 0}function Nh(e){const t=/^(?:Readonly)?Set<(.+)>$/.exec(e);return t?t[1]:void 0}function Oh(e){let t=e.trim();if(t.startsWith("readonly ")&&(t=t.slice(9).trim()),!t.startsWith("[")||!t.endsWith("]"))return;const n=t.slice(1,-1).trim();if(n.length!==0)return iu(n)}async function _h(e,t){const n=e.trim(),r=Eh(n);if(r!==void 0){const i=iu(r);if(i.length===2){const[a,c]=await Promise.all([t(i[0]),t(i[1])]);return{type:"array",items:{type:"array",items:[a,c],minItems:2,maxItems:2}}}}const o=Nh(n);if(o!==void 0)return{type:"array",items:await t(o),uniqueItems:!0};const s=Oh(n);if(s!==void 0){const i=await Promise.all(s.map(a=>t(a)));return{type:"array",items:i,minItems:i.length,maxItems:i.length}}}const au={"decimal.js":"Decimal"},lo={Date:{type:"string",format:"date-time"},bigint:{type:"string",format:"int64"},Uint8Array:{type:"string",format:"byte"},Buffer:{type:"string",format:"byte"},URL:{type:"string",format:"uri"},RegExp:{type:"string",format:"regex"},Decimal:{type:"string",format:"decimal"}},aa={Uint8Array:"byte",Buffer:"byte",Decimal:"decimal"};function ca(e){var t;const n=new Map;for(const r of e.getImportDeclarations()){const o=r.getModuleSpecifierValue(),s=au[o];if(!s)continue;const i=r.getDefaultImport();if(i){const a=i.getText();a!==s&&n.set(a,s)}for(const a of r.getNamedImports()){const c=((t=a.getAliasNode())==null?void 0:t.getText())??a.getName();c!==s&&n.set(c,s)}}return n}function kh(e,t){return n=>{n.addNodeParser({supportsNode(r){var o,s,i;if(r.kind!==t)return!1;const a=((o=r.typeName)==null?void 0:o.escapedText)??((i=(s=r.typeName)==null?void 0:s.right)==null?void 0:i.escapedText);return a!==void 0&&Object.prototype.hasOwnProperty.call(aa,a)},createType(r){var o,s,i;const a=((o=r.typeName)==null?void 0:o.escapedText)??((i=(s=r.typeName)==null?void 0:s.right)==null?void 0:i.escapedText);return new wt.AnnotatedType(new wt.StringType,{format:aa[a]},!1)}}),n.addNodeParser({supportsNode(r){return r.kind===e},createType(){return new wt.AnnotatedType(new wt.StringType,{format:"int64"},!1)}})}}let rn;function Ah(){if(rn)return rn;try{const e=F.dirname(require.resolve("ts-json-schema-generator/package.json"));rn=require(require.resolve("typescript",{paths:[e]}))}catch{rn=require("typescript")}return rn}const rt=new Map;function jh(){const e=process.env.APIGEN_PROGRAM_CACHE,t=e===void 0?NaN:Number(e);return Number.isFinite(t)&&t>=0?t:8}function Ih(e){const t=rt.get(e);return t&&(rt.delete(e),rt.set(e,t)),t}function Ph(e,t){const n=jh();if(n!==0)for(rt.delete(e),rt.set(e,t);rt.size>n;){const r=rt.keys().next().value;rt.delete(r)}}function xh(e,t){return`${e}\0${t??""}`}const Th=new Set(["zod",/^zod\/./]);function Ch(e){for(const t of e.getImportDeclarations()){const n=t.getModuleSpecifierValue();for(const r of Th)if(typeof r=="string"){if(n===r)return!0}else if(r.test(n))return!0}return!1}function Rh(e){for(const t of["$defs","definitions"]){const n=e[t];if(!n||typeof n!="object")continue;const r=Object.keys(n);if(r.length===0)continue;const o=new Set(r.filter(s=>/zod/i.test(s)));for(const[s,i]of Object.entries(n)){if(o.has(s)||typeof i!="object"||i===null)continue;const a=i,c=typeof a.$ref=="string"?a.$ref:"";if(c){for(const u of o)if(c.includes(u)){o.add(s);break}}}for(const s of o)delete n[s]}fo(e)}function fo(e,t){if(!e||typeof e!="object")return;const n=t??new WeakSet;if(!n.has(e)){n.add(e);for(const r of Object.keys(e))if(r==="$ref"&&typeof e[r]=="string"){const o=e[r];/zod/i.test(o)&&delete e[r]}for(const[,r]of Object.entries(e))if(typeof r=="object"&&r!==null)if(Array.isArray(r))for(const o of r)typeof o=="object"&&o!==null&&fo(o,n);else fo(r,n)}}function Mh(e){const t=new Set;for(const r of["$defs","definitions"]){const o=e[r];if(o&&typeof o=="object")for(const s of Object.keys(o))t.add(s)}const n=po(e,t);if(n.length>0)throw new Error(`[apigen-core-client] Generated schema contains ${n.length} unresolvable $ref(s): ${n.join(", ")}. This usually means zod-internal definitions were stripped but $ref references to them remain. Check the source file's imports or the ts-json-schema-generator output.`)}function po(e,t){if(!e||typeof e!="object")return[];const n=[];for(const[r,o]of Object.entries(e))if(r==="$ref"&&typeof o=="string"){const s=o.match(/#\/(?:\$defs|definitions)\/(.+)$/);s&&!t.has(s[1])&&n.push(o)}else if(typeof o=="object"&&o!==null)if(Array.isArray(o))for(const s of o)typeof s=="object"&&s!==null&&n.push(...po(s,t));else n.push(...po(o,t));return n}function Dh(e){const t=e.anyOf;if(!Array.isArray(t)||t.length<2)return e;const n=t,r=rs(n),o={...e};return delete o.anyOf,{...o,oneOf:n,...r?{discriminator:r}:{},[ar]:o[ar]??"union"}}function Lh(e,t,n){const{DEFAULT_CONFIG:r}=require("ts-json-schema-generator/dist/src/Config.js"),o={...r,...e},s=o.path,i=xh(s,o.tsconfig);let a;a=n?n.statVersion(s):ru(s);let c;if(i!==void 0){const l=(n==null?void 0:n.generatorCache.get(i))??Ih(i);l&&l.version===a&&(c=l.gen)}if(!c){const{createProgram:l}=require("ts-json-schema-generator/dist/factory/program.js"),f=Ah(),p=kh(f.SyntaxKind.BigIntKeyword,f.SyntaxKind.TypeReference),h=l(o),d=wt.createParser(h,o,p),v=wt.createFormatter(o);if(c=new wt.SchemaGenerator(h,d,v,o),n&&n.stats.generatorsBuilt++,i!==void 0&&a!==void 0){const m={version:a,gen:c};Ph(i,m),n==null||n.generatorCache.set(i,m)}}const u=c.createSchema(o.type);return Rh(u),Mh(u),u}function Uh(e,t){let n=e.trim();if(n=uu(n),t!=null&&t.size){const o=t.get(n);if(o!==void 0)return o}const r=n.match(/^ReadonlyArray<(.+)>$/);for(r&&(n=`${r[1].trim()}[]`);n.startsWith("readonly ");)n=n.slice(9).trim();return n}function cu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Bh=Object.entries(au).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${cu(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function uu(e){let t=e;for(const{pattern:n,key:r}of Bh)t=t.replace(n,r);return t}function Fh(e,t){let n=uu(e);for(const[r,o]of t)n=n.replace(new RegExp(`\\b${cu(r)}\\b`,"g"),o);return n}async function vn(e,t,n,r,o,s){const i=t.getFilePath(),a=`${i}\0${r??""}\0${n}`,c=s??new Set;if(c.has(a))return{};if(!o){const d=new Set(c);return d.add(a),ua(e,t,n,r,void 0,d)}const u=o.schemaCache.get(a);if(u!==void 0)return o.stats.schemaCacheHits++,u;const l=dh(i,r,o.statVersion(i)),f=l.get(n);if(f!==void 0)return o.stats.schemaCacheHits++,o.schemaCache.set(a,Promise.resolve(f)),f;o.stats.schemaCacheMisses++;const p=new Set(c);p.add(a);const h=ua(e,t,n,r,o,p).then(d=>(l.set(n,d),d)).catch(d=>{throw o.schemaCache.delete(a),d});return o.schemaCache.set(a,h),h}async function ua(e,t,n,r,o,s){if(["void","undefined","null","Promise<void>"].includes(n))return{type:"null"};let i;if(o){const p=o.aliasCache.get(t);i=p??ca(t),p||o.aliasCache.set(t,i)}else i=ca(t);const a=Uh(n,i),c=lo[a];if(c!==void 0)return c;const u=await _h(a,p=>vn(e,t,p,r,o,s));if(u!==void 0)return u;const l=(o==null?void 0:o.zodImportCache.get(t))??Ch(t);if(o&&o.zodImportCache.set(t,l),!l)try{const p={path:t.getFilePath(),type:a,skipTypeCheck:!0,tsconfig:r,topRef:!1},h=Lh(p,!0,o);return Dh(h)}catch{}try{const p=await Sh(e,t,a,h=>su(h,d=>vn(e,t,d,r,o,s),0));if(p!==void 0)return p}catch{}const f=Fh(a,i);return Hn(f,0,i)}function os(e,t,n){if(e!=null&&e.hasInitializer()){const r=e.getInitializer();if(r)return r.getText()}return Vh(n,t)}function Vh(e,t){var n;const r=e,o=((n=r==null?void 0:r.getJsDocs)==null?void 0:n.call(r))??[],s=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\[\\s*${s}\\s*=\\s*([^\\]]+)\\]`);for(const a of o)for(const c of a.getTags()){if(c.getTagName()!=="param")continue;const u=c.getText().match(i);if(u)return u[1].trim()}}function Kh(e){const t=e.trim(),n=t.match(/^(['"`])([\s\S]*)\1$/);if(n)return n[2];if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;if(t!=="undefined"){if(/^-?\d+(\.\d+)?$/.test(t))return Number(t);try{return JSON.parse(t)}catch{return t}}}function qh(e,t){const n=Kh(t);if(n===void 0)return;e.default=n;const r=typeof n=="string"?n:JSON.stringify(n),o=typeof e.description=="string"?e.description:void 0;e.description=o?`${o} (default: ${r})`:`(default: ${r})`}async function zh(e){const t=e.session===void 0,n=hh(e.session??ph());try{return await Gh(e,n)}finally{t&&n.dispose()}}async function Gh(e,t){const{sourceFile:n,namespace:r="",tsconfig:o}=e,s=t.projectFor(o),i=t.sourceFileFor(n,o),a=F.basename(n),c=Je(Qh(a)),u=Je(r),l=[];for(const[h,d]of i.getExportedDeclarations()){if(h==="default"||Tn(h))continue;const v=Zh(d);if(v){const w=v.getSignature(),S=la(w,v),N=w.getReturnType().getText();l.push(await xn(s,i,u,c,h,S,N,v.isAsync(),o,t));continue}const m=d.find(w=>w.getKindName()==="VariableDeclaration");if(!m)continue;const g=m.getInitializer(),$=g==null?void 0:g.getKindName();if(g&&["ArrowFunction","FunctionExpression"].includes($??"")){const w=m.getType().getCallSignatures();if(w.length===0)continue;const S=w[0],N=fa(S,m,m.getVariableStatement()),x=S.getReturnType().getText(),M=g.isAsync();l.push(await xn(s,i,u,c,h,N,x,M,o,t))}else if($==="ObjectLiteralExpression"){const w=m.getType();for(const S of w.getProperties()){const N=S.getName();if(Tn(N))continue;const x=S.getTypeAtLocation(m).getCallSignatures();if(x.length===0)continue;const M=x[0],q=fa(M,m,m.getVariableStatement()),Q=M.getReturnType().getText(),te=[c,Je(h),Je(N)];l.push(await Jn(s,i,u,te,N,q,Q,!1,o,t))}}else{const w=m.getType(),S=w.getText();if(gt(w,m)){const N=await vn(s,i,S,o,t);l.push(Jh(u,c,h,N))}else console.warn(`[apigen-core] Skipping non-callable, non-serializable export: ${h}`)}}const f=i.getDefaultExportSymbol();if(f){const h=i.getExportAssignment(d=>!d.isExportEquals());if(h){const d=h.getExpression(),v=d.getKindName();if(["ArrowFunction","FunctionExpression"].includes(v)){const m=d.getType().getCallSignatures();if(m.length>0){const g=m[0],$=Br(g,h),w=g.getReturnType().getText(),S=d.isAsync();l.push(await xn(s,i,u,c,"default",$,w,S,o,t))}}else{const m=d.getType();for(const g of m.getProperties()){const $=g.getName();if(Tn($))continue;const w=g.getTypeAtLocation(h).getCallSignatures();if(w.length===0)continue;const S=w[0],N=Br(S,h),x=S.getReturnType().getText(),M=[c,Je("default"),Je($)];l.push(await Jn(s,i,u,M,$,N,x,!1,o,t))}}}else{const d=f.getDeclarations();for(const v of d){if(v.getKindName()!=="FunctionDeclaration")continue;const m=v,g=m.getName(),$=g&&g.length>0?g:"default",w=m.getSignature(),S=la(w,m),N=w.getReturnType().getText();l.push(await xn(s,i,u,c,$,S,N,m.isAsync(),o,t))}}}const p=Yh(i);if(p.length>0)for(const{name:h,sig:d}of p){if(Tn(h))continue;const v=Br(d),m=d.getReturnType().getText(),g=[c,Je(h)];l.push(await Jn(s,i,u,g,h,v,m,!1,o,t))}return l}function Hh(e,t,n,r){const o=new Set,s=i=>{if(Array.isArray(i))return i.map(s);if(!i||typeof i!="object"||o.has(i))return i;o.add(i);try{const a=i,c={};for(const[u,l]of Object.entries(a)){if(u==="definitions"||u==="$defs"){const f=u,p=t[f];for(const[h,d]of Object.entries(l)){const v=s(d),m=p[h];if(m!==void 0&&JSON.stringify(m)!==JSON.stringify(v))throw new Error(`[apigen-core-client] Function "${n}": param "${r}" contributes a "${f}.${h}" definition that conflicts with an identically-named definition already hoisted from another param/output in the same function. Two structurally different types share the same generated definition key, so apigen cannot safely merge them into one function-level schema.`);p[h]=v}continue}c[u]=s(l)}return c}finally{o.delete(i)}};return s(e)}async function xn(e,t,n,r,o,s,i,a,c,u){const l=Je(o);return Jn(e,t,n,[r,l],o,s,i,a,c,u)}async function Jn(e,t,n,r,o,s,i,a,c,u){const l=s.length>0&&s[0].name==="ctx",f=s.filter($=>$.name!=="ctx"),p=f.filter($=>!$.optional).map($=>$.name),h={},d={definitions:{},$defs:{}};for(const $ of f){const w=await vn(e,t,$.type,c,u),S=Hh(w,d,o,$.name);$.defaultValue!==void 0&&qh(S,$.defaultValue),h[$.name]=S}const v=i.replace(/^Promise<(.+)>$/,"$1").trim(),m=await vn(e,t,v,c,u),g={type:"object",properties:h,required:p,...Object.keys(d.definitions).length>0?{definitions:d.definitions}:{},...Object.keys(d.$defs).length>0?{$defs:d.$defs}:{}};return{id:lu(n,r),host:"ts",namespace:n,path:r,kind:"action",async:a,streaming:!1,safe:!1,input:g,output:m,envelope:{},typeText:{lang:"ts",input:Xh(s),output:v},...l?{hasCtx:!0}:{}}}function Jh(e,t,n,r){const o=Je(n),s=[t,o];return{id:lu(e,s),host:"ts",namespace:e,path:s,kind:"query",async:!1,streaming:!1,safe:!0,input:{type:"object",properties:{},required:[]},output:r,envelope:{},typeText:null}}function lu(e,t){return(e.raw?[e,...t]:t).map(n=>n.words.join("-")).join("/")}function Wh(e){return e.split(/[-_.]+/).flatMap(t=>t.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").split("_").filter(Boolean)).map(t=>t.toLowerCase()).filter(Boolean)}function Je(e){return{raw:e,words:Wh(e)}}function Qh(e){return e.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function Yh(e){const t=[];for(const n of e.getStatements()){if(n.getKindName()!=="ExpressionStatement")continue;const r=n.getExpression();if(r.getKindName()!=="BinaryExpression")continue;const o=r;if(o.getLeft().getText().trim()!=="module.exports"||o.getOperatorToken().getKindName()!=="EqualsToken")continue;const s=o.getRight(),i=s.getType();for(const a of i.getProperties()){const c=a.getTypeAtLocation(s).getCallSignatures();c.length!==0&&t.push({name:a.getName(),sig:c[0]})}}return t}function Zh(e){let t;for(const n of e){if(n.getKindName()!=="FunctionDeclaration")continue;const r=n;if(t||(t=r),r.getBody())return r}return t}function la(e,t){return e.getParameters().map(n=>{var r;const o=n.getDeclarations(),s=o.length>0&&o[0].getKindName()==="Parameter"?o[0]:null,i=n.isOptional()||((s==null?void 0:s.hasInitializer())??!1)||(((r=s==null?void 0:s.hasQuestionToken)==null?void 0:r.call(s))??!1);return{name:n.getName(),type:n.getTypeAtLocation(e.getDeclaration()).getText(),optional:i,defaultValue:os(s,n.getName(),t)}})}function fa(e,t,n){return e.getParameters().map(r=>{var o;const s=r.getDeclarations(),i=s.length>0&&s[0].getKindName()==="Parameter"?s[0]:null,a=r.isOptional()||((i==null?void 0:i.hasInitializer())??!1)||(((o=i==null?void 0:i.hasQuestionToken)==null?void 0:o.call(i))??!1);return{name:r.getName(),type:r.getTypeAtLocation(t).getText(),optional:a,defaultValue:os(i,r.getName(),n??t)}})}function Br(e,t){return e.getParameters().map(n=>{var r,o,s;const i=n.getDeclarations(),a=i.length>0&&i[0].getKindName()==="Parameter"?i[0]:null,c=n.isOptional()||((a==null?void 0:a.hasInitializer())??!1)||(((r=a==null?void 0:a.hasQuestionToken)==null?void 0:r.call(a))??!1);return{name:n.getName(),type:a?a.getType().getText():((s=(o=n.getValueDeclaration())==null?void 0:o.getType())==null?void 0:s.getText())??"unknown",optional:c,defaultValue:os(a,n.getName(),t)}})}function Xh(e){const t=e.filter(n=>n.name!=="ctx");return t.length===0?"()":"("+t.map(n=>`${n.name}${n.optional?"?":""}: ${n.type}`).join(", ")+")"}function Tn(e){return!!(e==="__samples__"||e.startsWith("__"))}function gt(e,t,n=new Set){if(e.getCallSignatures().length>0||e.getConstructSignatures().length>0)return!1;if(e.isString()||e.isNumber()||e.isBoolean()||e.isNull()||e.isUndefined()||e.isStringLiteral()||e.isNumberLiteral()||e.isBooleanLiteral()||e.isEnumLiteral())return!0;if(e.isArray()||e.isReadonlyArray()){const r=e.getArrayElementType();return r?gt(r,t,n):!1}if(e.isTuple())return e.getTupleElements().every(r=>gt(r,t,n));if(e.isUnion())return e.getUnionTypes().every(r=>gt(r,t,n));if(e.isIntersection())return e.getIntersectionTypes().every(r=>gt(r,t,n));if(e.isObject()){const r=e.getText(t);if(n.has(r))return!0;n.add(r);const o=e.getStringIndexType(),s=e.getNumberIndexType();if(o||s)return[o,s].every(a=>!a||gt(a,t,n));const i=e.getProperties();return i.length===0?!0:i.every(a=>{const c=a.getTypeAtLocation(t);return gt(c,t,n)})}return!1}function da(e){return e.words.join("-")}function pa(e){return e.words.map(tm).join("")}function ha(e){return e.words.join("_")}function em(e,t={}){var p,h;const n=[e.namespace,...e.path],r=e.safe||ou(e.input)?"GET":"POST",o=((h=(p=t.http)==null?void 0:p.verb)==null?void 0:h[e.id])??r,s="/"+n.map(d=>da(d)).join("/"),i=n.map(d=>ha(d)).join("_"),c=n.map(d=>ha(d)).slice(0,-1).join("."),u=pa(n[n.length-2]??n[0]),l=pa(n[n.length-1]),f=n.map(d=>da(d));return{http:{verb:o,route:s},mcp:{name:i},grpc:{package:c,service:u,method:l},cli:{path:f}}}function tm(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function ss(e,t=5e3){e!==":memory:"&&W.mkdirSync(F.dirname(e),{recursive:!0});const n=new Fd(e);if(n.pragma("journal_mode = WAL"),!Number.isInteger(t)||t<0)throw new RangeError(`openGraphBacklogStore: busyTimeoutMs must be a non-negative integer, got ${t}`);const r=Vd.createGraphBackend(n);return r.applySchema(),n.pragma(`busy_timeout = ${t}`),{db:n,graph:r}}function is(e){e.db.close()}const nm=[".git",".adhd","adhd.environment.yaml"];function Fr(e){let t=F.resolve(e);const{root:n}=F.parse(t);for(;;){for(const o of nm)if(W.existsSync(`${t}/${o}`))return t;if(t===n)return;const r=F.dirname(t);if(r===t)return;t=r}}const rm=new Set(["system","global","project"]);function om(e,t){const n=e.cwd??process.cwd();if(e.scope)return e.scope==="project"?{scope:"project",projectRoot:Fr(n)??n}:{scope:e.scope};const r=t.ADHD_ENV_SCOPE;if(r!==void 0&&rm.has(r)){const s=r;return s==="project"?{scope:"project",projectRoot:Fr(n)??n}:{scope:s}}const o=Fr(n);return o?{scope:"project",projectRoot:o}:{scope:"global"}}function ma(e){return`.${e}`}function sm(e){const t=Gt.homedir();if(process.platform==="darwin")return F.join(t,"Library","Application Support",e);if(process.platform==="win32"){const r=process.env.APPDATA??F.join(t,"AppData","Roaming");return F.join(r,e)}const n=process.env.XDG_DATA_HOME??F.join(t,".local","share");return F.join(n,e)}function im(e){const t=e.orgNamespace,n=e.adhdRoot??F.join(Gt.homedir(),ma(t)),r=e.adhdRoot??sm(t),o={system:F.join(r,e.project,e.namespace),global:F.join(n,e.project,e.namespace)};return e.projectRoot&&(o.project=F.join(e.projectRoot,ma(t),e.project,e.namespace)),o}function fu(e,t){return t==="project"?e.project??e.global:e[t]}function am(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function cm(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var n=function r(){return this instanceof r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,o.get?o:{enumerable:!0,get:function(){return e[r]}})}),n}const ae={ANCHOR:"&",COMMENT:"#",TAG:"!",DIRECTIVES_END:"-",DOCUMENT_END:"."},j={ALIAS:"ALIAS",BLANK_LINE:"BLANK_LINE",BLOCK_FOLDED:"BLOCK_FOLDED",BLOCK_LITERAL:"BLOCK_LITERAL",COMMENT:"COMMENT",DIRECTIVE:"DIRECTIVE",DOCUMENT:"DOCUMENT",FLOW_MAP:"FLOW_MAP",FLOW_SEQ:"FLOW_SEQ",MAP:"MAP",MAP_KEY:"MAP_KEY",MAP_VALUE:"MAP_VALUE",PLAIN:"PLAIN",QUOTE_DOUBLE:"QUOTE_DOUBLE",QUOTE_SINGLE:"QUOTE_SINGLE",SEQ:"SEQ",SEQ_ITEM:"SEQ_ITEM"},Wn="tag:yaml.org,2002:",ot={MAP:"tag:yaml.org,2002:map",SEQ:"tag:yaml.org,2002:seq",STR:"tag:yaml.org,2002:str"};function ga(e){const t=[0];let n=e.indexOf(`
8
- `);for(;n!==-1;)n+=1,t.push(n),n=e.indexOf(`
9
- `,n);return t}function du(e){let t,n;return typeof e=="string"?(t=ga(e),n=e):(Array.isArray(e)&&(e=e[0]),e&&e.context&&(e.lineStarts||(e.lineStarts=ga(e.context.src)),t=e.lineStarts,n=e.context.src)),{lineStarts:t,src:n}}function ho(e,t){if(typeof e!="number"||e<0)return null;const{lineStarts:n,src:r}=du(t);if(!n||!r||e>r.length)return null;for(let s=0;s<n.length;++s){const i=n[s];if(e<i)return{line:s,col:e-n[s-1]+1};if(e===i)return{line:s+1,col:1}}const o=n.length;return{line:o,col:e-n[o-1]+1}}function um(e,t){const{lineStarts:n,src:r}=du(t);if(!n||!(e>=1)||e>n.length)return null;const o=n[e-1];let s=n[e];for(;s&&s>o&&r[s-1]===`
10
- `;)--s;return r.slice(o,s)}function lm({start:e,end:t},n,r=80){let o=um(e.line,n);if(!o)return null;let{col:s}=e;if(o.length>r)if(s<=r-10)o=o.substr(0,r-1)+"…";else{const l=Math.round(r/2);o.length>s+l&&(o=o.substr(0,s+l-1)+"…"),s-=o.length-r,o="…"+o.substr(1-r)}let i=1,a="";t&&(t.line===e.line&&s+(t.col-e.col)<=r+1?i=t.col-e.col:(i=Math.min(o.length+1,r)-s,a="…"));const c=s>1?" ".repeat(s-1):"",u="^".repeat(i);return`${o}
11
- ${c}${u}${a}`}let oe=class pu{static copy(t){return new pu(t.start,t.end)}constructor(t,n){this.start=t,this.end=n||t}isEmpty(){return typeof this.start!="number"||!this.end||this.end<=this.start}setOrigRange(t,n){const{start:r,end:o}=this;if(t.length===0||o<=t[0])return this.origStart=r,this.origEnd=o,n;let s=n;for(;s<t.length&&!(t[s]>r);)++s;this.origStart=r+s;const i=s;for(;s<t.length&&!(t[s]>=o);)++s;return this.origEnd=o+s,i}},R=class He{static addStringTerminator(t,n,r){if(r[r.length-1]===`
12
- `)return r;const o=He.endOfWhiteSpace(t,n);return o>=t.length||t[o]===`
13
- `?r+`
14
- `:r}static atDocumentBoundary(t,n,r){const o=t[n];if(!o)return!0;const s=t[n-1];if(s&&s!==`
15
- `)return!1;if(r){if(o!==r)return!1}else if(o!==ae.DIRECTIVES_END&&o!==ae.DOCUMENT_END)return!1;const i=t[n+1],a=t[n+2];if(i!==o||a!==o)return!1;const c=t[n+3];return!c||c===`
16
- `||c===" "||c===" "}static endOfIdentifier(t,n){let r=t[n];const o=r==="<",s=o?[`
17
- `," "," ",">"]:[`
18
- `," "," ","[","]","{","}",","];for(;r&&s.indexOf(r)===-1;)r=t[n+=1];return o&&r===">"&&(n+=1),n}static endOfIndent(t,n){let r=t[n];for(;r===" ";)r=t[n+=1];return n}static endOfLine(t,n){let r=t[n];for(;r&&r!==`
19
- `;)r=t[n+=1];return n}static endOfWhiteSpace(t,n){let r=t[n];for(;r===" "||r===" ";)r=t[n+=1];return n}static startOfLine(t,n){let r=t[n-1];if(r===`
20
- `)return n;for(;r&&r!==`
21
- `;)r=t[n-=1];return n+1}static endOfBlockIndent(t,n,r){const o=He.endOfIndent(t,r);if(o>r+n)return o;{const s=He.endOfWhiteSpace(t,o),i=t[s];if(!i||i===`
22
- `)return s}return null}static atBlank(t,n,r){const o=t[n];return o===`
23
- `||o===" "||o===" "||r&&!o}static nextNodeIsIndented(t,n,r){return!t||n<0?!1:n>0?!0:r&&t==="-"}static normalizeOffset(t,n){const r=t[n];return r?r!==`
24
- `&&t[n-1]===`
25
- `?n-1:He.endOfWhiteSpace(t,n):n}static foldNewline(t,n,r){let o=0,s=!1,i="",a=t[n+1];for(;a===" "||a===" "||a===`
26
- `;){switch(a){case`
27
- `:o=0,n+=1,i+=`
28
- `;break;case" ":o<=r&&(s=!0),n=He.endOfWhiteSpace(t,n+2)-1;break;case" ":o+=1,n+=1;break}a=t[n+1]}return i||(i=" "),a&&o<=r&&(s=!0),{fold:i,offset:n,error:s}}constructor(t,n,r){Object.defineProperty(this,"context",{value:r||null,writable:!0}),this.error=null,this.range=null,this.valueRange=null,this.props=n||[],this.type=t,this.value=null}getPropValue(t,n,r){if(!this.context)return null;const{src:o}=this.context,s=this.props[t];return s&&o[s.start]===n?o.slice(s.start+(r?1:0),s.end):null}get anchor(){for(let t=0;t<this.props.length;++t){const n=this.getPropValue(t,ae.ANCHOR,!0);if(n!=null)return n}return null}get comment(){const t=[];for(let n=0;n<this.props.length;++n){const r=this.getPropValue(n,ae.COMMENT,!0);r!=null&&t.push(r)}return t.length>0?t.join(`
29
- `):null}commentHasRequiredWhitespace(t){const{src:n}=this.context;if(this.header&&t===this.header.end||!this.valueRange)return!1;const{end:r}=this.valueRange;return t!==r||He.atBlank(n,r-1)}get hasComment(){if(this.context){const{src:t}=this.context;for(let n=0;n<this.props.length;++n)if(t[this.props[n].start]===ae.COMMENT)return!0}return!1}get hasProps(){if(this.context){const{src:t}=this.context;for(let n=0;n<this.props.length;++n)if(t[this.props[n].start]!==ae.COMMENT)return!0}return!1}get includesTrailingLines(){return!1}get jsonLike(){return[j.FLOW_MAP,j.FLOW_SEQ,j.QUOTE_DOUBLE,j.QUOTE_SINGLE].indexOf(this.type)!==-1}get rangeAsLinePos(){if(!this.range||!this.context)return;const t=ho(this.range.start,this.context.root);if(!t)return;const n=ho(this.range.end,this.context.root);return{start:t,end:n}}get rawValue(){if(!this.valueRange||!this.context)return null;const{start:t,end:n}=this.valueRange;return this.context.src.slice(t,n)}get tag(){for(let t=0;t<this.props.length;++t){const n=this.getPropValue(t,ae.TAG,!1);if(n!=null){if(n[1]==="<")return{verbatim:n.slice(2,-1)};{const[r,o,s]=n.match(/^(.*!)([^!]*)$/);return{handle:o,suffix:s}}}}return null}get valueRangeContainsNewline(){if(!this.valueRange||!this.context)return!1;const{start:t,end:n}=this.valueRange,{src:r}=this.context;for(let o=t;o<n;++o)if(r[o]===`
30
- `)return!0;return!1}parseComment(t){const{src:n}=this.context;if(n[t]===ae.COMMENT){const r=He.endOfLine(n,t+1),o=new oe(t,r);return this.props.push(o),r}return t}setOrigRanges(t,n){return this.range&&(n=this.range.setOrigRange(t,n)),this.valueRange&&this.valueRange.setOrigRange(t,n),this.props.forEach(r=>r.setOrigRange(t,n)),n}toString(){const{context:{src:t},range:n,value:r}=this;if(r!=null)return r;const o=t.slice(n.start,n.end);return He.addStringTerminator(t,n.end,o)}},_t=class extends Error{constructor(t,n,r){if(!r||!(n instanceof R))throw new Error(`Invalid arguments for new ${t}`);super(),this.name=t,this.message=r,this.source=n}makePretty(){if(!this.source)return;this.nodeType=this.source.type;const t=this.source.context&&this.source.context.root;if(typeof this.offset=="number"){this.range=new oe(this.offset,this.offset+1);const n=t&&ho(this.offset,t);if(n){const r={line:n.line,col:n.col+1};this.linePos={start:n,end:r}}delete this.offset}else this.range=this.source.range,this.linePos=this.source.rangeAsLinePos;if(this.linePos){const{line:n,col:r}=this.linePos.start;this.message+=` at line ${n}, column ${r}`;const o=t&&lm(this.linePos,t);o&&(this.message+=`:
31
-
32
- ${o}
33
- `)}delete this.source}},$n=class extends _t{constructor(t,n){super("YAMLReferenceError",t,n)}},V=class extends _t{constructor(t,n){super("YAMLSemanticError",t,n)}},ge=class extends _t{constructor(t,n){super("YAMLSyntaxError",t,n)}},Qt=class extends _t{constructor(t,n){super("YAMLWarning",t,n)}};function ve(e,t,n){return(t=dm(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function fm(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function dm(e){var t=fm(e,"string");return typeof t=="symbol"?t:t+""}let hu=class mo extends R{static endOfLine(t,n,r){let o=t[n],s=n;for(;o&&o!==`
34
- `&&!(r&&(o==="["||o==="]"||o==="{"||o==="}"||o===","));){const i=t[s+1];if(o===":"&&(!i||i===`
35
- `||i===" "||i===" "||r&&i===",")||(o===" "||o===" ")&&i==="#")break;s+=1,o=i}return s}get strValue(){if(!this.valueRange||!this.context)return null;let{start:t,end:n}=this.valueRange;const{src:r}=this.context;let o=r[n-1];for(;t<n&&(o===`
36
- `||o===" "||o===" ");)o=r[--n-1];let s="";for(let a=t;a<n;++a){const c=r[a];if(c===`
37
- `){const{fold:u,offset:l}=R.foldNewline(r,a,-1);s+=u,a=l}else if(c===" "||c===" "){const u=a;let l=r[a+1];for(;a<n&&(l===" "||l===" ");)a+=1,l=r[a+1];l!==`
38
- `&&(s+=a>u?r.slice(u,a+1):c)}else s+=c}const i=r[t];switch(i){case" ":{const a="Plain value cannot start with a tab character";return{errors:[new V(this,a)],str:s}}case"@":case"`":{const a=`Plain value cannot start with reserved character ${i}`;return{errors:[new V(this,a)],str:s}}default:return s}}parseBlockValue(t){const{indent:n,inFlow:r,src:o}=this.context;let s=t,i=t;for(let a=o[s];a===`
39
- `&&!R.atDocumentBoundary(o,s+1);a=o[s]){const c=R.endOfBlockIndent(o,n,s+1);if(c===null||o[c]==="#")break;o[c]===`
40
- `?s=c:(i=mo.endOfLine(o,c,r),s=i)}return this.valueRange.isEmpty()&&(this.valueRange.start=t),this.valueRange.end=i,i}parse(t,n){this.context=t;const{inFlow:r,src:o}=t;let s=n;const i=o[s];return i&&i!=="#"&&i!==`
41
- `&&(s=mo.endOfLine(o,n,r)),this.valueRange=new oe(n,s),s=R.endOfWhiteSpace(o,s),s=this.parseComment(s),(!this.hasComment||this.valueRange.isEmpty())&&(s=this.parseBlockValue(s)),s}},wn=class extends R{constructor(){super(j.BLANK_LINE)}get includesTrailingLines(){return!0}parse(t,n){return this.context=t,this.range=new oe(n,n+1),n+1}};class as extends R{constructor(t,n){super(t,n),this.node=null}get includesTrailingLines(){return!!this.node&&this.node.includesTrailingLines}parse(t,n){this.context=t;const{parseNode:r,src:o}=t;let{atLineStart:s,lineStart:i}=t;!s&&this.type===j.SEQ_ITEM&&(this.error=new V(this,"Sequence items must not have preceding content on the same line"));const a=s?n-i:t.indent;let c=R.endOfWhiteSpace(o,n+1),u=o[c];const l=u==="#",f=[];let p=null;for(;u===`
42
- `||u==="#";){if(u==="#"){const d=R.endOfLine(o,c+1);f.push(new oe(c,d)),c=d}else{s=!0,i=c+1;const d=R.endOfWhiteSpace(o,i);o[d]===`
43
- `&&f.length===0&&(p=new wn,i=p.parse({src:o},i)),c=R.endOfIndent(o,i)}u=o[c]}if(R.nextNodeIsIndented(u,c-(i+a),this.type!==j.SEQ_ITEM)?this.node=r({atLineStart:s,inCollection:!1,indent:a,lineStart:i,parent:this},c):u&&i>n+1&&(c=i-1),this.node){if(p){const d=t.parent.items||t.parent.contents;d&&d.push(p)}f.length&&Array.prototype.push.apply(this.props,f),c=this.node.range.end}else if(l){const d=f[0];this.props.push(d),c=d.end}else c=R.endOfLine(o,n+1);const h=this.node?this.node.valueRange.end:c;return this.valueRange=new oe(n,h),c}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.node?this.node.setOrigRanges(t,n):n}toString(){const{context:{src:t},node:n,range:r,value:o}=this;if(o!=null)return o;const s=n?t.slice(r.start,n.range.start)+String(n):t.slice(r.start,r.end);return R.addStringTerminator(t,r.end,s)}}let dn=class extends R{constructor(){super(j.COMMENT)}parse(t,n){this.context=t;const r=this.parseComment(n);return this.range=new oe(n,r),r}};function go(e){let t=e;for(;t instanceof as;)t=t.node;if(!(t instanceof mu))return null;const n=t.items.length;let r=-1;for(let i=n-1;i>=0;--i){const a=t.items[i];if(a.type===j.COMMENT){const{indent:c,lineStart:u}=a.context;if(c>0&&a.range.start>=u+c)break;r=i}else if(a.type===j.BLANK_LINE)r=i;else break}if(r===-1)return null;const o=t.items.splice(r,n-r),s=o[0].range.start;for(;t.range.end=s,t.valueRange&&t.valueRange.end>s&&(t.valueRange.end=s),t!==e;)t=t.context.parent;return o}let mu=class yo extends R{static nextContentHasIndent(t,n,r){const o=R.endOfLine(t,n)+1;n=R.endOfWhiteSpace(t,o);const s=t[n];return s?n>=o+r?!0:s!=="#"&&s!==`
44
- `?!1:yo.nextContentHasIndent(t,n,r):!1}constructor(t){super(t.type===j.SEQ_ITEM?j.SEQ:j.MAP);for(let r=t.props.length-1;r>=0;--r)if(t.props[r].start<t.context.lineStart){this.props=t.props.slice(0,r+1),t.props=t.props.slice(r+1);const o=t.props[0]||t.valueRange;t.range.start=o.start;break}this.items=[t];const n=go(t);n&&Array.prototype.push.apply(this.items,n)}get includesTrailingLines(){return this.items.length>0}parse(t,n){this.context=t;const{parseNode:r,src:o}=t;let s=R.startOfLine(o,n);const i=this.items[0];i.context.parent=this,this.valueRange=oe.copy(i.valueRange);const a=i.range.start-i.context.lineStart;let c=n;c=R.normalizeOffset(o,c);let u=o[c],l=R.endOfWhiteSpace(o,s)===c,f=!1;for(;u;){for(;u===`
45
- `||u==="#";){if(l&&u===`
46
- `&&!f){const d=new wn;if(c=d.parse({src:o},c),this.valueRange.end=c,c>=o.length){u=null;break}this.items.push(d),c-=1}else if(u==="#"){if(c<s+a&&!yo.nextContentHasIndent(o,c,a))return c;const d=new dn;if(c=d.parse({indent:a,lineStart:s,src:o},c),this.items.push(d),this.valueRange.end=c,c>=o.length){u=null;break}}if(s=c+1,c=R.endOfIndent(o,s),R.atBlank(o,c)){const d=R.endOfWhiteSpace(o,c),v=o[d];(!v||v===`
47
- `||v==="#")&&(c=d)}u=o[c],l=!0}if(!u)break;if(c!==s+a&&(l||u!==":")){if(c<s+a){s>n&&(c=s);break}else if(!this.error){const d="All collection items must start at the same column";this.error=new ge(this,d)}}if(i.type===j.SEQ_ITEM){if(u!=="-"){s>n&&(c=s);break}}else if(u==="-"&&!this.error){const d=o[c+1];if(!d||d===`
48
- `||d===" "||d===" "){const v="A collection cannot be both a mapping and a sequence";this.error=new ge(this,v)}}const p=r({atLineStart:l,inCollection:!0,indent:a,lineStart:s,parent:this},c);if(!p)return c;if(this.items.push(p),this.valueRange.end=p.valueRange.end,c=R.normalizeOffset(o,p.range.end),u=o[c],l=!1,f=p.includesTrailingLines,u){let d=c-1,v=o[d];for(;v===" "||v===" ";)v=o[--d];v===`
49
- `&&(s=d+1,l=!0)}const h=go(p);h&&Array.prototype.push.apply(this.items,h)}return c}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.items.forEach(r=>{n=r.setOrigRanges(t,n)}),n}toString(){const{context:{src:t},items:n,range:r,value:o}=this;if(o!=null)return o;let s=t.slice(r.start,n[0].range.start)+String(n[0]);for(let i=1;i<n.length;++i){const a=n[i],{atLineStart:c,indent:u}=a.context;if(c)for(let l=0;l<u;++l)s+=" ";s+=String(a)}return R.addStringTerminator(t,r.end,s)}};class pm extends R{constructor(){super(j.DIRECTIVE),this.name=null}get parameters(){const t=this.rawValue;return t?t.trim().split(/[ \t]+/):[]}parseName(t){const{src:n}=this.context;let r=t,o=n[r];for(;o&&o!==`
50
- `&&o!==" "&&o!==" ";)o=n[r+=1];return this.name=n.slice(t,r),r}parseParameters(t){const{src:n}=this.context;let r=t,o=n[r];for(;o&&o!==`
51
- `&&o!=="#";)o=n[r+=1];return this.valueRange=new oe(t,r),r}parse(t,n){this.context=t;let r=this.parseName(n+1);return r=this.parseParameters(r),r=this.parseComment(r),this.range=new oe(n,r),r}}let hm=class vo extends R{static startCommentOrEndBlankLine(t,n){const r=R.endOfWhiteSpace(t,n),o=t[r];return o==="#"||o===`
52
- `?r:n}constructor(){super(j.DOCUMENT),this.directives=null,this.contents=null,this.directivesEndMarker=null,this.documentEndMarker=null}parseDirectives(t){const{src:n}=this.context;this.directives=[];let r=!0,o=!1,s=t;for(;!R.atDocumentBoundary(n,s,ae.DIRECTIVES_END);)switch(s=vo.startCommentOrEndBlankLine(n,s),n[s]){case`
53
- `:if(r){const i=new wn;s=i.parse({src:n},s),s<n.length&&this.directives.push(i)}else s+=1,r=!0;break;case"#":{const i=new dn;s=i.parse({src:n},s),this.directives.push(i),r=!1}break;case"%":{const i=new pm;s=i.parse({parent:this,src:n},s),this.directives.push(i),o=!0,r=!1}break;default:return o?this.error=new V(this,"Missing directives-end indicator line"):this.directives.length>0&&(this.contents=this.directives,this.directives=[]),s}return n[s]?(this.directivesEndMarker=new oe(s,s+3),s+3):(o?this.error=new V(this,"Missing directives-end indicator line"):this.directives.length>0&&(this.contents=this.directives,this.directives=[]),s)}parseContents(t){const{parseNode:n,src:r}=this.context;this.contents||(this.contents=[]);let o=t;for(;r[o-1]==="-";)o-=1;let s=R.endOfWhiteSpace(r,t),i=o===t;for(this.valueRange=new oe(s);!R.atDocumentBoundary(r,s,ae.DOCUMENT_END);){switch(r[s]){case`
54
- `:if(i){const a=new wn;s=a.parse({src:r},s),s<r.length&&this.contents.push(a)}else s+=1,i=!0;o=s;break;case"#":{const a=new dn;s=a.parse({src:r},s),this.contents.push(a),i=!1}break;default:{const a=R.endOfIndent(r,s),c=n({atLineStart:i,indent:-1,inFlow:!1,inCollection:!1,lineStart:o,parent:this},a);if(!c)return this.valueRange.end=a;this.contents.push(c),s=c.range.end,i=!1;const u=go(c);u&&Array.prototype.push.apply(this.contents,u)}}s=vo.startCommentOrEndBlankLine(r,s)}if(this.valueRange.end=s,r[s]&&(this.documentEndMarker=new oe(s,s+3),s+=3,r[s])){if(s=R.endOfWhiteSpace(r,s),r[s]==="#"){const a=new dn;s=a.parse({src:r},s),this.contents.push(a)}switch(r[s]){case`
55
- `:s+=1;break;case void 0:break;default:this.error=new ge(this,"Document end marker line cannot have a non-comment suffix")}}return s}parse(t,n){t.root=this,this.context=t;const{src:r}=t;let o=r.charCodeAt(n)===65279?n+1:n;return o=this.parseDirectives(o),o=this.parseContents(o),o}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.directives.forEach(r=>{n=r.setOrigRanges(t,n)}),this.directivesEndMarker&&(n=this.directivesEndMarker.setOrigRange(t,n)),this.contents.forEach(r=>{n=r.setOrigRanges(t,n)}),this.documentEndMarker&&(n=this.documentEndMarker.setOrigRange(t,n)),n}toString(){const{contents:t,directives:n,value:r}=this;if(r!=null)return r;let o=n.join("");return t.length>0&&((n.length>0||t[0].type===j.COMMENT)&&(o+=`---
56
- `),o+=t.join("")),o[o.length-1]!==`
57
- `&&(o+=`
58
- `),o}},mm=class extends R{parse(e,t){this.context=e;const{src:n}=e;let r=R.endOfIdentifier(n,t+1);return this.valueRange=new oe(t+1,r),r=R.endOfWhiteSpace(n,r),r=this.parseComment(r),r}};const tt={CLIP:"CLIP",KEEP:"KEEP",STRIP:"STRIP"};class gm extends R{constructor(t,n){super(t,n),this.blockIndent=null,this.chomping=tt.CLIP,this.header=null}get includesTrailingLines(){return this.chomping===tt.KEEP}get strValue(){if(!this.valueRange||!this.context)return null;let{start:t,end:n}=this.valueRange;const{indent:r,src:o}=this.context;if(this.valueRange.isEmpty())return"";let s=null,i=o[n-1];for(;i===`
59
- `||i===" "||i===" ";){if(n-=1,n<=t){if(this.chomping===tt.KEEP)break;return""}i===`
60
- `&&(s=n),i=o[n-1]}let a=n+1;s&&(this.chomping===tt.KEEP?(a=s,n=this.valueRange.end):n=s);const c=r+this.blockIndent,u=this.type===j.BLOCK_FOLDED;let l=!0,f="",p="",h=!1;for(let d=t;d<n;++d){for(let m=0;m<c&&o[d]===" ";++m)d+=1;const v=o[d];if(v===`
61
- `)p===`
62
- `?f+=`
63
- `:p=`
64
- `;else{const m=R.endOfLine(o,d),g=o.slice(d,m);d=m,u&&(v===" "||v===" ")&&d<a?(p===" "?p=`
65
- `:!h&&!l&&p===`
66
- `&&(p=`
67
-
68
- `),f+=p+g,p=m<n&&o[m]||"",h=!0):(f+=p+g,p=u&&d<a?" ":`
69
- `,h=!1),l&&g!==""&&(l=!1)}}return this.chomping===tt.STRIP?f:f+`
70
- `}parseBlockHeader(t){const{src:n}=this.context;let r=t+1,o="";for(;;){const s=n[r];switch(s){case"-":this.chomping=tt.STRIP;break;case"+":this.chomping=tt.KEEP;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":o+=s;break;default:return this.blockIndent=Number(o)||null,this.header=new oe(t,r),r}r+=1}}parseBlockValue(t){const{indent:n,src:r}=this.context,o=!!this.blockIndent;let s=t,i=t,a=1;for(let c=r[s];c===`
71
- `&&(s+=1,!R.atDocumentBoundary(r,s));c=r[s]){const u=R.endOfBlockIndent(r,n,s);if(u===null)break;const l=r[u],f=u-(s+n);if(this.blockIndent){if(l&&l!==`
72
- `&&f<this.blockIndent){if(r[u]==="#")break;if(!this.error){const p=`Block scalars must not be less indented than their ${o?"explicit indentation indicator":"first line"}`;this.error=new V(this,p)}}}else if(r[u]!==`
73
- `){if(f<a){const p="Block scalars with more-indented leading empty lines must use an explicit indentation indicator";this.error=new V(this,p)}this.blockIndent=f}else f>a&&(a=f);r[u]===`
74
- `?s=u:s=i=R.endOfLine(r,u)}return this.chomping!==tt.KEEP&&(s=r[i]?i+1:i),this.valueRange=new oe(t+1,s),s}parse(t,n){this.context=t;const{src:r}=t;let o=this.parseBlockHeader(n);return o=R.endOfWhiteSpace(r,o),o=this.parseComment(o),o=this.parseBlockValue(o),o}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.header?this.header.setOrigRange(t,n):n}}class ym extends R{constructor(t,n){super(t,n),this.items=null}prevNodeIsJsonLike(t=this.items.length){const n=this.items[t-1];return!!n&&(n.jsonLike||n.type===j.COMMENT&&this.prevNodeIsJsonLike(t-1))}parse(t,n){this.context=t;const{parseNode:r,src:o}=t;let{indent:s,lineStart:i}=t,a=o[n];this.items=[{char:a,offset:n}];let c=R.endOfWhiteSpace(o,n+1);for(a=o[c];a&&a!=="]"&&a!=="}";){switch(a){case`
75
- `:{i=c+1;const u=R.endOfWhiteSpace(o,i);if(o[u]===`
76
- `){const l=new wn;i=l.parse({src:o},i),this.items.push(l)}if(c=R.endOfIndent(o,i),c<=i+s&&(a=o[c],c<i+s||a!=="]"&&a!=="}")){const l="Insufficient indentation in flow collection";this.error=new V(this,l)}}break;case",":this.items.push({char:a,offset:c}),c+=1;break;case"#":{const u=new dn;c=u.parse({src:o},c),this.items.push(u)}break;case"?":case":":{const u=o[c+1];if(u===`
77
- `||u===" "||u===" "||u===","||a===":"&&this.prevNodeIsJsonLike()){this.items.push({char:a,offset:c}),c+=1;break}}default:{const u=r({atLineStart:!1,inCollection:!1,inFlow:!0,indent:-1,lineStart:i,parent:this},c);if(!u)return this.valueRange=new oe(n,c),c;this.items.push(u),c=R.normalizeOffset(o,u.range.end)}}c=R.endOfWhiteSpace(o,c),a=o[c]}return this.valueRange=new oe(n,c+1),a&&(this.items.push({char:a,offset:c}),c=R.endOfWhiteSpace(o,c+1),c=this.parseComment(c)),c}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.items.forEach(r=>{if(r instanceof R)n=r.setOrigRanges(t,n);else if(t.length===0)r.origOffset=r.offset;else{let o=n;for(;o<t.length&&!(t[o]>r.offset);)++o;r.origOffset=r.offset+o,n=o}}),n}toString(){const{context:{src:t},items:n,range:r,value:o}=this;if(o!=null)return o;const s=n.filter(c=>c instanceof R);let i="",a=r.start;return s.forEach(c=>{const u=t.slice(a,c.range.start);a=c.range.end,i+=u+String(c),i[i.length-1]===`
78
- `&&t[a-1]!==`
79
- `&&t[a]===`
80
- `&&(a+=1)}),i+=t.slice(a,r.end),R.addStringTerminator(t,r.end,i)}}class cs extends R{static endOfQuote(t,n){let r=t[n];for(;r&&r!=='"';)n+=r==="\\"?2:1,r=t[n];return n+1}get strValue(){if(!this.valueRange||!this.context)return null;const t=[],{start:n,end:r}=this.valueRange,{indent:o,src:s}=this.context;s[r-1]!=='"'&&t.push(new ge(this,'Missing closing "quote'));let i="";for(let a=n+1;a<r-1;++a){const c=s[a];if(c===`
81
- `){R.atDocumentBoundary(s,a+1)&&t.push(new V(this,"Document boundary indicators are not allowed within string values"));const{fold:u,offset:l,error:f}=R.foldNewline(s,a,o);i+=u,a=l,f&&t.push(new V(this,"Multi-line double-quoted string needs to be sufficiently indented"))}else if(c==="\\")switch(a+=1,s[a]){case"0":i+="\0";break;case"a":i+="\x07";break;case"b":i+="\b";break;case"e":i+="\x1B";break;case"f":i+="\f";break;case"n":i+=`
82
- `;break;case"r":i+="\r";break;case"t":i+=" ";break;case"v":i+="\v";break;case"N":i+="…";break;case"_":i+=" ";break;case"L":i+="\u2028";break;case"P":i+="\u2029";break;case" ":i+=" ";break;case'"':i+='"';break;case"/":i+="/";break;case"\\":i+="\\";break;case" ":i+=" ";break;case"x":i+=this.parseCharCode(a+1,2,t),a+=2;break;case"u":i+=this.parseCharCode(a+1,4,t),a+=4;break;case"U":i+=this.parseCharCode(a+1,8,t),a+=8;break;case`
83
- `:for(;s[a+1]===" "||s[a+1]===" ";)a+=1;break;default:t.push(new ge(this,`Invalid escape sequence ${s.substr(a-1,2)}`)),i+="\\"+s[a]}else if(c===" "||c===" "){const u=a;let l=s[a+1];for(;l===" "||l===" ";)a+=1,l=s[a+1];l!==`
84
- `&&(i+=a>u?s.slice(u,a+1):c)}else i+=c}return t.length>0?{errors:t,str:i}:i}parseCharCode(t,n,r){const{src:o}=this.context,s=o.substr(t,n),i=s.length===n&&/^[0-9a-fA-F]+$/.test(s)?parseInt(s,16):NaN;return isNaN(i)?(r.push(new ge(this,`Invalid escape sequence ${o.substr(t-2,n+2)}`)),o.substr(t-2,n+2)):String.fromCodePoint(i)}parse(t,n){this.context=t;const{src:r}=t;let o=cs.endOfQuote(r,n+1);return this.valueRange=new oe(n,o),o=R.endOfWhiteSpace(r,o),o=this.parseComment(o),o}}class us extends R{static endOfQuote(t,n){let r=t[n];for(;r;)if(r==="'"){if(t[n+1]!=="'")break;r=t[n+=2]}else r=t[n+=1];return n+1}get strValue(){if(!this.valueRange||!this.context)return null;const t=[],{start:n,end:r}=this.valueRange,{indent:o,src:s}=this.context;s[r-1]!=="'"&&t.push(new ge(this,"Missing closing 'quote"));let i="";for(let a=n+1;a<r-1;++a){const c=s[a];if(c===`
85
- `){R.atDocumentBoundary(s,a+1)&&t.push(new V(this,"Document boundary indicators are not allowed within string values"));const{fold:u,offset:l,error:f}=R.foldNewline(s,a,o);i+=u,a=l,f&&t.push(new V(this,"Multi-line single-quoted string needs to be sufficiently indented"))}else if(c==="'")i+=c,a+=1,s[a]!=="'"&&t.push(new ge(this,"Unescaped single quote? This should not happen."));else if(c===" "||c===" "){const u=a;let l=s[a+1];for(;l===" "||l===" ";)a+=1,l=s[a+1];l!==`
86
- `&&(i+=a>u?s.slice(u,a+1):c)}else i+=c}return t.length>0?{errors:t,str:i}:i}parse(t,n){this.context=t;const{src:r}=t;let o=us.endOfQuote(r,n+1);return this.valueRange=new oe(n,o),o=R.endOfWhiteSpace(r,o),o=this.parseComment(o),o}}function vm(e,t){switch(e){case j.ALIAS:return new mm(e,t);case j.BLOCK_FOLDED:case j.BLOCK_LITERAL:return new gm(e,t);case j.FLOW_MAP:case j.FLOW_SEQ:return new ym(e,t);case j.MAP_KEY:case j.MAP_VALUE:case j.SEQ_ITEM:return new as(e,t);case j.COMMENT:case j.PLAIN:return new hu(e,t);case j.QUOTE_DOUBLE:return new cs(e,t);case j.QUOTE_SINGLE:return new us(e,t);default:return null}}let $m=class Qn{static parseType(t,n,r){switch(t[n]){case"*":return j.ALIAS;case">":return j.BLOCK_FOLDED;case"|":return j.BLOCK_LITERAL;case"{":return j.FLOW_MAP;case"[":return j.FLOW_SEQ;case"?":return!r&&R.atBlank(t,n+1,!0)?j.MAP_KEY:j.PLAIN;case":":return!r&&R.atBlank(t,n+1,!0)?j.MAP_VALUE:j.PLAIN;case"-":return!r&&R.atBlank(t,n+1,!0)?j.SEQ_ITEM:j.PLAIN;case'"':return j.QUOTE_DOUBLE;case"'":return j.QUOTE_SINGLE;default:return j.PLAIN}}constructor(t={},{atLineStart:n,inCollection:r,inFlow:o,indent:s,lineStart:i,parent:a}={}){ve(this,"parseNode",(c,u)=>{if(R.atDocumentBoundary(this.src,u))return null;const l=new Qn(this,c),{props:f,type:p,valueStart:h}=l.parseProps(u),d=vm(p,f);let v=u;try{v=d.parse(l,h)}catch(m){const g=m instanceof Error?m.message:String(m);d.error||(d.error=new ge(d,g))}if(d.range=new oe(u,v),v<=u&&(d.error||(d.error=new Error("Node#parse consumed no characters")),d.error.parseEnd=v,d.error.source=d,d.range.end=u+1),l.nodeStartsCollection(d)){!d.error&&!l.atLineStart&&l.parent.type===j.DOCUMENT&&(d.error=new ge(d,"Block collection must not have preceding content here (e.g. directives-end indicator)"));const m=new mu(d);return v=m.parse(new Qn(l),v),m.range=new oe(u,v),m}return d}),this.atLineStart=n??(t.atLineStart||!1),this.inCollection=r??(t.inCollection||!1),this.inFlow=o??(t.inFlow||!1),this.indent=s??t.indent,this.lineStart=i??t.lineStart,this.parent=a??(t.parent||{}),this.root=t.root,this.src=t.src}nodeStartsCollection(t){const{inCollection:n,inFlow:r,src:o}=this;if(n||r)return!1;if(t instanceof as)return!0;let s=t.range.end;return o[s]===`
87
- `||o[s-1]===`
88
- `?!1:(s=R.endOfWhiteSpace(o,s),o[s]===":")}parseProps(t){const{inFlow:n,parent:r,src:o}=this,s=[];let i=!1;t=this.atLineStart?R.endOfIndent(o,t):R.endOfWhiteSpace(o,t);let a=o[t];for(;a===ae.ANCHOR||a===ae.COMMENT||a===ae.TAG||a===`
89
- `;){if(a===`
90
- `){let u=t,l;do l=u+1,u=R.endOfIndent(o,l);while(o[u]===`
91
- `);const f=u-(l+this.indent),p=r.type===j.SEQ_ITEM&&r.context.atLineStart;if(o[u]!=="#"&&!R.nextNodeIsIndented(o[u],f,!p))break;this.atLineStart=!0,this.lineStart=l,i=!1,t=u}else if(a===ae.COMMENT){const u=R.endOfLine(o,t+1);s.push(new oe(t,u)),t=u}else{let u=R.endOfIdentifier(o,t+1);a===ae.TAG&&o[u]===","&&/^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(o.slice(t+1,u+13))&&(u=R.endOfIdentifier(o,u+5)),s.push(new oe(t,u)),i=!0,t=R.endOfWhiteSpace(o,u)}a=o[t]}i&&a===":"&&R.atBlank(o,t+1,!0)&&(t-=1);const c=Qn.parseType(o,t,n);return{props:s,type:c,valueStart:t}}};function ls(e){const t=[];e.indexOf("\r")!==-1&&(e=e.replace(/\r\n?/g,(o,s)=>(o.length>1&&t.push(s),`
92
- `)));const n=[];let r=0;do{const o=new hm,s=new $m({src:e});r=o.parse(s,r),n.push(o)}while(r<e.length);return n.setOrigRanges=()=>{if(t.length===0)return!1;for(let s=1;s<t.length;++s)t[s]-=s;let o=0;for(let s=0;s<n.length;++s)o=n[s].setOrigRanges(t,o);return t.splice(0,t.length),!0},n.toString=()=>n.join(`...
93
- `),n}function wm(e,t,n){return n?`#${n.replace(/[\s\S]^/gm,`$&${t}#`)}
94
- ${t}${e}`:e}function Vt(e,t,n){return n?n.indexOf(`
95
- `)===-1?`${e} #${n}`:`${e}
96
- `+n.replace(/^/gm,`${t||""}#`):e}let Se=class{};function Le(e,t,n){if(Array.isArray(e))return e.map((r,o)=>Le(r,String(o),n));if(e&&typeof e.toJSON=="function"){const r=n&&n.anchors&&n.anchors.get(e);r&&(n.onCreate=s=>{r.res=s,delete n.onCreate});const o=e.toJSON(t,n);return r&&n.onCreate&&n.onCreate(o),o}return(!n||!n.keep)&&typeof e=="bigint"?Number(e):e}let X=class extends Se{constructor(t){super(),this.value=t}toJSON(t,n){return n&&n.keep?this.value:Le(this.value,t,n)}toString(){return String(this.value)}};function ya(e,t,n){let r=n;for(let o=t.length-1;o>=0;--o){const s=t[o];if(Number.isInteger(s)&&s>=0){const i=[];i[s]=r,r=i}else{const i={};Object.defineProperty(i,s,{value:r,writable:!0,enumerable:!0,configurable:!0}),r=i}}return e.createNode(r,!1)}const cn=e=>e==null||typeof e=="object"&&e[Symbol.iterator]().next().done;let me=class yt extends Se{constructor(t){super(),ve(this,"items",[]),this.schema=t}addIn(t,n){if(cn(t))this.add(n);else{const[r,...o]=t,s=this.get(r,!0);if(s instanceof yt)s.addIn(o,n);else if(s===void 0&&this.schema)this.set(r,ya(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}deleteIn([t,...n]){if(n.length===0)return this.delete(t);const r=this.get(t,!0);if(r instanceof yt)return r.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn([t,...n],r){const o=this.get(t,!0);return n.length===0?!r&&o instanceof X?o.value:o:o instanceof yt?o.getIn(n,r):void 0}hasAllNullValues(){return this.items.every(t=>{if(!t||t.type!=="PAIR")return!1;const n=t.value;return n==null||n instanceof X&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn([t,...n]){if(n.length===0)return this.has(t);const r=this.get(t,!0);return r instanceof yt?r.hasIn(n):!1}setIn([t,...n],r){if(n.length===0)this.set(t,r);else{const o=this.get(t,!0);if(o instanceof yt)o.setIn(n,r);else if(o===void 0&&this.schema)this.set(t,ya(this.schema,n,r));else throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}}toJSON(){return null}toString(t,{blockItem:n,flowChars:r,isMap:o,itemIndent:s},i,a){const{indent:c,indentStep:u,stringify:l}=t,f=this.type===j.FLOW_MAP||this.type===j.FLOW_SEQ||t.inFlow;f&&(s+=u);const p=o&&this.hasAllNullValues();t=Object.assign({},t,{allNullValues:p,indent:s,inFlow:f,type:null});let h=!1,d=!1;const v=this.items.reduce((g,$,w)=>{let S;$&&(!h&&$.spaceBefore&&g.push({type:"comment",str:""}),$.commentBefore&&$.commentBefore.match(/^.*$/gm).forEach(x=>{g.push({type:"comment",str:`#${x}`})}),$.comment&&(S=$.comment),f&&(!h&&$.spaceBefore||$.commentBefore||$.comment||$.key&&($.key.commentBefore||$.key.comment)||$.value&&($.value.commentBefore||$.value.comment))&&(d=!0)),h=!1;let N=l($,t,()=>S=null,()=>h=!0);return f&&!d&&N.includes(`
97
- `)&&(d=!0),f&&w<this.items.length-1&&(N+=","),N=Vt(N,s,S),h&&(S||f)&&(h=!1),g.push({type:"item",str:N}),g},[]);let m;if(v.length===0)m=r.start+r.end;else if(f){const{start:g,end:$}=r,w=v.map(S=>S.str);if(d||w.reduce((S,N)=>S+N.length+2,2)>yt.maxFlowStringSingleLineLength){m=g;for(const S of w)m+=S?`
98
- ${u}${c}${S}`:`
99
- `;m+=`
100
- ${c}${$}`}else m=`${g} ${w.join(" ")} ${$}`}else{const g=v.map(n);m=g.shift();for(const $ of g)m+=$?`
101
- ${c}${$}`:`
102
- `}return this.comment?(m+=`
103
- `+this.comment.replace(/^/gm,`${c}#`),i&&i()):h&&a&&a(),m}};ve(me,"maxFlowStringSingleLineLength",60);function Cn(e){let t=e instanceof X?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),Number.isInteger(t)&&t>=0?t:null}let Fe=class extends me{add(t){this.items.push(t)}delete(t){const n=Cn(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){const r=Cn(t);if(typeof r!="number")return;const o=this.items[r];return!n&&o instanceof X?o.value:o}has(t){const n=Cn(t);return typeof n=="number"&&n<this.items.length}set(t,n){const r=Cn(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);this.items[r]=n}toJSON(t,n){const r=[];n&&n.onCreate&&n.onCreate(r);let o=0;for(const s of this.items)r.push(Le(s,String(o++),n));return r}toString(t,n,r){return t?super.toString(t,{blockItem:o=>o.type==="comment"?o.str:`- ${o.str}`,flowChars:{start:"[",end:"]"},isMap:!1,itemIndent:(t.indent||"")+" "},n,r):JSON.stringify(this)}};const bm=(e,t,n)=>t===null?"":typeof t!="object"?String(t):e instanceof Se&&n&&n.doc?e.toString({anchors:Object.create(null),doc:n.doc,indent:"",indentStep:n.indentStep,inFlow:!0,inStringifyKey:!0,stringify:n.stringify}):JSON.stringify(t);let H=class gu extends Se{constructor(t,n=null){super(),this.key=t,this.value=n,this.type=gu.Type.PAIR}get commentBefore(){return this.key instanceof Se?this.key.commentBefore:void 0}set commentBefore(t){if(this.key==null&&(this.key=new X(null)),this.key instanceof Se)this.key.commentBefore=t;else{const n="Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.";throw new Error(n)}}addToJSMap(t,n){const r=Le(this.key,"",t);if(n instanceof Map){const o=Le(this.value,r,t);n.set(r,o)}else if(n instanceof Set)n.add(r);else{const o=bm(this.key,r,t),s=Le(this.value,o,t);o in n?Object.defineProperty(n,o,{value:s,writable:!0,enumerable:!0,configurable:!0}):n[o]=s}return n}toJSON(t,n){const r=n&&n.mapAsMap?new Map:{};return this.addToJSMap(n,r)}toString(t,n,r){if(!t||!t.doc)return JSON.stringify(this);const{indent:o,indentSeq:s,simpleKeys:i}=t.doc.options;let{key:a,value:c}=this,u=a instanceof Se&&a.comment;if(i){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(a instanceof me){const N="With simple keys, collection cannot be used as a key value";throw new Error(N)}}let l=!i&&(!a||u||(a instanceof Se?a instanceof me||a.type===j.BLOCK_FOLDED||a.type===j.BLOCK_LITERAL:typeof a=="object"));const{doc:f,indent:p,indentStep:h,stringify:d}=t;t=Object.assign({},t,{implicitKey:!l,indent:p+h});let v=!1,m=d(a,t,()=>u=null,()=>v=!0);if(m=Vt(m,t.indent,u),!l&&m.length>1024){if(i)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");l=!0}if(t.allNullValues&&!i)return this.comment?(m=Vt(m,t.indent,this.comment),n&&n()):v&&!u&&r&&r(),t.inFlow&&!l?m:`? ${m}`;m=l?`? ${m}
104
- ${p}:`:`${m}:`,this.comment&&(m=Vt(m,t.indent,this.comment),n&&n());let g="",$=null;if(c instanceof Se){if(c.spaceBefore&&(g=`
105
- `),c.commentBefore){const N=c.commentBefore.replace(/^/gm,`${t.indent}#`);g+=`
106
- ${N}`}$=c.comment}else c&&typeof c=="object"&&(c=f.schema.createNode(c,!0));t.implicitKey=!1,!l&&!this.comment&&c instanceof X&&(t.indentAtStart=m.length+1),v=!1,!s&&o>=2&&!t.inFlow&&!l&&c instanceof Fe&&c.type!==j.FLOW_SEQ&&!c.tag&&!f.anchors.getName(c)&&(t.indent=t.indent.substr(2));const w=d(c,t,()=>$=null,()=>v=!0);let S=" ";return g||this.comment?S=`${g}
107
- ${t.indent}`:!l&&c instanceof me?(!(w[0]==="["||w[0]==="{")||w.includes(`
108
- `))&&(S=`
109
- ${t.indent}`):w[0]===`
110
- `&&(S=""),v&&!$&&r&&r(),Vt(m+S+w,t.indent,$)}};ve(H,"Type",{PAIR:"PAIR",MERGE_PAIR:"MERGE_PAIR"});const Yn=(e,t)=>{if(e instanceof Ze){const n=t.get(e.source);return n.count*n.aliasCount}else if(e instanceof me){let n=0;for(const r of e.items){const o=Yn(r,t);o>n&&(n=o)}return n}else if(e instanceof H){const n=Yn(e.key,t),r=Yn(e.value,t);return Math.max(n,r)}return 1};let Ze=class yu extends Se{static stringify({range:t,source:n},{anchors:r,doc:o,implicitKey:s,inStringifyKey:i}){let a=Object.keys(r).find(u=>r[u]===n);if(!a&&i&&(a=o.anchors.getName(n)||o.anchors.newName()),a)return`*${a}${s?" ":""}`;const c=o.anchors.getName(n)?"Alias node must be after source node":"Source node not found for alias node";throw new Error(`${c} [${t}]`)}constructor(t){super(),this.source=t,this.type=j.ALIAS}set tag(t){throw new Error("Alias nodes cannot have tags")}toJSON(t,n){if(!n)return Le(this.source,t,n);const{anchors:r,maxAliasCount:o}=n,s=r.get(this.source);if(!s||s.res===void 0){const i="This should not happen: Alias anchor was not resolved?";throw this.cstNode?new $n(this.cstNode,i):new ReferenceError(i)}if(o>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=Yn(this.source,r)),s.count*s.aliasCount>o)){const i="Excessive alias count indicates a resource exhaustion attack";throw this.cstNode?new $n(this.cstNode,i):new ReferenceError(i)}return s.res}toString(t){return yu.stringify(this,t)}};ve(Ze,"default",!0);function St(e,t){const n=t instanceof X?t.value:t;for(const r of e)if(r instanceof H&&(r.key===t||r.key===n||r.key&&r.key.value===n))return r}let Ee=class extends me{add(t,n){t?t instanceof H||(t=new H(t.key||t,t.value)):t=new H(t);const r=St(this.items,t.key),o=this.schema&&this.schema.sortMapEntries;if(r)if(n)r.value=t.value;else throw new Error(`Key ${t.key} already set`);else if(o){const s=this.items.findIndex(i=>o(t,i)<0);s===-1?this.items.push(t):this.items.splice(s,0,t)}else this.items.push(t)}delete(t){const n=St(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){const r=St(this.items,t),o=r&&r.value;return!n&&o instanceof X?o.value:o}has(t){return!!St(this.items,t)}set(t,n){this.add(new H(t,n),!0)}toJSON(t,n,r){const o=r?new r:n&&n.mapAsMap?new Map:{};n&&n.onCreate&&n.onCreate(o);for(const s of this.items)s.addToJSMap(n,o);return o}toString(t,n,r){if(!t)return JSON.stringify(this);for(const o of this.items)if(!(o instanceof H))throw new Error(`Map items must all be pairs; found ${JSON.stringify(o)} instead`);return super.toString(t,{blockItem:o=>o.str,flowChars:{start:"{",end:"}"},isMap:!0,itemIndent:t.indent||""},n,r)}};const vu="<<";class $u extends H{constructor(t){if(t instanceof H){let n=t.value;n instanceof Fe||(n=new Fe,n.items.push(t.value),n.range=t.value.range),super(t.key,n),this.range=t.range}else super(new X(vu),new Fe);this.type=H.Type.MERGE_PAIR}addToJSMap(t,n){for(const{source:r}of this.value.items){if(!(r instanceof Ee))throw new Error("Merge sources must be maps");const o=r.toJSON(null,t,Map);for(const[s,i]of o)n instanceof Map?n.has(s)||n.set(s,i):n instanceof Set?n.add(s):Object.prototype.hasOwnProperty.call(n,s)||Object.defineProperty(n,s,{value:i,writable:!0,enumerable:!0,configurable:!0})}return n}toString(t,n){const r=this.value;if(r.items.length>1)return super.toString(t,n);this.value=r.items[0];const o=super.toString(t,n);return this.value=r,o}}const pn={defaultType:j.BLOCK_LITERAL,lineWidth:76},We={trueStr:"true",falseStr:"false"},ct={asBigInt:!1},Ht={nullStr:"null"},Xe={defaultType:j.PLAIN,doubleQuoted:{jsonEncoding:!1,minMultiLineLength:40},fold:{lineWidth:80,minContentWidth:20}};function fs(e,t,n){for(const{format:r,test:o,resolve:s}of t)if(o){const i=e.match(o);if(i){let a=s.apply(null,i);return a instanceof X||(a=new X(a)),r&&(a.format=r),a}}return n&&(e=n(e)),new X(e)}const wu="flow",$o="block",Zn="quoted",va=(e,t)=>{let n=e[t+1];for(;n===" "||n===" ";){do n=e[t+=1];while(n&&n!==`
111
- `);n=e[t+1]}return t};function yr(e,t,n,{indentAtStart:r,lineWidth:o=80,minContentWidth:s=20,onFold:i,onOverflow:a}){if(!o||o<0)return e;const c=Math.max(1+s,1+o-t.length);if(e.length<=c)return e;const u=[],l={};let f=o-t.length;typeof r=="number"&&(r>o-Math.max(2,s)?u.push(0):f=o-r);let p,h,d=!1,v=-1,m=-1,g=-1;n===$o&&(v=va(e,v),v!==-1&&(f=v+c));for(let w;w=e[v+=1];){if(n===Zn&&w==="\\"){switch(m=v,e[v+1]){case"x":v+=3;break;case"u":v+=5;break;case"U":v+=9;break;default:v+=1}g=v}if(w===`
112
- `)n===$o&&(v=va(e,v)),f=v+c,p=void 0;else{if(w===" "&&h&&h!==" "&&h!==`
113
- `&&h!==" "){const S=e[v+1];S&&S!==" "&&S!==`
114
- `&&S!==" "&&(p=v)}if(v>=f)if(p)u.push(p),f=p+c,p=void 0;else if(n===Zn){for(;h===" "||h===" ";)h=w,w=e[v+=1],d=!0;const S=v>g+1?v-2:m-1;if(l[S])return e;u.push(S),l[S]=!0,f=S+c,p=void 0}else d=!0}h=w}if(d&&a&&a(),u.length===0)return e;i&&i();let $=e.slice(0,u[0]);for(let w=0;w<u.length;++w){const S=u[w],N=u[w+1]||e.length;S===0?$=`
115
- ${t}${e.slice(0,N)}`:(n===Zn&&l[S]&&($+=`${e[S]}\\`),$+=`
116
- ${t}${e.slice(S+1,N)}`)}return $}const ds=({indentAtStart:e})=>e?Object.assign({indentAtStart:e},Xe.fold):Xe.fold,vr=e=>/^(%|---|\.\.\.)/m.test(e);function Sm(e,t,n){if(!t||t<0)return!1;const r=t-n,o=e.length;if(o<=r)return!1;for(let s=0,i=0;s<o;++s)if(e[s]===`
117
- `){if(s-i>r)return!0;if(i=s+1,o-i<=r)return!1}return!0}function Ot(e,t){const{implicitKey:n}=t,{jsonEncoding:r,minMultiLineLength:o}=Xe.doubleQuoted,s=JSON.stringify(e);if(r)return s;const i=t.indent||(vr(e)?" ":"");let a="",c=0;for(let u=0,l=s[u];l;l=s[++u])if(l===" "&&s[u+1]==="\\"&&s[u+2]==="n"&&(a+=s.slice(c,u)+"\\ ",u+=1,c=u,l="\\"),l==="\\")switch(s[u+1]){case"u":{a+=s.slice(c,u);const f=s.substr(u+2,4);switch(f){case"0000":a+="\\0";break;case"0007":a+="\\a";break;case"000b":a+="\\v";break;case"001b":a+="\\e";break;case"0085":a+="\\N";break;case"00a0":a+="\\_";break;case"2028":a+="\\L";break;case"2029":a+="\\P";break;default:f.substr(0,2)==="00"?a+="\\x"+f.substr(2):a+=s.substr(u,6)}u+=5,c=u+1}break;case"n":if(n||s[u+2]==='"'||s.length<o)u+=1;else{for(a+=s.slice(c,u)+`
118
-
119
- `;s[u+2]==="\\"&&s[u+3]==="n"&&s[u+4]!=='"';)a+=`
120
- `,u+=2;a+=i,s[u+2]===" "&&(a+="\\"),u+=1,c=u+1}break;default:u+=1}return a=c?a+s.slice(c):s,n?a:yr(a,i,Zn,ds(t))}function bu(e,t){if(t.implicitKey){if(/\n/.test(e))return Ot(e,t)}else if(/[ \t]\n|\n[ \t]/.test(e))return Ot(e,t);const n=t.indent||(vr(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
121
- ${n}`)+"'";return t.implicitKey?r:yr(r,n,wu,ds(t))}function Xn({comment:e,type:t,value:n},r,o,s){if(/\n[\t ]+$/.test(n)||/^\s*$/.test(n))return Ot(n,r);const i=r.indent||(r.forceBlockIndent||vr(n)?" ":""),a=i?"2":"1",c=t===j.BLOCK_FOLDED?!1:t===j.BLOCK_LITERAL?!0:!Sm(n,Xe.fold.lineWidth,i.length);let u=c?"|":">";if(!n)return u+`
122
- `;let l="",f="";if(n=n.replace(/[\n\t ]*$/,h=>{const d=h.indexOf(`
123
- `);return d===-1?u+="-":(n===h||d!==h.length-1)&&(u+="+",s&&s()),f=h.replace(/\n$/,""),""}).replace(/^[\n ]*/,h=>{h.indexOf(" ")!==-1&&(u+=a);const d=h.match(/ +$/);return d?(l=h.slice(0,-d[0].length),d[0]):(l=h,"")}),f&&(f=f.replace(/\n+(?!\n|$)/g,`$&${i}`)),l&&(l=l.replace(/\n+/g,`$&${i}`)),e&&(u+=" #"+e.replace(/ ?[\r\n]+/g," "),o&&o()),!n)return`${u}${a}
124
- ${i}${f}`;if(c)return n=n.replace(/\n+/g,`$&${i}`),`${u}
125
- ${i}${l}${n}${f}`;n=n.replace(/\n+/g,`
126
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${i}`);const p=yr(`${l}${n}${f}`,i,$o,Xe.fold);return`${u}
127
- ${i}${p}`}function Em(e,t,n,r){const{comment:o,type:s,value:i}=e,{actualString:a,implicitKey:c,indent:u,inFlow:l}=t;if(c&&/[\n[\]{},]/.test(i)||l&&/[[\]{},]/.test(i))return Ot(i,t);if(!i||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return c||l||i.indexOf(`
128
- `)===-1?i.indexOf('"')!==-1&&i.indexOf("'")===-1?bu(i,t):Ot(i,t):Xn(e,t,n,r);if(!c&&!l&&s!==j.PLAIN&&i.indexOf(`
129
- `)!==-1)return Xn(e,t,n,r);if(u===""&&vr(i))return t.forceBlockIndent=!0,Xn(e,t,n,r);const f=i.replace(/\n+/g,`$&
130
- ${u}`);if(a){const{tags:h}=t.doc.schema;if(typeof fs(f,h,h.scalarFallback).value!="string")return Ot(i,t)}const p=c?f:yr(f,u,wu,ds(t));return o&&!l&&(p.indexOf(`
131
- `)!==-1||o.indexOf(`
132
- `)!==-1)?(n&&n(),wm(p,u,o)):p}function ps(e,t,n,r){const{defaultType:o}=Xe,{implicitKey:s,inFlow:i}=t;let{type:a,value:c}=e;typeof c!="string"&&(c=String(c),e=Object.assign({},e,{value:c}));const u=f=>{switch(f){case j.BLOCK_FOLDED:case j.BLOCK_LITERAL:return Xn(e,t,n,r);case j.QUOTE_DOUBLE:return Ot(c,t);case j.QUOTE_SINGLE:return bu(c,t);case j.PLAIN:return Em(e,t,n,r);default:return null}};(a!==j.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(c)||(s||i)&&(a===j.BLOCK_FOLDED||a===j.BLOCK_LITERAL))&&(a=j.QUOTE_DOUBLE);let l=u(a);if(l===null&&(l=u(o),l===null))throw new Error(`Unsupported default string type ${o}`);return l}function Qe({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r=="bigint")return String(r);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let o=JSON.stringify(r);if(!e&&t&&(!n||n==="tag:yaml.org,2002:float")&&/^\d/.test(o)){let s=o.indexOf(".");s<0&&(s=o.length,o+=".");let i=t-(o.length-s-1);for(;i-- >0;)o+="0"}return o}function Su(e,t){let n,r;switch(t.type){case j.FLOW_MAP:n="}",r="flow map";break;case j.FLOW_SEQ:n="]",r="flow sequence";break;default:e.push(new V(t,"Not a flow collection!?"));return}let o;for(let s=t.items.length-1;s>=0;--s){const i=t.items[s];if(!i||i.type!==j.COMMENT){o=i;break}}if(o&&o.char!==n){const s=`Expected ${r} to end with ${n}`;let i;typeof o.offset=="number"?(i=new V(t,s),i.offset=o.offset+1):(i=new V(o,s),o.range&&o.range.end&&(i.offset=o.range.end-o.range.start)),e.push(i)}}function Eu(e,t){const n=t.context.src[t.range.start-1];if(n!==`
133
- `&&n!==" "&&n!==" "){const r="Comments must be separated from other tokens by white space characters";e.push(new V(t,r))}}function Nu(e,t){const n=String(t),r=n.substr(0,8)+"..."+n.substr(-8);return new V(e,`The "${r}" key is too long`)}function Ou(e,t){for(const{afterKey:n,before:r,comment:o}of t){let s=e.items[r];s?(n&&s.value&&(s=s.value),o===void 0?(n||!s.commentBefore)&&(s.spaceBefore=!0):s.commentBefore?s.commentBefore+=`
134
- `+o:s.commentBefore=o):o!==void 0&&(e.comment?e.comment+=`
135
- `+o:e.comment=o)}}function _n(e,t){const n=t.strValue;return n?typeof n=="string"?n:(n.errors.forEach(r=>{r.source||(r.source=t),e.errors.push(r)}),n.str):""}function Nm(e,t){const{handle:n,suffix:r}=t.tag;let o=e.tagPrefixes.find(s=>s.handle===n);if(!o){const s=e.getDefaults().tagPrefixes;if(s&&(o=s.find(i=>i.handle===n)),!o)throw new V(t,`The ${n} tag handle is non-default and was not declared.`)}if(!r)throw new V(t,`The ${n} tag has no suffix.`);if(n==="!"&&(e.version||e.options.version)==="1.0"){if(r[0]==="^")return e.warnings.push(new Qt(t,"YAML 1.0 ^ tag expansion is not supported")),r;if(/[:/]/.test(r)){const s=r.match(/^([a-z0-9-]+)\/(.*)/i);return s?`tag:${s[1]}.yaml.org,2002:${s[2]}`:`tag:${r}`}}return o.prefix+decodeURIComponent(r)}function Om(e,t){const{tag:n,type:r}=t;let o=!1;if(n){const{handle:s,suffix:i,verbatim:a}=n;if(a){if(a!=="!"&&a!=="!!")return a;const c=`Verbatim tags aren't resolved, so ${a} is invalid.`;e.errors.push(new V(t,c))}else if(s==="!"&&!i)o=!0;else try{return Nm(e,t)}catch(c){e.errors.push(c)}}switch(r){case j.BLOCK_FOLDED:case j.BLOCK_LITERAL:case j.QUOTE_DOUBLE:case j.QUOTE_SINGLE:return ot.STR;case j.FLOW_MAP:case j.MAP:return ot.MAP;case j.FLOW_SEQ:case j.SEQ:return ot.SEQ;case j.PLAIN:return o?ot.STR:null;default:return null}}function $a(e,t,n){const{tags:r}=e.schema,o=[];for(const i of r)if(i.tag===n)if(i.test)o.push(i);else{const a=i.resolve(e,t);return a instanceof me?a:new X(a)}const s=_n(e,t);return typeof s=="string"&&o.length>0?fs(s,o,r.scalarFallback):null}function _m({type:e}){switch(e){case j.FLOW_MAP:case j.MAP:return ot.MAP;case j.FLOW_SEQ:case j.SEQ:return ot.SEQ;default:return ot.STR}}function km(e,t,n){try{const r=$a(e,t,n);if(r)return n&&t.tag&&(r.tag=n),r}catch(r){if(r instanceof _t)r.source||(r.source=t),e.errors.push(r);else{const o=r instanceof Error?r.message:String(r);e.errors.push(new V(t,o))}return null}try{const r=_m(t);if(!r)throw new Error(`The tag ${n} is unavailable`);const o=`The tag ${n} is unavailable, falling back to ${r}`;e.warnings.push(new Qt(t,o));const s=$a(e,t,r);return s.tag=n,s}catch(r){const o=new $n(t,r.message);return o.stack=r.stack,e.errors.push(o),null}}const Am=e=>{if(!e)return!1;const{type:t}=e;return t===j.MAP_KEY||t===j.MAP_VALUE||t===j.SEQ_ITEM};function jm(e,t){const n={before:[],after:[]};let r=!1,o=!1;const s=Am(t.context.parent)?t.context.parent.props.concat(t.props):t.props;for(const{start:i,end:a}of s)switch(t.context.src[i]){case ae.COMMENT:{if(!t.commentHasRequiredWhitespace(i)){const l="Comments must be separated from other tokens by white space characters";e.push(new V(t,l))}const{header:c,valueRange:u}=t;(u&&(i>u.start||c&&i>c.start)?n.after:n.before).push(t.context.src.slice(i+1,a));break}case ae.ANCHOR:if(r){const c="A node can have at most one anchor";e.push(new V(t,c))}r=!0;break;case ae.TAG:if(o){const c="A node can have at most one tag";e.push(new V(t,c))}o=!0;break}return{comments:n,hasAnchor:r,hasTag:o}}function Im(e,t){const{anchors:n,errors:r,schema:o}=e;if(t.type===j.ALIAS){const i=t.rawValue,a=n.getNode(i);if(!a){const u=`Aliased anchor not found: ${i}`;return r.push(new $n(t,u)),null}const c=new Ze(a);return n._cstAliases.push(c),c}const s=Om(e,t);if(s)return km(e,t,s);if(t.type!==j.PLAIN){const i=`Failed to resolve ${t.type} node here`;return r.push(new ge(t,i)),null}try{const i=_n(e,t);return fs(i,o.tags,o.tags.scalarFallback)}catch(i){return i.source||(i.source=t),r.push(i),null}}function at(e,t){if(!t)return null;t.error&&e.errors.push(t.error);const{comments:n,hasAnchor:r,hasTag:o}=jm(e.errors,t);if(r){const{anchors:i}=e,a=t.anchor,c=i.getNode(a);c&&(i.map[i.newName(a)]=c),i.map[a]=t}if(t.type===j.ALIAS&&(r||o)){const i="An alias node must not specify any properties";e.errors.push(new V(t,i))}const s=Im(e,t);if(s){s.range=[t.range.start,t.range.end],e.options.keepCstNodes&&(s.cstNode=t),e.options.keepNodeTypes&&(s.type=t.type);const i=n.before.join(`
136
- `);i&&(s.commentBefore=s.commentBefore?`${s.commentBefore}
137
- ${i}`:i);const a=n.after.join(`
138
- `);a&&(s.comment=s.comment?`${s.comment}
139
- ${a}`:a)}return t.resolved=s}function _u(e,t){if(t.type!==j.MAP&&t.type!==j.FLOW_MAP){const i=`A ${t.type} node cannot be resolved as a mapping`;return e.errors.push(new ge(t,i)),null}const{comments:n,items:r}=t.type===j.FLOW_MAP?Cm(e,t):Tm(e,t),o=new Ee;o.items=r,Ou(o,n);let s=!1;for(let i=0;i<r.length;++i){const{key:a}=r[i];if(a instanceof me&&(s=!0),e.schema.merge&&a&&a.value===vu){r[i]=new $u(r[i]);const c=r[i].value.items;let u=null;c.some(l=>{if(l instanceof Ze){const{type:f}=l.source;return f===j.MAP||f===j.FLOW_MAP?!1:u="Merge nodes aliases can only point to maps"}return u="Merge nodes can only have Alias nodes as values"}),u&&e.errors.push(new V(t,u))}else for(let c=i+1;c<r.length;++c){const{key:u}=r[c];if(a===u||a&&u&&Object.prototype.hasOwnProperty.call(a,"value")&&a.value===u.value){const l=`Map keys must be unique; "${a}" is repeated`;e.errors.push(new V(t,l));break}}}if(s&&!e.options.mapAsMap){const i="Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.";e.warnings.push(new Qt(t,i))}return t.resolved=o,o}const Pm=({context:{lineStart:e,node:t,src:n},props:r})=>{if(r.length===0)return!1;const{start:o}=r[0];if(t&&o>t.valueRange.start||n[o]!==ae.COMMENT)return!1;for(let s=e;s<o;++s)if(n[s]===`
140
- `)return!1;return!0};function xm(e,t){if(!Pm(e))return;const n=e.getPropValue(0,ae.COMMENT,!0);let r=!1;const o=t.value.commentBefore;if(o&&o.startsWith(n))t.value.commentBefore=o.substr(n.length+1),r=!0;else{const s=t.value.comment;!e.node&&s&&s.startsWith(n)&&(t.value.comment=s.substr(n.length+1),r=!0)}r&&(t.comment=n)}function Tm(e,t){const n=[],r=[];let o,s=null;for(let i=0;i<t.items.length;++i){const a=t.items[i];switch(a.type){case j.BLANK_LINE:n.push({afterKey:!!o,before:r.length});break;case j.COMMENT:n.push({afterKey:!!o,before:r.length,comment:a.comment});break;case j.MAP_KEY:o!==void 0&&r.push(new H(o)),a.error&&e.errors.push(a.error),o=at(e,a.node),s=null;break;case j.MAP_VALUE:{if(o===void 0&&(o=null),a.error&&e.errors.push(a.error),!a.context.atLineStart&&a.node&&a.node.type===j.MAP&&!a.node.context.atLineStart){const l="Nested mappings are not allowed in compact mappings";e.errors.push(new V(a.node,l))}let c=a.node;if(!c&&a.props.length>0){c=new hu(j.PLAIN,[]),c.context={parent:a,src:a.context.src};const l=a.range.start+1;if(c.range={start:l,end:l},c.valueRange={start:l,end:l},typeof a.range.origStart=="number"){const f=a.range.origStart+1;c.range.origStart=c.range.origEnd=f,c.valueRange.origStart=c.valueRange.origEnd=f}}const u=new H(o,at(e,c));xm(a,u),r.push(u),o&&typeof s=="number"&&a.range.start>s+1024&&e.errors.push(Nu(t,o)),o=void 0,s=null}break;default:o!==void 0&&r.push(new H(o)),o=at(e,a),s=a.range.start,a.error&&e.errors.push(a.error);e:for(let c=i+1;;++c){const u=t.items[c];switch(u&&u.type){case j.BLANK_LINE:case j.COMMENT:continue e;case j.MAP_VALUE:break e;default:{const l="Implicit map keys need to be followed by map values";e.errors.push(new V(a,l));break e}}}if(a.valueRangeContainsNewline){const c="Implicit map keys need to be on a single line";e.errors.push(new V(a,c))}}}return o!==void 0&&r.push(new H(o)),{comments:n,items:r}}function Cm(e,t){const n=[],r=[];let o,s=!1,i="{";for(let a=0;a<t.items.length;++a){const c=t.items[a];if(typeof c.char=="string"){const{char:u,offset:l}=c;if(u==="?"&&o===void 0&&!s){s=!0,i=":";continue}if(u===":"){if(o===void 0&&(o=null),i===":"){i=",";continue}}else if(s&&(o===void 0&&u!==","&&(o=null),s=!1),o!==void 0&&(r.push(new H(o)),o=void 0,u===",")){i=":";continue}if(u==="}"){if(a===t.items.length-1)continue}else if(u===i){i=":";continue}const f=`Flow map contains an unexpected ${u}`,p=new ge(t,f);p.offset=l,e.errors.push(p)}else c.type===j.BLANK_LINE?n.push({afterKey:!!o,before:r.length}):c.type===j.COMMENT?(Eu(e.errors,c),n.push({afterKey:!!o,before:r.length,comment:c.comment})):o===void 0?(i===","&&e.errors.push(new V(c,"Separator , missing in flow map")),o=at(e,c)):(i!==","&&e.errors.push(new V(c,"Indicator : missing in flow map entry")),r.push(new H(o,at(e,c))),o=void 0,s=!1)}return Su(e.errors,t),o!==void 0&&r.push(new H(o)),{comments:n,items:r}}function ku(e,t){if(t.type!==j.SEQ&&t.type!==j.FLOW_SEQ){const s=`A ${t.type} node cannot be resolved as a sequence`;return e.errors.push(new ge(t,s)),null}const{comments:n,items:r}=t.type===j.FLOW_SEQ?Mm(e,t):Rm(e,t),o=new Fe;if(o.items=r,Ou(o,n),!e.options.mapAsMap&&r.some(s=>s instanceof H&&s.key instanceof me)){const s="Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.";e.warnings.push(new Qt(t,s))}return t.resolved=o,o}function Rm(e,t){const n=[],r=[];for(let o=0;o<t.items.length;++o){const s=t.items[o];switch(s.type){case j.BLANK_LINE:n.push({before:r.length});break;case j.COMMENT:n.push({comment:s.comment,before:r.length});break;case j.SEQ_ITEM:if(s.error&&e.errors.push(s.error),r.push(at(e,s.node)),s.hasProps){const i="Sequence items cannot have tags or anchors before the - indicator";e.errors.push(new V(s,i))}break;default:s.error&&e.errors.push(s.error),e.errors.push(new ge(s,`Unexpected ${s.type} node in sequence`))}}return{comments:n,items:r}}function Mm(e,t){const n=[],r=[];let o=!1,s,i=null,a="[",c=null;for(let u=0;u<t.items.length;++u){const l=t.items[u];if(typeof l.char=="string"){const{char:f,offset:p}=l;if(f!==":"&&(o||s!==void 0)&&(o&&s===void 0&&(s=a?r.pop():null),r.push(new H(s)),o=!1,s=void 0,i=null),f===a)a=null;else if(!a&&f==="?")o=!0;else if(a!=="["&&f===":"&&s===void 0){if(a===","){if(s=r.pop(),s instanceof H){const h="Chaining flow sequence pairs is invalid",d=new V(t,h);d.offset=p,e.errors.push(d)}if(!o&&typeof i=="number"){const h=l.range?l.range.start:l.offset;h>i+1024&&e.errors.push(Nu(t,s));const{src:d}=c.context;for(let v=i;v<h;++v)if(d[v]===`
141
- `){const m="Implicit keys of flow sequence pairs need to be on a single line";e.errors.push(new V(c,m));break}}}else s=null;i=null,o=!1,a=null}else if(a==="["||f!=="]"||u<t.items.length-1){const h=`Flow sequence contains an unexpected ${f}`,d=new ge(t,h);d.offset=p,e.errors.push(d)}}else if(l.type===j.BLANK_LINE)n.push({before:r.length});else if(l.type===j.COMMENT)Eu(e.errors,l),n.push({comment:l.comment,before:r.length});else{if(a){const p=`Expected a ${a} in flow sequence`;e.errors.push(new V(l,p))}const f=at(e,l);s===void 0?(r.push(f),c=l):(r.push(new H(s,f)),s=void 0),i=l.range.start,a=","}}return Su(e.errors,t),s!==void 0&&r.push(new H(s)),{comments:n,items:r}}const Au={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve:(e,t)=>{const n=_n(e,t);if(typeof Buffer=="function")return Buffer.from(n,"base64");if(typeof atob=="function"){const r=atob(n.replace(/[\n\r]/g,"")),o=new Uint8Array(r.length);for(let s=0;s<r.length;++s)o[s]=r.charCodeAt(s);return o}else{const r="This environment does not support reading binary tags; either Buffer or atob is required";return e.errors.push(new $n(t,r)),null}},options:pn,stringify:({comment:e,type:t,value:n},r,o,s)=>{let i;if(typeof Buffer=="function")i=n instanceof Buffer?n.toString("base64"):Buffer.from(n.buffer).toString("base64");else if(typeof btoa=="function"){let a="";for(let c=0;c<n.length;++c)a+=String.fromCharCode(n[c]);i=btoa(a)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t||(t=pn.defaultType),t===j.QUOTE_DOUBLE)n=i;else{const{lineWidth:a}=pn,c=Math.ceil(i.length/a),u=new Array(c);for(let l=0,f=0;l<c;++l,f+=a)u[l]=i.substr(f,a);n=u.join(t===j.BLOCK_LITERAL?`
142
- `:" ")}return ps({comment:e,type:t,value:n},r,o,s)}};function ju(e,t){const n=ku(e,t);for(let r=0;r<n.items.length;++r){let o=n.items[r];if(!(o instanceof H)){if(o instanceof Ee){if(o.items.length>1){const i="Each pair must have its own sequence indicator";throw new V(t,i)}const s=o.items[0]||new H;o.commentBefore&&(s.commentBefore=s.commentBefore?`${o.commentBefore}
143
- ${s.commentBefore}`:o.commentBefore),o.comment&&(s.comment=s.comment?`${o.comment}
144
- ${s.comment}`:o.comment),o=s}n.items[r]=o instanceof H?o:new H(o)}}return n}function Iu(e,t,n){const r=new Fe(e);r.tag="tag:yaml.org,2002:pairs";for(const o of t){let s,i;if(Array.isArray(o))if(o.length===2)s=o[0],i=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){const c=Object.keys(o);if(c.length===1)s=c[0],i=o[s];else throw new TypeError(`Expected { key: value } tuple: ${o}`)}else s=o;const a=e.createPair(s,i,n);r.items.push(a)}return r}const Pu={default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ju,createNode:Iu};class Yt extends Fe{constructor(){super(),ve(this,"add",Ee.prototype.add.bind(this)),ve(this,"delete",Ee.prototype.delete.bind(this)),ve(this,"get",Ee.prototype.get.bind(this)),ve(this,"has",Ee.prototype.has.bind(this)),ve(this,"set",Ee.prototype.set.bind(this)),this.tag=Yt.tag}toJSON(t,n){const r=new Map;n&&n.onCreate&&n.onCreate(r);for(const o of this.items){let s,i;if(o instanceof H?(s=Le(o.key,"",n),i=Le(o.value,s,n)):s=Le(o,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,i)}return r}}ve(Yt,"tag","tag:yaml.org,2002:omap");function Dm(e,t){const n=ju(e,t),r=[];for(const{key:o}of n.items)if(o instanceof X)if(r.includes(o.value)){const s="Ordered maps must not include duplicate keys";throw new V(t,s)}else r.push(o.value);return Object.assign(new Yt,n)}function Lm(e,t,n){const r=Iu(e,t,n),o=new Yt;return o.items=r.items,o}const xu={identify:e=>e instanceof Map,nodeClass:Yt,default:!1,tag:"tag:yaml.org,2002:omap",resolve:Dm,createNode:Lm};let $r=class Tu extends Ee{constructor(){super(),this.tag=Tu.tag}add(t){const n=t instanceof H?t:new H(t);St(this.items,n.key)||this.items.push(n)}get(t,n){const r=St(this.items,t);return!n&&r instanceof H?r.key instanceof X?r.key.value:r.key:r}set(t,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);const r=St(this.items,t);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new H(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues())return super.toString(t,n,r);throw new Error("Set items must all have null values")}};ve($r,"tag","tag:yaml.org,2002:set");function Um(e,t){const n=_u(e,t);if(!n.hasAllNullValues())throw new V(t,"Set items must all have null values");return Object.assign(new $r,n)}function Bm(e,t,n){const r=new $r;for(const o of t)r.items.push(e.createPair(o,null,n));return r}const Cu={identify:e=>e instanceof Set,nodeClass:$r,default:!1,tag:"tag:yaml.org,2002:set",resolve:Um,createNode:Bm},hs=(e,t)=>{const n=t.split(":").reduce((r,o)=>r*60+Number(o),0);return e==="-"?-n:n},Ru=({value:e})=>{if(isNaN(e)||!isFinite(e))return Qe(e);let t="";e<0&&(t="-",e=Math.abs(e));const n=[e%60];return e<60?n.unshift(0):(e=Math.round((e-n[0])/60),n.unshift(e%60),e>=60&&(e=Math.round((e-n[0])/60),n.unshift(e))),t+n.map(r=>r<10?"0"+String(r):String(r)).join(":").replace(/000000\d*$/,"")},Mu={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/,resolve:(e,t,n)=>hs(t,n.replace(/_/g,"")),stringify:Ru},Du={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/,resolve:(e,t,n)=>hs(t,n.replace(/_/g,"")),stringify:Ru},Lu={identify:e=>e 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:(e,t,n,r,o,s,i,a,c)=>{a&&(a=(a+"00").substr(1,3));let u=Date.UTC(t,n-1,r,o||0,s||0,i||0,a||0);if(c&&c!=="Z"){let l=hs(c[0],c.slice(1));Math.abs(l)<30&&(l*=60),u-=6e4*l}return new Date(u)},stringify:({value:e})=>e.toISOString().replace(/((T00:00)?:00)?\.000Z$/,"")};function Uu(e){const t=typeof process<"u"&&process.env||{};return e?typeof YAML_SILENCE_DEPRECATION_WARNINGS<"u"?!YAML_SILENCE_DEPRECATION_WARNINGS:!t.YAML_SILENCE_DEPRECATION_WARNINGS:typeof YAML_SILENCE_WARNINGS<"u"?!YAML_SILENCE_WARNINGS:!t.YAML_SILENCE_WARNINGS}function Bu(e,t){if(Uu(!1)){const n=typeof process<"u"&&process.emitWarning;n?n(e,t):console.warn(t?`${t}: ${e}`:e)}}const wa={};function Fm(e,t){if(!wa[e]&&Uu(!0)){wa[e]=!0;let n=`The option '${e}' will be removed in a future release`;n+=`, use '${t}' instead.`,Bu(n,"DeprecationWarning")}}function Vm(e,t,n){const r=new Ee(e);if(t instanceof Map)for(const[o,s]of t)r.items.push(e.createPair(o,s,n));else if(t&&typeof t=="object")for(const o of Object.keys(t))r.items.push(e.createPair(o,t[o],n));return typeof e.sortMapEntries=="function"&&r.items.sort(e.sortMapEntries),r}const bn={createNode:Vm,default:!0,nodeClass:Ee,tag:"tag:yaml.org,2002:map",resolve:_u};function Km(e,t,n){const r=new Fe(e);if(t&&t[Symbol.iterator])for(const o of t){const s=e.createNode(o,n.wrapScalars,null,n);r.items.push(s)}return r}const wr={createNode:Km,default:!0,nodeClass:Fe,tag:"tag:yaml.org,2002:seq",resolve:ku},qm={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:_n,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),ps(e,t,n,r)},options:Xe},ms=[bn,wr,qm],br=e=>typeof e=="bigint"||Number.isInteger(e),gs=(e,t,n)=>ct.asBigInt?BigInt(e):parseInt(t,n);function Fu(e,t,n){const{value:r}=e;return br(r)&&r>=0?n+r.toString(t):Qe(e)}const Vu={identify:e=>e==null,createNode:(e,t,n)=>n.wrapScalars?new X(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>null,options:Ht,stringify:()=>Ht.nullStr},Ku={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>e[0]==="t"||e[0]==="T",options:We,stringify:({value:e})=>e?We.trueStr:We.falseStr},qu={identify:e=>br(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o([0-7]+)$/,resolve:(e,t)=>gs(e,t,8),options:ct,stringify:e=>Fu(e,8,"0o")},zu={identify:br,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:e=>gs(e,e,10),options:ct,stringify:Qe},Gu={identify:e=>br(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x([0-9a-fA-F]+)$/,resolve:(e,t)=>gs(e,t,16),options:ct,stringify:e=>Fu(e,16,"0x")},Hu={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.inf|(\.nan))$/i,resolve:(e,t)=>t?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Qe},Ju={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify:({value:e})=>Number(e).toExponential()},Wu={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.([0-9]+)|[0-9]+\.([0-9]*))$/,resolve(e,t,n){const r=t||n,o=new X(parseFloat(e));return r&&r[r.length-1]==="0"&&(o.minFractionDigits=r.length),o},stringify:Qe},zm=ms.concat([Vu,Ku,qu,zu,Gu,Hu,Ju,Wu]),ba=e=>typeof e=="bigint"||Number.isInteger(e),Rn=({value:e})=>JSON.stringify(e),Qu=[bn,wr,{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:_n,stringify:Rn},{identify:e=>e==null,createNode:(e,t,n)=>n.wrapScalars?new X(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Rn},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:e=>e==="true",stringify:Rn},{identify:ba,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:e=>ct.asBigInt?BigInt(e):parseInt(e,10),stringify:({value:e})=>ba(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Rn}];Qu.scalarFallback=e=>{throw new SyntaxError(`Unresolved plain scalar ${JSON.stringify(e)}`)};const Sa=({value:e})=>e?We.trueStr:We.falseStr,un=e=>typeof e=="bigint"||Number.isInteger(e);function Mn(e,t,n){let r=t.replace(/_/g,"");if(ct.asBigInt){switch(n){case 2:r=`0b${r}`;break;case 8:r=`0o${r}`;break;case 16:r=`0x${r}`;break}const s=BigInt(r);return e==="-"?BigInt(-1)*s:s}const o=parseInt(r,n);return e==="-"?-1*o:o}function Vr(e,t,n){const{value:r}=e;if(un(r)){const o=r.toString(t);return r<0?"-"+n+o.substr(1):n+o}return Qe(e)}const Gm=ms.concat([{identify:e=>e==null,createNode:(e,t,n)=>n.wrapScalars?new X(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>null,options:Ht,stringify:()=>Ht.nullStr},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>!0,options:We,stringify:Sa},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i,resolve:()=>!1,options:We,stringify:Sa},{identify:un,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^([-+]?)0b([0-1_]+)$/,resolve:(e,t,n)=>Mn(t,n,2),stringify:e=>Vr(e,2,"0b")},{identify:un,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^([-+]?)0([0-7_]+)$/,resolve:(e,t,n)=>Mn(t,n,8),stringify:e=>Vr(e,8,"0")},{identify:un,default:!0,tag:"tag:yaml.org,2002:int",test:/^([-+]?)([0-9][0-9_]*)$/,resolve:(e,t,n)=>Mn(t,n,10),stringify:Qe},{identify:un,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^([-+]?)0x([0-9a-fA-F_]+)$/,resolve:(e,t,n)=>Mn(t,n,16),stringify:e=>Vr(e,16,"0x")},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.inf|(\.nan))$/i,resolve:(e,t)=>t?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Qe},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?([0-9][0-9_]*)?(\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify:({value:e})=>Number(e).toExponential()},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/,resolve(e,t){const n=new X(parseFloat(e.replace(/_/g,"")));if(t){const r=t.replace(/_/g,"");r[r.length-1]==="0"&&(n.minFractionDigits=r.length)}return n},stringify:Qe}],Au,xu,Pu,Cu,Mu,Du,Lu),Hm={core:zm,failsafe:ms,json:Qu,yaml11:Gm},Jm={binary:Au,bool:Ku,float:Wu,floatExp:Ju,floatNaN:Hu,floatTime:Du,int:zu,intHex:Gu,intOct:qu,intTime:Mu,map:bn,null:Vu,omap:xu,pairs:Pu,seq:wr,set:Cu,timestamp:Lu};function Wm(e,t,n){if(t){const r=n.filter(s=>s.tag===t),o=r.find(s=>!s.format)||r[0];if(!o)throw new Error(`Tag ${t} not found`);return o}return n.find(r=>(r.identify&&r.identify(e)||r.class&&e instanceof r.class)&&!r.format)}function Qm(e,t,n){if(e instanceof Se)return e;const{defaultPrefix:r,onTagObj:o,prevObjects:s,schema:i,wrapScalars:a}=n;t&&t.startsWith("!!")&&(t=r+t.slice(2));let c=Wm(e,t,i.tags);if(!c){if(typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object")return a?new X(e):e;c=e instanceof Map?bn:e[Symbol.iterator]?wr:bn}o&&(o(c),delete n.onTagObj);const u={value:void 0,node:void 0};if(e&&typeof e=="object"&&s){const l=s.get(e);if(l){const f=new Ze(l);return n.aliasNodes.push(f),f}u.value=e,s.set(e,u)}return u.node=c.createNode?c.createNode(n.schema,e,n):a?new X(e):e,t&&u.node instanceof Se&&(u.node.tag=t),u.node}function Ym(e,t,n,r){let o=e[r.replace(/\W/g,"")];if(!o){const s=Object.keys(e).map(i=>JSON.stringify(i)).join(", ");throw new Error(`Unknown schema "${r}"; use one of ${s}`)}if(Array.isArray(n))for(const s of n)o=o.concat(s);else typeof n=="function"&&(o=n(o.slice()));for(let s=0;s<o.length;++s){const i=o[s];if(typeof i=="string"){const a=t[i];if(!a){const c=Object.keys(t).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag "${i}"; use one of ${c}`)}o[s]=a}}return o}const Zm=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;let Sn=class Yu{constructor({customTags:t,merge:n,schema:r,sortMapEntries:o,tags:s}){this.merge=!!n,this.name=r,this.sortMapEntries=o===!0?Zm:o||null,!t&&s&&Fm("tags","customTags"),this.tags=Ym(Hm,Jm,t||s,r)}createNode(t,n,r,o){const s={defaultPrefix:Yu.defaultPrefix,schema:this,wrapScalars:n},i=o?Object.assign(o,s):s;return Qm(t,r,i)}createPair(t,n,r){r||(r={wrapScalars:!0});const o=this.createNode(t,r.wrapScalars,null,r),s=this.createNode(n,r.wrapScalars,null,r);return new H(o,s)}};ve(Sn,"defaultPrefix",Wn);ve(Sn,"defaultTags",ot);const cr={anchorPrefix:"a",customTags:null,indent:2,indentSeq:!0,keepCstNodes:!1,keepNodeTypes:!0,keepBlobsInJSON:!0,mapAsMap:!1,maxAliasCount:100,prettyErrors:!1,simpleKeys:!1,version:"1.2"},Xm={get binary(){return pn},set binary(e){Object.assign(pn,e)},get bool(){return We},set bool(e){Object.assign(We,e)},get int(){return ct},set int(e){Object.assign(ct,e)},get null(){return Ht},set null(e){Object.assign(Ht,e)},get str(){return Xe},set str(e){Object.assign(Xe,e)}},Zu={"1.0":{schema:"yaml-1.1",merge:!0,tagPrefixes:[{handle:"!",prefix:Wn},{handle:"!!",prefix:"tag:private.yaml.org,2002:"}]},1.1:{schema:"yaml-1.1",merge:!0,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:Wn}]},1.2:{schema:"core",merge:!1,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:Wn}]}};function Ea(e,t){if((e.version||e.options.version)==="1.0"){const o=t.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/);if(o)return"!"+o[1];const s=t.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/);return s?`!${s[1]}/${s[2]}`:`!${t.replace(/^tag:/,"")}`}let n=e.tagPrefixes.find(o=>t.indexOf(o.prefix)===0);if(!n){const o=e.getDefaults().tagPrefixes;n=o&&o.find(s=>t.indexOf(s.prefix)===0)}if(!n)return t[0]==="!"?t:`!<${t}>`;const r=t.substr(n.prefix.length).replace(/[!,[\]{}]/g,o=>({"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"})[o]);return n.handle+r}function eg(e,t){if(t instanceof Ze)return Ze;if(t.tag){const o=e.filter(s=>s.tag===t.tag);if(o.length>0)return o.find(s=>s.format===t.format)||o[0]}let n,r;if(t instanceof X){r=t.value;const o=e.filter(s=>s.identify&&s.identify(r)||s.class&&r instanceof s.class);n=o.find(s=>s.format===t.format)||o.find(s=>!s.format)}else r=t,n=e.find(o=>o.nodeClass&&r instanceof o.nodeClass);if(!n){const o=r&&r.constructor?r.constructor.name:typeof r;throw new Error(`Tag not resolved for ${o} value`)}return n}function tg(e,t,{anchors:n,doc:r}){const o=[],s=r.anchors.getName(e);return s&&(n[s]=e,o.push(`&${s}`)),e.tag?o.push(Ea(r,e.tag)):t.default||o.push(Ea(r,t.tag)),o.join(" ")}function Dn(e,t,n,r){const{anchors:o,schema:s}=t.doc;let i;if(!(e instanceof Se)){const u={aliasNodes:[],onTagObj:l=>i=l,prevObjects:new Map};e=s.createNode(e,!0,null,u);for(const l of u.aliasNodes){l.source=l.source.node;let f=o.getName(l.source);f||(f=o.newName(),o.map[f]=l.source)}}if(e instanceof H)return e.toString(t,n,r);i||(i=eg(s.tags,e));const a=tg(e,i,t);a.length>0&&(t.indentAtStart=(t.indentAtStart||0)+a.length+1);const c=typeof i.stringify=="function"?i.stringify(e,t,n,r):e instanceof X?ps(e,t,n,r):e.toString(t,n,r);return a?e instanceof X||c[0]==="{"||c[0]==="["?`${a} ${c}`:`${a}
145
- ${t.indent}${c}`:c}class ys{static validAnchorNode(t){return t instanceof X||t instanceof Fe||t instanceof Ee}constructor(t){ve(this,"map",Object.create(null)),this.prefix=t}createAlias(t,n){return this.setAnchor(t,n),new Ze(t)}createMergePair(...t){const n=new $u;return n.value.items=t.map(r=>{if(r instanceof Ze){if(r.source instanceof Ee)return r}else if(r instanceof Ee)return this.createAlias(r);throw new Error("Merge sources must be Map nodes or their Aliases")}),n}getName(t){const{map:n}=this;return Object.keys(n).find(r=>n[r]===t)}getNames(){return Object.keys(this.map)}getNode(t){return this.map[t]}newName(t){t||(t=this.prefix);const n=Object.keys(this.map);for(let r=1;;++r){const o=`${t}${r}`;if(!n.includes(o))return o}}resolveNodes(){const{map:t,_cstAliases:n}=this;Object.keys(t).forEach(r=>{t[r]=t[r].resolved}),n.forEach(r=>{r.source=r.source.resolved}),delete this._cstAliases}setAnchor(t,n){if(t!=null&&!ys.validAnchorNode(t))throw new Error("Anchors may only be set for Scalar, Seq and Map nodes");if(n&&/[\x00-\x19\s,[\]{}]/.test(n))throw new Error("Anchor names must not contain whitespace or control characters");const{map:r}=this,o=t&&Object.keys(r).find(s=>r[s]===t);if(o)if(n)o!==n&&(delete r[o],r[n]=t);else return o;else{if(!n){if(!t)return null;n=this.newName()}r[n]=t}return n}}const er=(e,t)=>{if(e&&typeof e=="object"){const{tag:n}=e;e instanceof me?(n&&(t[n]=!0),e.items.forEach(r=>er(r,t))):e instanceof H?(er(e.key,t),er(e.value,t)):e instanceof X&&n&&(t[n]=!0)}return t},ng=e=>Object.keys(er(e,{}));function rg(e,t){const n={before:[],after:[]};let r,o=!1;for(const s of t)if(s.valueRange){if(r!==void 0){const a="Document contains trailing content not separated by a ... or --- line";e.errors.push(new ge(s,a));break}const i=at(e,s);o&&(i.spaceBefore=!0,o=!1),r=i}else s.comment!==null?(r===void 0?n.before:n.after).push(s.comment):s.type===j.BLANK_LINE&&(o=!0,r===void 0&&n.before.length>0&&!e.commentBefore&&(e.commentBefore=n.before.join(`
146
- `),n.before=[]));if(e.contents=r||null,!r)e.comment=n.before.concat(n.after).join(`
147
- `)||null;else{const s=n.before.join(`
148
- `);if(s){const i=r instanceof me&&r.items[0]?r.items[0]:r;i.commentBefore=i.commentBefore?`${s}
149
- ${i.commentBefore}`:s}e.comment=n.after.join(`
150
- `)||null}}function og({tagPrefixes:e},t){const[n,r]=t.parameters;if(!n||!r){const o="Insufficient parameters given for %TAG directive";throw new V(t,o)}if(e.some(o=>o.handle===n)){const o="The %TAG directive must only be given at most once per handle in the same document.";throw new V(t,o)}return{handle:n,prefix:r}}function sg(e,t){let[n]=t.parameters;if(t.name==="YAML:1.0"&&(n="1.0"),!n){const r="Insufficient parameters given for %YAML directive";throw new V(t,r)}if(!Zu[n]){const r=`Document will be parsed as YAML ${e.version||e.options.version} rather than YAML ${n}`;e.warnings.push(new Qt(t,r))}return n}function ig(e,t,n){const r=[];let o=!1;for(const s of t){const{comment:i,name:a}=s;switch(a){case"TAG":try{e.tagPrefixes.push(og(e,s))}catch(c){e.errors.push(c)}o=!0;break;case"YAML":case"YAML:1.0":if(e.version){const c="The %YAML directive must only be given at most once per document.";e.errors.push(new V(s,c))}try{e.version=sg(e,s)}catch(c){e.errors.push(c)}o=!0;break;default:if(a){const c=`YAML only supports %TAG and %YAML directives, and not %${a}`;e.warnings.push(new Qt(s,c))}}i&&r.push(i)}if(n&&!o&&(e.version||n.version||e.options.version)==="1.1"){const s=({handle:i,prefix:a})=>({handle:i,prefix:a});e.tagPrefixes=n.tagPrefixes.map(s),e.version=n.version}e.commentBefore=r.join(`
151
- `)||null}function Tt(e){if(e instanceof me)return!0;throw new Error("Expected a YAML collection as document contents")}let vs=class wo{constructor(t){this.anchors=new ys(t.anchorPrefix),this.commentBefore=null,this.comment=null,this.contents=null,this.directivesEndMarker=null,this.errors=[],this.options=t,this.schema=null,this.tagPrefixes=[],this.version=null,this.warnings=[]}add(t){return Tt(this.contents),this.contents.add(t)}addIn(t,n){Tt(this.contents),this.contents.addIn(t,n)}delete(t){return Tt(this.contents),this.contents.delete(t)}deleteIn(t){return cn(t)?this.contents==null?!1:(this.contents=null,!0):(Tt(this.contents),this.contents.deleteIn(t))}getDefaults(){return wo.defaults[this.version]||wo.defaults[this.options.version]||{}}get(t,n){return this.contents instanceof me?this.contents.get(t,n):void 0}getIn(t,n){return cn(t)?!n&&this.contents instanceof X?this.contents.value:this.contents:this.contents instanceof me?this.contents.getIn(t,n):void 0}has(t){return this.contents instanceof me?this.contents.has(t):!1}hasIn(t){return cn(t)?this.contents!==void 0:this.contents instanceof me?this.contents.hasIn(t):!1}set(t,n){Tt(this.contents),this.contents.set(t,n)}setIn(t,n){cn(t)?this.contents=n:(Tt(this.contents),this.contents.setIn(t,n))}setSchema(t,n){if(!t&&!n&&this.schema)return;typeof t=="number"&&(t=t.toFixed(1)),t==="1.0"||t==="1.1"||t==="1.2"?(this.version?this.version=t:this.options.version=t,delete this.options.schema):t&&typeof t=="string"&&(this.options.schema=t),Array.isArray(n)&&(this.options.customTags=n);const r=Object.assign({},this.getDefaults(),this.options);this.schema=new Sn(r)}parse(t,n){this.options.keepCstNodes&&(this.cstNode=t),this.options.keepNodeTypes&&(this.type="DOCUMENT");const{directives:r=[],contents:o=[],directivesEndMarker:s,error:i,valueRange:a}=t;if(i&&(i.source||(i.source=this),this.errors.push(i)),ig(this,r,n),s&&(this.directivesEndMarker=!0),this.range=a?[a.start,a.end]:null,this.setSchema(),this.anchors._cstAliases=[],rg(this,o),this.anchors.resolveNodes(),this.options.prettyErrors){for(const c of this.errors)c instanceof _t&&c.makePretty();for(const c of this.warnings)c instanceof _t&&c.makePretty()}return this}listNonDefaultTags(){return ng(this.contents).filter(t=>t.indexOf(Sn.defaultPrefix)!==0)}setTagPrefix(t,n){if(t[0]!=="!"||t[t.length-1]!=="!")throw new Error("Handle must start and end with !");if(n){const r=this.tagPrefixes.find(o=>o.handle===t);r?r.prefix=n:this.tagPrefixes.push({handle:t,prefix:n})}else this.tagPrefixes=this.tagPrefixes.filter(r=>r.handle!==t)}toJSON(t,n){const{keepBlobsInJSON:r,mapAsMap:o,maxAliasCount:s}=this.options,i=r&&(typeof t!="string"||!(this.contents instanceof X)),a={doc:this,indentStep:" ",keep:i,mapAsMap:i&&!!o,maxAliasCount:s,stringify:Dn},c=Object.keys(this.anchors.map);c.length>0&&(a.anchors=new Map(c.map(l=>[this.anchors.map[l],{alias:[],aliasCount:0,count:1}])));const u=Le(this.contents,t,a);if(typeof n=="function"&&a.anchors)for(const{count:l,res:f}of a.anchors.values())n(f,l);return u}toString(){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");const t=this.options.indent;if(!Number.isInteger(t)||t<=0){const c=JSON.stringify(t);throw new Error(`"indent" option must be a positive integer, not ${c}`)}this.setSchema();const n=[];let r=!1;if(this.version){let c="%YAML 1.2";this.schema.name==="yaml-1.1"&&(this.version==="1.0"?c="%YAML:1.0":this.version==="1.1"&&(c="%YAML 1.1")),n.push(c),r=!0}const o=this.listNonDefaultTags();this.tagPrefixes.forEach(({handle:c,prefix:u})=>{o.some(l=>l.indexOf(u)===0)&&(n.push(`%TAG ${c} ${u}`),r=!0)}),(r||this.directivesEndMarker)&&n.push("---"),this.commentBefore&&((r||!this.directivesEndMarker)&&n.unshift(""),n.unshift(this.commentBefore.replace(/^/gm,"#")));const s={anchors:Object.create(null),doc:this,indent:"",indentStep:" ".repeat(t),stringify:Dn};let i=!1,a=null;if(this.contents){this.contents instanceof Se&&(this.contents.spaceBefore&&(r||this.directivesEndMarker)&&n.push(""),this.contents.commentBefore&&n.push(this.contents.commentBefore.replace(/^/gm,"#")),s.forceBlockIndent=!!this.comment,a=this.contents.comment);const c=a?null:()=>i=!0,u=Dn(this.contents,s,()=>a=null,c);n.push(Vt(u,"",a))}else this.contents!==void 0&&n.push(Dn(this.contents,s));return this.comment&&((!i||a)&&n[n.length-1]!==""&&n.push(""),n.push(this.comment.replace(/^/gm,"#"))),n.join(`
152
- `)+`
153
- `}};ve(vs,"defaults",Zu);function ag(e,t=!0,n){n===void 0&&typeof t=="string"&&(n=t,t=!0);const r=Object.assign({},vs.defaults[cr.version],cr);return new Sn(r).createNode(e,t,n)}class Sr extends vs{constructor(t){super(Object.assign({},cr,t))}}function cg(e,t){const n=[];let r;for(const o of ls(e)){const s=new Sr(t);s.parse(o,r),n.push(s),r=s}return n}function Xu(e,t){const n=ls(e),r=new Sr(t).parse(n[0]);if(n.length>1){const o="Source contains multiple documents; please use YAML.parseAllDocuments()";r.errors.unshift(new V(n[1],o))}return r}function ug(e,t){const n=Xu(e,t);if(n.warnings.forEach(r=>Bu(r)),n.errors.length>0)throw n.errors[0];return n.toJSON()}function lg(e,t){const n=new Sr(t);return n.contents=e,String(n)}const fg={createNode:ag,defaultOptions:cr,Document:Sr,parse:ug,parseAllDocuments:cg,parseCST:ls,parseDocument:Xu,scalarOptions:Xm,stringify:lg},dg=Object.freeze(Object.defineProperty({__proto__:null,YAML:fg},Symbol.toStringTag,{value:"Module"})),pg=cm(dg);var hg=pg.YAML;const mg="1.0.0-redesign.1",gg="adhd",yg="default",vg="adhd-environment.json",Kr="config.yaml",$g="config.local.yaml",wg={data:"shared",cache:"shared",state:"shared",config:"shared",run:"shared",logs:"per-instance",temp:"per-instance"};class Na extends Error{constructor(t,n){super(`contentHash: lone surrogate in ${t} (not well-formed Unicode)`),this.location=t,this.offending=n,this.name="LoneSurrogateError"}}function Oa(e){for(let t=0;t<e.length;t++){const n=e.charCodeAt(t);if(n>=55296&&n<=56319){const r=t+1<e.length?e.charCodeAt(t+1):0;if(r<56320||r>57343)return!0;t++}else if(n>=56320&&n<=57343)return!0}return!1}function el(e,t){const n=Array.from(e),r=Array.from(t),o=Math.min(n.length,r.length);for(let s=0;s<o;s++){const i=n[s].codePointAt(0)??0,a=r[s].codePointAt(0)??0;if(i!==a)return i<a?-1:1}return n.length===r.length?0:n.length<r.length?-1:1}function _a(e){return new TextEncoder().encode(e).length}function bg(e){const t=Object.keys(e).sort(el);let n="";for(const r of t){const o=e[r];if(Oa(r))throw new Na("key",r);if(Oa(o))throw new Na("value",o);n+=`${_a(r)}:${r}=${_a(o)}:${o}
154
- `}return`sha256-${tl(n)}`}function Sg(e){const t=[...e].sort((n,r)=>el(n.name,r.name)).map(n=>`${n.name}:${n.kind}:${n.scope}`).join(`
155
- `);return`sha256-${tl(t)}`}function Eg(e){return`ADHD_${e.toUpperCase().replace(/[.-]/g,"_")}`}function Ng(e,t){return`${e}_${t.toUpperCase().replace(/[.-]/g,"_")}`}function Og(e){const t={type:"object",properties:{}},n=e;for(const r of Object.keys(n)){const o=n[r],s=r.split(".");let i=t;s.forEach((a,c)=>{if(c===s.length-1){i.properties[a]=_g(o);return}const u=i.properties[a];if(u===void 0){const l={type:"object",properties:{}};i.properties[a]=l,i=l}else i=u})}return t}function _g(e){const t={type:e.type};return e.default!==void 0&&e.secret!==!0&&(t.default=e.default),e.description!==void 0&&(t.description=e.description),e.minimum!==void 0&&(t.minimum=e.minimum),e.maximum!==void 0&&(t.maximum=e.maximum),e.enum!==void 0&&(t.enum=e.enum),e.pattern!==void 0&&(t.pattern=e.pattern),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),e.items!==void 0&&(t.items=e.items),t}const kg="adhd-env-ref:";function Ag(e){return`${kg}${e}`}const jg=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],Ig=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];function Be(e,t){return(e>>>t|e<<32-t)>>>0}function Pg(e){const t=Uint32Array.from(Ig),n=e.length*8;let r=e.length+1;for(;r%64!==56;)r++;r+=8;const o=new Uint8Array(r);o.set(e),o[e.length]=128;const s=Math.floor(n/4294967296),i=n>>>0,a=new DataView(o.buffer);a.setUint32(r-8,s,!1),a.setUint32(r-4,i,!1);const c=new Uint32Array(64);for(let f=0;f<r;f+=64){for(let S=0;S<16;S++)c[S]=a.getUint32(f+S*4,!1);for(let S=16;S<64;S++){const N=c[S-15],x=c[S-2],M=Be(N,7)^Be(N,18)^N>>>3,q=Be(x,17)^Be(x,19)^x>>>10;c[S]=c[S-16]+M+c[S-7]+q>>>0}let p=t[0],h=t[1],d=t[2],v=t[3],m=t[4],g=t[5],$=t[6],w=t[7];for(let S=0;S<64;S++){const N=Be(m,6)^Be(m,11)^Be(m,25),x=m&g^~m&$,M=w+N+x+jg[S]+c[S]>>>0,q=Be(p,2)^Be(p,13)^Be(p,22),Q=p&h^p&d^h&d,te=q+Q>>>0;w=$,$=g,g=m,m=v+M>>>0,v=d,d=h,h=p,p=M+te>>>0}t[0]=t[0]+p>>>0,t[1]=t[1]+h>>>0,t[2]=t[2]+d>>>0,t[3]=t[3]+v>>>0,t[4]=t[4]+m>>>0,t[5]=t[5]+g>>>0,t[6]=t[6]+$>>>0,t[7]=t[7]+w>>>0}const u=new Uint8Array(32),l=new DataView(u.buffer);for(let f=0;f<8;f++)l.setUint32(f*4,t[f],!1);return u}function xg(e){let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t}function tl(e){const t=new TextEncoder().encode(e);return xg(Pg(t))}function nl(e,t=""){const n={};if(e===null||typeof e!="object"||Array.isArray(e))return t&&(n[t]=e),n;for(const[r,o]of Object.entries(e)){const s=t?`${t}.${r}`:r;o!==null&&typeof o=="object"&&!Array.isArray(o)?Object.assign(n,nl(o,s)):n[s]=o}return n}function Ln(e){if(W.existsSync(e))try{const t=W.readFileSync(e,"utf8"),n=hg.parse(t);return n===null||typeof n!="object"||Array.isArray(n)?void 0:nl(n)}catch{return}}function Tg(e){return{system:Ln(F.join(e.system,Kr)),global:Ln(F.join(e.global,Kr)),project:e.project?Ln(F.join(e.project,Kr)):void 0,local:e.project?Ln(F.join(e.project,$g)):void 0}}function Cg(e){const t={source:e.source,scope:e.scope};return e.source==="env"&&e.env!==void 0&&(t.env=e.env),t}function bo(e,t){if(e===void 0)return e;switch(t){case"integer":{if(typeof e=="number")return e;const n=parseInt(String(e),10);return Number.isNaN(n)?e:n}case"number":{if(typeof e=="number")return e;const n=parseFloat(String(e));return Number.isNaN(n)?e:n}case"boolean":{if(typeof e=="boolean")return e;const n=String(e).toLowerCase();return n==="true"?!0:n==="false"?!1:e}case"array":return Array.isArray(e)?e:typeof e=="string"?e.length===0?[]:e.split(",").map(n=>n.trim()):e;case"string":return typeof e=="string"?e:String(e);default:return e}}function rl(e){const t={};for(const n of Object.keys(e)){const r=n.split(".");let o=t;r.forEach((s,i)=>{if(i===r.length-1){o[s]=e[n];return}const a=o[s];(typeof a!="object"||a===null||Array.isArray(a))&&(o[s]={}),o=o[s]})}return t}const Rg=[["system","system"],["global","global"],["project","project"],["local","local"]];function Mg(e,t,n,r){const o={},s={},i={},a={};for(const c of Object.keys(e)){const u=e[c],l=u.env&&u.env!==""?u.env:Ng(r.prefix,c),f=u.at==="runtime"||u.secret===!0,p=u.scope??r.activeScope;let h=u.default,d="default";for(const[w,S]of Rg){const N=t[w];N&&Object.prototype.hasOwnProperty.call(N,c)&&(h=bo(N[c],u.type),d=S)}const v=n[l];let m,g,$;v!==void 0?(m=bo(v,u.type),g="env",$=l):(m=h,g=d),o[c]=f?Ag(l):m,s[c]=m,i[c]=Cg(f?{source:"env",scope:p,env:l}:{source:g,scope:p,env:$}),a[c]={...u,env:l,live:f,fallbackValue:h}}return{raw:o,nested:rl(o),typedRaw:s,provenance:i,fields:a}}function Dg(e,t){return e.replace(/\$\{HOME\}/g,Gt.homedir()).replace(/\$HOME\b/g,Gt.homedir()).replace(/\$\{PROJECT_ROOT\}/g,t.projectRoot??process.cwd()).replace(/\$\{NAMESPACE\}/g,t.namespace)}function Lg(e,t){const n={};for(const[r,o]of Object.entries(e??{})){const s=o.scope??t.activeScope,i=o.share??wg[o.kind],a=o.path?Dg(o.path,t):F.join(fu(t.roots,s),r),c=i==="per-instance"?F.join(a,t.instanceId):a;n[r]={name:r,kind:o.kind,path:c,scope:s,share:i}}return n}function Ug(e,t){const n={};for(const[r,o]of Object.entries(e??{})){const s=t[o.in];if(!s)throw new Error(`files.${r}.in references unknown dirs key "${o.in}"`);n[r]={name:r,in:o.in,path:F.join(s.path,o.name),share:o.share??"shared"}}return n}var So={exports:{}},ol={},ze={},dt={},kn={},G={},En={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class n extends t{constructor($){if(super(),!e.IDENTIFIER.test($))throw new Error("CodeGen: name must be a valid identifier");this.str=$}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=n;class r extends t{constructor($){super(),this._items=typeof $=="string"?[$]:$}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const $=this._items[0];return $===""||$==='""'}get str(){var $;return($=this._str)!==null&&$!==void 0?$:this._str=this._items.reduce((w,S)=>`${w}${S}`,"")}get names(){var $;return($=this._names)!==null&&$!==void 0?$:this._names=this._items.reduce((w,S)=>(S instanceof n&&(w[S.str]=(w[S.str]||0)+1),w),{})}}e._Code=r,e.nil=new r("");function o(g,...$){const w=[g[0]];let S=0;for(;S<$.length;)a(w,$[S]),w.push(g[++S]);return new r(w)}e._=o;const s=new r("+");function i(g,...$){const w=[h(g[0])];let S=0;for(;S<$.length;)w.push(s),a(w,$[S]),w.push(s,h(g[++S]));return c(w),new r(w)}e.str=i;function a(g,$){$ instanceof r?g.push(...$._items):$ instanceof n?g.push($):g.push(f($))}e.addCodeArg=a;function c(g){let $=1;for(;$<g.length-1;){if(g[$]===s){const w=u(g[$-1],g[$+1]);if(w!==void 0){g.splice($-1,3,w);continue}g[$++]="+"}$++}}function u(g,$){if($==='""')return g;if(g==='""')return $;if(typeof g=="string")return $ instanceof n||g[g.length-1]!=='"'?void 0:typeof $!="string"?`${g.slice(0,-1)}${$}"`:$[0]==='"'?g.slice(0,-1)+$.slice(1):void 0;if(typeof $=="string"&&$[0]==='"'&&!(g instanceof n))return`"${g}${$.slice(1)}`}function l(g,$){return $.emptyStr()?g:g.emptyStr()?$:i`${g}${$}`}e.strConcat=l;function f(g){return typeof g=="number"||typeof g=="boolean"||g===null?g:h(Array.isArray(g)?g.join(","):g)}function p(g){return new r(h(g))}e.stringify=p;function h(g){return JSON.stringify(g).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=h;function d(g){return typeof g=="string"&&e.IDENTIFIER.test(g)?new r(`.${g}`):o`[${g}]`}e.getProperty=d;function v(g){if(typeof g=="string"&&e.IDENTIFIER.test(g))return new r(`${g}`);throw new Error(`CodeGen: invalid export name: ${g}, use explicit $id name mapping`)}e.getEsmExportName=v;function m(g){return new r(g.toString())}e.regexpCode=m})(En);var Eo={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=En;class n extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var r;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class o{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof t.Name?u:this.name(u)}name(u){return new t.Name(this._newName(u))}_newName(u){const l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,f;if(!((f=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||f===void 0)&&f.has(u)||this._prefixes&&!this._prefixes.has(u))throw new Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}e.Scope=o;class s extends t.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:f}){this.value=u,this.scopePath=(0,t._)`.${new t.Name(l)}[${f}]`}}e.ValueScopeName=s;const i=(0,t._)`\n`;class a extends o{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?i:t.nil}}get(){return this._scope}name(u){return new s(u,this._newName(u))}value(u,l){var f;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const p=this.toName(u),{prefix:h}=p,d=(f=l.key)!==null&&f!==void 0?f:l.ref;let v=this._values[h];if(v){const $=v.get(d);if($)return $}else v=this._values[h]=new Map;v.set(d,p);const m=this._scope[h]||(this._scope[h]=[]),g=m.length;return m[g]=l.ref,p.setValue(l,{property:h,itemIndex:g}),p}getValue(u,l){const f=this._values[u];if(f)return f.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,f=>{if(f.scopePath===void 0)throw new Error(`CodeGen: name "${f}" has no value`);return(0,t._)`${u}${f.scopePath}`})}scopeCode(u=this._values,l,f){return this._reduceValues(u,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},l,f)}_reduceValues(u,l,f={},p){let h=t.nil;for(const d in u){const v=u[d];if(!v)continue;const m=f[d]=f[d]||new Map;v.forEach(g=>{if(m.has(g))return;m.set(g,r.Started);let $=l(g);if($){const w=this.opts.es5?e.varKinds.var:e.varKinds.const;h=(0,t._)`${h}${w} ${g} = ${$};${this.opts._n}`}else if($=p==null?void 0:p(g))h=(0,t._)`${h}${$}${this.opts._n}`;else throw new n(g);m.set(g,r.Completed)})}return h}}e.ValueScope=a})(Eo);(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=En,n=Eo;var r=En;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var o=Eo;Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class s{optimizeNodes(){return this}optimizeNames(y,b){return this}}class i extends s{constructor(y,b,A){super(),this.varKind=y,this.name=b,this.rhs=A}render({es5:y,_n:b}){const A=y?n.varKinds.var:this.varKind,L=this.rhs===void 0?"":` = ${this.rhs}`;return`${A} ${this.name}${L};`+b}optimizeNames(y,b){if(y[this.name.str])return this.rhs&&(this.rhs=se(this.rhs,y,b)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class a extends s{constructor(y,b,A){super(),this.lhs=y,this.rhs=b,this.sideEffects=A}render({_n:y}){return`${this.lhs} = ${this.rhs};`+y}optimizeNames(y,b){if(!(this.lhs instanceof t.Name&&!y[this.lhs.str]&&!this.sideEffects))return this.rhs=se(this.rhs,y,b),this}get names(){const y=this.lhs instanceof t.Name?{}:{...this.lhs.names};return re(y,this.rhs)}}class c extends a{constructor(y,b,A,L){super(y,A,L),this.op=b}render({_n:y}){return`${this.lhs} ${this.op}= ${this.rhs};`+y}}class u extends s{constructor(y){super(),this.label=y,this.names={}}render({_n:y}){return`${this.label}:`+y}}class l extends s{constructor(y){super(),this.label=y,this.names={}}render({_n:y}){return`break${this.label?` ${this.label}`:""};`+y}}class f extends s{constructor(y){super(),this.error=y}render({_n:y}){return`throw ${this.error};`+y}get names(){return this.error.names}}class p extends s{constructor(y){super(),this.code=y}render({_n:y}){return`${this.code};`+y}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(y,b){return this.code=se(this.code,y,b),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class h extends s{constructor(y=[]){super(),this.nodes=y}render(y){return this.nodes.reduce((b,A)=>b+A.render(y),"")}optimizeNodes(){const{nodes:y}=this;let b=y.length;for(;b--;){const A=y[b].optimizeNodes();Array.isArray(A)?y.splice(b,1,...A):A?y[b]=A:y.splice(b,1)}return y.length>0?this:void 0}optimizeNames(y,b){const{nodes:A}=this;let L=A.length;for(;L--;){const B=A[L];B.optimizeNames(y,b)||(qe(y,B.names),A.splice(L,1))}return A.length>0?this:void 0}get names(){return this.nodes.reduce((y,b)=>le(y,b.names),{})}}class d extends h{render(y){return"{"+y._n+super.render(y)+"}"+y._n}}class v extends h{}class m extends d{}m.kind="else";class g extends d{constructor(y,b){super(b),this.condition=y}render(y){let b=`if(${this.condition})`+super.render(y);return this.else&&(b+="else "+this.else.render(y)),b}optimizeNodes(){super.optimizeNodes();const y=this.condition;if(y===!0)return this.nodes;let b=this.else;if(b){const A=b.optimizeNodes();b=this.else=Array.isArray(A)?new m(A):A}if(b)return y===!1?b instanceof g?b:b.nodes:this.nodes.length?this:new g(lt(y),b instanceof g?[b]:b.nodes);if(!(y===!1||!this.nodes.length))return this}optimizeNames(y,b){var A;if(this.else=(A=this.else)===null||A===void 0?void 0:A.optimizeNames(y,b),!!(super.optimizeNames(y,b)||this.else))return this.condition=se(this.condition,y,b),this}get names(){const y=super.names;return re(y,this.condition),this.else&&le(y,this.else.names),y}}g.kind="if";class $ extends d{}$.kind="for";class w extends ${constructor(y){super(),this.iteration=y}render(y){return`for(${this.iteration})`+super.render(y)}optimizeNames(y,b){if(super.optimizeNames(y,b))return this.iteration=se(this.iteration,y,b),this}get names(){return le(super.names,this.iteration.names)}}class S extends ${constructor(y,b,A,L){super(),this.varKind=y,this.name=b,this.from=A,this.to=L}render(y){const b=y.es5?n.varKinds.var:this.varKind,{name:A,from:L,to:B}=this;return`for(${b} ${A}=${L}; ${A}<${B}; ${A}++)`+super.render(y)}get names(){const y=re(super.names,this.from);return re(y,this.to)}}class N extends ${constructor(y,b,A,L){super(),this.loop=y,this.varKind=b,this.name=A,this.iterable=L}render(y){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(y)}optimizeNames(y,b){if(super.optimizeNames(y,b))return this.iterable=se(this.iterable,y,b),this}get names(){return le(super.names,this.iterable.names)}}class x extends d{constructor(y,b,A){super(),this.name=y,this.args=b,this.async=A}render(y){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(y)}}x.kind="func";class M extends h{render(y){return"return "+super.render(y)}}M.kind="return";class q extends d{render(y){let b="try"+super.render(y);return this.catch&&(b+=this.catch.render(y)),this.finally&&(b+=this.finally.render(y)),b}optimizeNodes(){var y,b;return super.optimizeNodes(),(y=this.catch)===null||y===void 0||y.optimizeNodes(),(b=this.finally)===null||b===void 0||b.optimizeNodes(),this}optimizeNames(y,b){var A,L;return super.optimizeNames(y,b),(A=this.catch)===null||A===void 0||A.optimizeNames(y,b),(L=this.finally)===null||L===void 0||L.optimizeNames(y,b),this}get names(){const y=super.names;return this.catch&&le(y,this.catch.names),this.finally&&le(y,this.finally.names),y}}class Q extends d{constructor(y){super(),this.error=y}render(y){return`catch(${this.error})`+super.render(y)}}Q.kind="catch";class te extends d{render(y){return"finally"+super.render(y)}}te.kind="finally";class ne{constructor(y,b={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...b,_n:b.lines?`
156
- `:""},this._extScope=y,this._scope=new n.Scope({parent:y}),this._nodes=[new v]}toString(){return this._root.render(this.opts)}name(y){return this._scope.name(y)}scopeName(y){return this._extScope.name(y)}scopeValue(y,b){const A=this._extScope.value(y,b);return(this._values[A.prefix]||(this._values[A.prefix]=new Set)).add(A),A}getScopeValue(y,b){return this._extScope.getValue(y,b)}scopeRefs(y){return this._extScope.scopeRefs(y,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(y,b,A,L){const B=this._scope.toName(b);return A!==void 0&&L&&(this._constants[B.str]=A),this._leafNode(new i(y,B,A)),B}const(y,b,A){return this._def(n.varKinds.const,y,b,A)}let(y,b,A){return this._def(n.varKinds.let,y,b,A)}var(y,b,A){return this._def(n.varKinds.var,y,b,A)}assign(y,b,A){return this._leafNode(new a(y,b,A))}add(y,b){return this._leafNode(new c(y,e.operators.ADD,b))}code(y){return typeof y=="function"?y():y!==t.nil&&this._leafNode(new p(y)),this}object(...y){const b=["{"];for(const[A,L]of y)b.length>1&&b.push(","),b.push(A),(A!==L||this.opts.es5)&&(b.push(":"),(0,t.addCodeArg)(b,L));return b.push("}"),new t._Code(b)}if(y,b,A){if(this._blockNode(new g(y)),b&&A)this.code(b).else().code(A).endIf();else if(b)this.code(b).endIf();else if(A)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(y){return this._elseNode(new g(y))}else(){return this._elseNode(new m)}endIf(){return this._endBlockNode(g,m)}_for(y,b){return this._blockNode(y),b&&this.code(b).endFor(),this}for(y,b){return this._for(new w(y),b)}forRange(y,b,A,L,B=this.opts.es5?n.varKinds.var:n.varKinds.let){const Y=this._scope.toName(y);return this._for(new S(B,Y,b,A),()=>L(Y))}forOf(y,b,A,L=n.varKinds.const){const B=this._scope.toName(y);if(this.opts.es5){const Y=b instanceof t.Name?b:this.var("_arr",b);return this.forRange("_i",0,(0,t._)`${Y}.length`,J=>{this.var(B,(0,t._)`${Y}[${J}]`),A(B)})}return this._for(new N("of",L,B,b),()=>A(B))}forIn(y,b,A,L=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(y,(0,t._)`Object.keys(${b})`,A);const B=this._scope.toName(y);return this._for(new N("in",L,B,b),()=>A(B))}endFor(){return this._endBlockNode($)}label(y){return this._leafNode(new u(y))}break(y){return this._leafNode(new l(y))}return(y){const b=new M;if(this._blockNode(b),this.code(y),b.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(M)}try(y,b,A){if(!b&&!A)throw new Error('CodeGen: "try" without "catch" and "finally"');const L=new q;if(this._blockNode(L),this.code(y),b){const B=this.name("e");this._currNode=L.catch=new Q(B),b(B)}return A&&(this._currNode=L.finally=new te,this.code(A)),this._endBlockNode(Q,te)}throw(y){return this._leafNode(new f(y))}block(y,b){return this._blockStarts.push(this._nodes.length),y&&this.code(y).endBlock(b),this}endBlock(y){const b=this._blockStarts.pop();if(b===void 0)throw new Error("CodeGen: not in self-balancing block");const A=this._nodes.length-b;if(A<0||y!==void 0&&A!==y)throw new Error(`CodeGen: wrong number of nodes: ${A} vs ${y} expected`);return this._nodes.length=b,this}func(y,b=t.nil,A,L){return this._blockNode(new x(y,b,A)),L&&this.code(L).endFunc(),this}endFunc(){return this._endBlockNode(x)}optimize(y=1){for(;y-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(y){return this._currNode.nodes.push(y),this}_blockNode(y){this._currNode.nodes.push(y),this._nodes.push(y)}_endBlockNode(y,b){const A=this._currNode;if(A instanceof y||b&&A instanceof b)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${b?`${y.kind}/${b.kind}`:y.kind}"`)}_elseNode(y){const b=this._currNode;if(!(b instanceof g))throw new Error('CodeGen: "else" without "if"');return this._currNode=b.else=y,this}get _root(){return this._nodes[0]}get _currNode(){const y=this._nodes;return y[y.length-1]}set _currNode(y){const b=this._nodes;b[b.length-1]=y}}e.CodeGen=ne;function le(k,y){for(const b in y)k[b]=(k[b]||0)+(y[b]||0);return k}function re(k,y){return y instanceof t._CodeOrName?le(k,y.names):k}function se(k,y,b){if(k instanceof t.Name)return A(k);if(!L(k))return k;return new t._Code(k._items.reduce((B,Y)=>(Y instanceof t.Name&&(Y=A(Y)),Y instanceof t._Code?B.push(...Y._items):B.push(Y),B),[]));function A(B){const Y=b[B.str];return Y===void 0||y[B.str]!==1?B:(delete y[B.str],Y)}function L(B){return B instanceof t._Code&&B._items.some(Y=>Y instanceof t.Name&&y[Y.str]===1&&b[Y.str]!==void 0)}}function qe(k,y){for(const b in y)k[b]=(k[b]||0)-(y[b]||0)}function lt(k){return typeof k=="boolean"||typeof k=="number"||k===null?!k:(0,t._)`!${P(k)}`}e.not=lt;const It=O(e.operators.AND);function tn(...k){return k.reduce(It)}e.and=tn;const Pt=O(e.operators.OR);function C(...k){return k.reduce(Pt)}e.or=C;function O(k){return(y,b)=>y===t.nil?b:b===t.nil?y:(0,t._)`${P(y)} ${k} ${P(b)}`}function P(k){return k instanceof t.Name?k:(0,t._)`(${k})`}})(G);var D={};Object.defineProperty(D,"__esModule",{value:!0});D.checkStrictMode=D.getErrorPath=D.Type=D.useFunc=D.setEvaluated=D.evaluatedPropsToName=D.mergeEvaluated=D.eachItem=D.unescapeJsonPointer=D.escapeJsonPointer=D.escapeFragment=D.unescapeFragment=D.schemaRefOrVal=D.schemaHasRulesButRef=D.schemaHasRules=D.checkUnknownRules=D.alwaysValidSchema=D.toHash=void 0;const ee=G,Bg=En;function Fg(e){const t={};for(const n of e)t[n]=!0;return t}D.toHash=Fg;function Vg(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(sl(e,t),!il(t,e.self.RULES.all))}D.alwaysValidSchema=Vg;function sl(e,t=e.schema){const{opts:n,self:r}=e;if(!n.strictSchema||typeof t=="boolean")return;const o=r.RULES.keywords;for(const s in t)o[s]||ul(e,`unknown keyword: "${s}"`)}D.checkUnknownRules=sl;function il(e,t){if(typeof e=="boolean")return!e;for(const n in e)if(t[n])return!0;return!1}D.schemaHasRules=il;function Kg(e,t){if(typeof e=="boolean")return!e;for(const n in e)if(n!=="$ref"&&t.all[n])return!0;return!1}D.schemaHasRulesButRef=Kg;function qg({topSchemaRef:e,schemaPath:t},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,ee._)`${n}`}return(0,ee._)`${e}${t}${(0,ee.getProperty)(r)}`}D.schemaRefOrVal=qg;function zg(e){return al(decodeURIComponent(e))}D.unescapeFragment=zg;function Gg(e){return encodeURIComponent($s(e))}D.escapeFragment=Gg;function $s(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}D.escapeJsonPointer=$s;function al(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}D.unescapeJsonPointer=al;function Hg(e,t){if(Array.isArray(e))for(const n of e)t(n);else t(e)}D.eachItem=Hg;function ka({mergeNames:e,mergeToName:t,mergeValues:n,resultToName:r}){return(o,s,i,a)=>{const c=i===void 0?s:i instanceof ee.Name?(s instanceof ee.Name?e(o,s,i):t(o,s,i),i):s instanceof ee.Name?(t(o,i,s),s):n(s,i);return a===ee.Name&&!(c instanceof ee.Name)?r(o,c):c}}D.mergeEvaluated={props:ka({mergeNames:(e,t,n)=>e.if((0,ee._)`${n} !== true && ${t} !== undefined`,()=>{e.if((0,ee._)`${t} === true`,()=>e.assign(n,!0),()=>e.assign(n,(0,ee._)`${n} || {}`).code((0,ee._)`Object.assign(${n}, ${t})`))}),mergeToName:(e,t,n)=>e.if((0,ee._)`${n} !== true`,()=>{t===!0?e.assign(n,!0):(e.assign(n,(0,ee._)`${n} || {}`),ws(e,n,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:cl}),items:ka({mergeNames:(e,t,n)=>e.if((0,ee._)`${n} !== true && ${t} !== undefined`,()=>e.assign(n,(0,ee._)`${t} === true ? true : ${n} > ${t} ? ${n} : ${t}`)),mergeToName:(e,t,n)=>e.if((0,ee._)`${n} !== true`,()=>e.assign(n,t===!0?!0:(0,ee._)`${n} > ${t} ? ${n} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function cl(e,t){if(t===!0)return e.var("props",!0);const n=e.var("props",(0,ee._)`{}`);return t!==void 0&&ws(e,n,t),n}D.evaluatedPropsToName=cl;function ws(e,t,n){Object.keys(n).forEach(r=>e.assign((0,ee._)`${t}${(0,ee.getProperty)(r)}`,!0))}D.setEvaluated=ws;const Aa={};function Jg(e,t){return e.scopeValue("func",{ref:t,code:Aa[t.code]||(Aa[t.code]=new Bg._Code(t.code))})}D.useFunc=Jg;var No;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(No||(D.Type=No={}));function Wg(e,t,n){if(e instanceof ee.Name){const r=t===No.Num;return n?r?(0,ee._)`"[" + ${e} + "]"`:(0,ee._)`"['" + ${e} + "']"`:r?(0,ee._)`"/" + ${e}`:(0,ee._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,ee.getProperty)(e).toString():"/"+$s(e)}D.getErrorPath=Wg;function ul(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw new Error(t);e.self.logger.warn(t)}}D.checkStrictMode=ul;var Ke={};Object.defineProperty(Ke,"__esModule",{value:!0});const ye=G,Qg={data:new ye.Name("data"),valCxt:new ye.Name("valCxt"),instancePath:new ye.Name("instancePath"),parentData:new ye.Name("parentData"),parentDataProperty:new ye.Name("parentDataProperty"),rootData:new ye.Name("rootData"),dynamicAnchors:new ye.Name("dynamicAnchors"),vErrors:new ye.Name("vErrors"),errors:new ye.Name("errors"),this:new ye.Name("this"),self:new ye.Name("self"),scope:new ye.Name("scope"),json:new ye.Name("json"),jsonPos:new ye.Name("jsonPos"),jsonLen:new ye.Name("jsonLen"),jsonPart:new ye.Name("jsonPart")};Ke.default=Qg;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=G,n=D,r=Ke;e.keywordError={message:({keyword:m})=>(0,t.str)`must pass "${m}" keyword validation`},e.keyword$DataError={message:({keyword:m,schemaType:g})=>g?(0,t.str)`"${m}" keyword must be ${g} ($data)`:(0,t.str)`"${m}" keyword is invalid ($data)`};function o(m,g=e.keywordError,$,w){const{it:S}=m,{gen:N,compositeRule:x,allErrors:M}=S,q=f(m,g,$);w??(x||M)?c(N,q):u(S,(0,t._)`[${q}]`)}e.reportError=o;function s(m,g=e.keywordError,$){const{it:w}=m,{gen:S,compositeRule:N,allErrors:x}=w,M=f(m,g,$);c(S,M),N||x||u(w,r.default.vErrors)}e.reportExtraError=s;function i(m,g){m.assign(r.default.errors,g),m.if((0,t._)`${r.default.vErrors} !== null`,()=>m.if(g,()=>m.assign((0,t._)`${r.default.vErrors}.length`,g),()=>m.assign(r.default.vErrors,null)))}e.resetErrorsCount=i;function a({gen:m,keyword:g,schemaValue:$,data:w,errsCount:S,it:N}){if(S===void 0)throw new Error("ajv implementation error");const x=m.name("err");m.forRange("i",S,r.default.errors,M=>{m.const(x,(0,t._)`${r.default.vErrors}[${M}]`),m.if((0,t._)`${x}.instancePath === undefined`,()=>m.assign((0,t._)`${x}.instancePath`,(0,t.strConcat)(r.default.instancePath,N.errorPath))),m.assign((0,t._)`${x}.schemaPath`,(0,t.str)`${N.errSchemaPath}/${g}`),N.opts.verbose&&(m.assign((0,t._)`${x}.schema`,$),m.assign((0,t._)`${x}.data`,w))})}e.extendErrors=a;function c(m,g){const $=m.const("err",g);m.if((0,t._)`${r.default.vErrors} === null`,()=>m.assign(r.default.vErrors,(0,t._)`[${$}]`),(0,t._)`${r.default.vErrors}.push(${$})`),m.code((0,t._)`${r.default.errors}++`)}function u(m,g){const{gen:$,validateName:w,schemaEnv:S}=m;S.$async?$.throw((0,t._)`new ${m.ValidationError}(${g})`):($.assign((0,t._)`${w}.errors`,g),$.return(!1))}const l={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function f(m,g,$){const{createErrors:w}=m.it;return w===!1?(0,t._)`{}`:p(m,g,$)}function p(m,g,$={}){const{gen:w,it:S}=m,N=[h(S,$),d(m,$)];return v(m,g,N),w.object(...N)}function h({errorPath:m},{instancePath:g}){const $=g?(0,t.str)`${m}${(0,n.getErrorPath)(g,n.Type.Str)}`:m;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,$)]}function d({keyword:m,it:{errSchemaPath:g}},{schemaPath:$,parentSchema:w}){let S=w?g:(0,t.str)`${g}/${m}`;return $&&(S=(0,t.str)`${S}${(0,n.getErrorPath)($,n.Type.Str)}`),[l.schemaPath,S]}function v(m,{params:g,message:$},w){const{keyword:S,data:N,schemaValue:x,it:M}=m,{opts:q,propertyName:Q,topSchemaRef:te,schemaPath:ne}=M;w.push([l.keyword,S],[l.params,typeof g=="function"?g(m):g||(0,t._)`{}`]),q.messages&&w.push([l.message,typeof $=="function"?$(m):$]),q.verbose&&w.push([l.schema,x],[l.parentSchema,(0,t._)`${te}${ne}`],[r.default.data,N]),Q&&w.push([l.propertyName,Q])}})(kn);var ja;function Yg(){if(ja)return dt;ja=1,Object.defineProperty(dt,"__esModule",{value:!0}),dt.boolOrEmptySchema=dt.topBoolOrEmptySchema=void 0;const e=kn,t=G,n=Ke,r={message:"boolean schema is false"};function o(a){const{gen:c,schema:u,validateName:l}=a;u===!1?i(a,!1):typeof u=="object"&&u.$async===!0?c.return(n.default.data):(c.assign((0,t._)`${l}.errors`,null),c.return(!0))}dt.topBoolOrEmptySchema=o;function s(a,c){const{gen:u,schema:l}=a;l===!1?(u.var(c,!1),i(a)):u.var(c,!0)}dt.boolOrEmptySchema=s;function i(a,c){const{gen:u,data:l}=a,f={gen:u,keyword:"false schema",data:l,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:a};(0,e.reportError)(f,r,void 0,c)}return dt}var ce={},kt={};Object.defineProperty(kt,"__esModule",{value:!0});kt.getRules=kt.isJSONType=void 0;const Zg=["string","number","integer","boolean","null","object","array"],Xg=new Set(Zg);function ey(e){return typeof e=="string"&&Xg.has(e)}kt.isJSONType=ey;function ty(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}kt.getRules=ty;var Ye={};Object.defineProperty(Ye,"__esModule",{value:!0});Ye.shouldUseRule=Ye.shouldUseGroup=Ye.schemaHasRulesForType=void 0;function ny({schema:e,self:t},n){const r=t.RULES.types[n];return r&&r!==!0&&ll(e,r)}Ye.schemaHasRulesForType=ny;function ll(e,t){return t.rules.some(n=>fl(e,n))}Ye.shouldUseGroup=ll;function fl(e,t){var n;return e[t.keyword]!==void 0||((n=t.definition.implements)===null||n===void 0?void 0:n.some(r=>e[r]!==void 0))}Ye.shouldUseRule=fl;Object.defineProperty(ce,"__esModule",{value:!0});ce.reportTypeError=ce.checkDataTypes=ce.checkDataType=ce.coerceAndCheckDataType=ce.getJSONTypes=ce.getSchemaTypes=ce.DataType=void 0;const ry=kt,oy=Ye,sy=kn,K=G,dl=D;var qt;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(qt||(ce.DataType=qt={}));function iy(e){const t=pl(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}ce.getSchemaTypes=iy;function pl(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(ry.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}ce.getJSONTypes=pl;function ay(e,t){const{gen:n,data:r,opts:o}=e,s=cy(t,o.coerceTypes),i=t.length>0&&!(s.length===0&&t.length===1&&(0,oy.schemaHasRulesForType)(e,t[0]));if(i){const a=bs(t,r,o.strictNumbers,qt.Wrong);n.if(a,()=>{s.length?uy(e,t,s):Ss(e)})}return i}ce.coerceAndCheckDataType=ay;const hl=new Set(["string","number","integer","boolean","null"]);function cy(e,t){return t?e.filter(n=>hl.has(n)||t==="array"&&n==="array"):[]}function uy(e,t,n){const{gen:r,data:o,opts:s}=e,i=r.let("dataType",(0,K._)`typeof ${o}`),a=r.let("coerced",(0,K._)`undefined`);s.coerceTypes==="array"&&r.if((0,K._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,K._)`${o}[0]`).assign(i,(0,K._)`typeof ${o}`).if(bs(t,o,s.strictNumbers),()=>r.assign(a,o))),r.if((0,K._)`${a} !== undefined`);for(const u of n)(hl.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);r.else(),Ss(e),r.endIf(),r.if((0,K._)`${a} !== undefined`,()=>{r.assign(o,a),ly(e,a)});function c(u){switch(u){case"string":r.elseIf((0,K._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,K._)`"" + ${o}`).elseIf((0,K._)`${o} === null`).assign(a,(0,K._)`""`);return;case"number":r.elseIf((0,K._)`${i} == "boolean" || ${o} === null
157
- || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,K._)`+${o}`);return;case"integer":r.elseIf((0,K._)`${i} === "boolean" || ${o} === null
158
- || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,K._)`+${o}`);return;case"boolean":r.elseIf((0,K._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,K._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":r.elseIf((0,K._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(a,null);return;case"array":r.elseIf((0,K._)`${i} === "string" || ${i} === "number"
159
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,K._)`[${o}]`)}}}function ly({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,K._)`${t} !== undefined`,()=>e.assign((0,K._)`${t}[${n}]`,r))}function Oo(e,t,n,r=qt.Correct){const o=r===qt.Correct?K.operators.EQ:K.operators.NEQ;let s;switch(e){case"null":return(0,K._)`${t} ${o} null`;case"array":s=(0,K._)`Array.isArray(${t})`;break;case"object":s=(0,K._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=i((0,K._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=i();break;default:return(0,K._)`typeof ${t} ${o} ${e}`}return r===qt.Correct?s:(0,K.not)(s);function i(a=K.nil){return(0,K.and)((0,K._)`typeof ${t} == "number"`,a,n?(0,K._)`isFinite(${t})`:K.nil)}}ce.checkDataType=Oo;function bs(e,t,n,r){if(e.length===1)return Oo(e[0],t,n,r);let o;const s=(0,dl.toHash)(e);if(s.array&&s.object){const i=(0,K._)`typeof ${t} != "object"`;o=s.null?i:(0,K._)`!${t} || ${i}`,delete s.null,delete s.array,delete s.object}else o=K.nil;s.number&&delete s.integer;for(const i in s)o=(0,K.and)(o,Oo(i,t,n,r));return o}ce.checkDataTypes=bs;const fy={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,K._)`{type: ${e}}`:(0,K._)`{type: ${t}}`};function Ss(e){const t=dy(e);(0,sy.reportError)(t,fy)}ce.reportTypeError=Ss;function dy(e){const{gen:t,data:n,schema:r}=e,o=(0,dl.schemaRefOrVal)(e,r,"type");return{gen:t,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:e}}var on={},Ia;function py(){if(Ia)return on;Ia=1,Object.defineProperty(on,"__esModule",{value:!0}),on.assignDefaults=void 0;const e=G,t=D;function n(o,s){const{properties:i,items:a}=o.schema;if(s==="object"&&i)for(const c in i)r(o,c,i[c].default);else s==="array"&&Array.isArray(a)&&a.forEach((c,u)=>r(o,u,c.default))}on.assignDefaults=n;function r(o,s,i){const{gen:a,compositeRule:c,data:u,opts:l}=o;if(i===void 0)return;const f=(0,e._)`${u}${(0,e.getProperty)(s)}`;if(c){(0,t.checkStrictMode)(o,`default is ignored for: ${f}`);return}let p=(0,e._)`${f} === undefined`;l.useDefaults==="empty"&&(p=(0,e._)`${p} || ${f} === null || ${f} === ""`),a.if(p,(0,e._)`${f} = ${(0,e.stringify)(i)}`)}return on}var Te={},Z={},Pa;function Ue(){if(Pa)return Z;Pa=1,Object.defineProperty(Z,"__esModule",{value:!0}),Z.validateUnion=Z.validateArray=Z.usePattern=Z.callValidateCode=Z.schemaProperties=Z.allSchemaProperties=Z.noPropertyInData=Z.propertyInData=Z.isOwnProperty=Z.hasPropFunc=Z.reportMissingProp=Z.checkMissingProp=Z.checkReportMissingProp=void 0;const e=G,t=D,n=Ke,r=D;function o($,w){const{gen:S,data:N,it:x}=$;S.if(l(S,N,w,x.opts.ownProperties),()=>{$.setParams({missingProperty:(0,e._)`${w}`},!0),$.error()})}Z.checkReportMissingProp=o;function s({gen:$,data:w,it:{opts:S}},N,x){return(0,e.or)(...N.map(M=>(0,e.and)(l($,w,M,S.ownProperties),(0,e._)`${x} = ${M}`)))}Z.checkMissingProp=s;function i($,w){$.setParams({missingProperty:w},!0),$.error()}Z.reportMissingProp=i;function a($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}Z.hasPropFunc=a;function c($,w,S){return(0,e._)`${a($)}.call(${w}, ${S})`}Z.isOwnProperty=c;function u($,w,S,N){const x=(0,e._)`${w}${(0,e.getProperty)(S)} !== undefined`;return N?(0,e._)`${x} && ${c($,w,S)}`:x}Z.propertyInData=u;function l($,w,S,N){const x=(0,e._)`${w}${(0,e.getProperty)(S)} === undefined`;return N?(0,e.or)(x,(0,e.not)(c($,w,S))):x}Z.noPropertyInData=l;function f($){return $?Object.keys($).filter(w=>w!=="__proto__"):[]}Z.allSchemaProperties=f;function p($,w){return f(w).filter(S=>!(0,t.alwaysValidSchema)($,w[S]))}Z.schemaProperties=p;function h({schemaCode:$,data:w,it:{gen:S,topSchemaRef:N,schemaPath:x,errorPath:M},it:q},Q,te,ne){const le=ne?(0,e._)`${$}, ${w}, ${N}${x}`:w,re=[[n.default.instancePath,(0,e.strConcat)(n.default.instancePath,M)],[n.default.parentData,q.parentData],[n.default.parentDataProperty,q.parentDataProperty],[n.default.rootData,n.default.rootData]];q.opts.dynamicRef&&re.push([n.default.dynamicAnchors,n.default.dynamicAnchors]);const se=(0,e._)`${le}, ${S.object(...re)}`;return te!==e.nil?(0,e._)`${Q}.call(${te}, ${se})`:(0,e._)`${Q}(${se})`}Z.callValidateCode=h;const d=(0,e._)`new RegExp`;function v({gen:$,it:{opts:w}},S){const N=w.unicodeRegExp?"u":"",{regExp:x}=w.code,M=x(S,N);return $.scopeValue("pattern",{key:M.toString(),ref:M,code:(0,e._)`${x.code==="new RegExp"?d:(0,r.useFunc)($,x)}(${S}, ${N})`})}Z.usePattern=v;function m($){const{gen:w,data:S,keyword:N,it:x}=$,M=w.name("valid");if(x.allErrors){const Q=w.let("valid",!0);return q(()=>w.assign(Q,!1)),Q}return w.var(M,!0),q(()=>w.break()),M;function q(Q){const te=w.const("len",(0,e._)`${S}.length`);w.forRange("i",0,te,ne=>{$.subschema({keyword:N,dataProp:ne,dataPropType:t.Type.Num},M),w.if((0,e.not)(M),Q)})}}Z.validateArray=m;function g($){const{gen:w,schema:S,keyword:N,it:x}=$;if(!Array.isArray(S))throw new Error("ajv implementation error");if(S.some(Q=>(0,t.alwaysValidSchema)(x,Q))&&!x.opts.unevaluated)return;const M=w.let("valid",!1),q=w.name("_valid");w.block(()=>S.forEach((Q,te)=>{const ne=$.subschema({keyword:N,schemaProp:te,compositeRule:!0},q);w.assign(M,(0,e._)`${M} || ${q}`),$.mergeValidEvaluated(ne,q)||w.if((0,e.not)(M))})),$.result(M,()=>$.reset(),()=>$.error(!0))}return Z.validateUnion=g,Z}var xa;function hy(){if(xa)return Te;xa=1,Object.defineProperty(Te,"__esModule",{value:!0}),Te.validateKeywordUsage=Te.validSchemaType=Te.funcKeywordCode=Te.macroKeywordCode=void 0;const e=G,t=Ke,n=Ue(),r=kn;function o(p,h){const{gen:d,keyword:v,schema:m,parentSchema:g,it:$}=p,w=h.macro.call($.self,m,g,$),S=u(d,v,w);$.opts.validateSchema!==!1&&$.self.validateSchema(w,!0);const N=d.name("valid");p.subschema({schema:w,schemaPath:e.nil,errSchemaPath:`${$.errSchemaPath}/${v}`,topSchemaRef:S,compositeRule:!0},N),p.pass(N,()=>p.error(!0))}Te.macroKeywordCode=o;function s(p,h){var d;const{gen:v,keyword:m,schema:g,parentSchema:$,$data:w,it:S}=p;c(S,h);const N=!w&&h.compile?h.compile.call(S.self,g,$,S):h.validate,x=u(v,m,N),M=v.let("valid");p.block$data(M,q),p.ok((d=h.valid)!==null&&d!==void 0?d:M);function q(){if(h.errors===!1)ne(),h.modifying&&i(p),le(()=>p.error());else{const re=h.async?Q():te();h.modifying&&i(p),le(()=>a(p,re))}}function Q(){const re=v.let("ruleErrs",null);return v.try(()=>ne((0,e._)`await `),se=>v.assign(M,!1).if((0,e._)`${se} instanceof ${S.ValidationError}`,()=>v.assign(re,(0,e._)`${se}.errors`),()=>v.throw(se))),re}function te(){const re=(0,e._)`${x}.errors`;return v.assign(re,null),ne(e.nil),re}function ne(re=h.async?(0,e._)`await `:e.nil){const se=S.opts.passContext?t.default.this:t.default.self,qe=!("compile"in h&&!w||h.schema===!1);v.assign(M,(0,e._)`${re}${(0,n.callValidateCode)(p,x,se,qe)}`,h.modifying)}function le(re){var se;v.if((0,e.not)((se=h.valid)!==null&&se!==void 0?se:M),re)}}Te.funcKeywordCode=s;function i(p){const{gen:h,data:d,it:v}=p;h.if(v.parentData,()=>h.assign(d,(0,e._)`${v.parentData}[${v.parentDataProperty}]`))}function a(p,h){const{gen:d}=p;d.if((0,e._)`Array.isArray(${h})`,()=>{d.assign(t.default.vErrors,(0,e._)`${t.default.vErrors} === null ? ${h} : ${t.default.vErrors}.concat(${h})`).assign(t.default.errors,(0,e._)`${t.default.vErrors}.length`),(0,r.extendErrors)(p)},()=>p.error())}function c({schemaEnv:p},h){if(h.async&&!p.$async)throw new Error("async keyword in sync schema")}function u(p,h,d){if(d===void 0)throw new Error(`keyword "${h}" failed to compile`);return p.scopeValue("keyword",typeof d=="function"?{ref:d}:{ref:d,code:(0,e.stringify)(d)})}function l(p,h,d=!1){return!h.length||h.some(v=>v==="array"?Array.isArray(p):v==="object"?p&&typeof p=="object"&&!Array.isArray(p):typeof p==v||d&&typeof p>"u")}Te.validSchemaType=l;function f({schema:p,opts:h,self:d,errSchemaPath:v},m,g){if(Array.isArray(m.keyword)?!m.keyword.includes(g):m.keyword!==g)throw new Error("ajv implementation error");const $=m.dependencies;if($!=null&&$.some(w=>!Object.prototype.hasOwnProperty.call(p,w)))throw new Error(`parent schema must have dependencies of ${g}: ${$.join(",")}`);if(m.validateSchema&&!m.validateSchema(p[g])){const w=`keyword "${g}" value is invalid at path "${v}": `+d.errorsText(m.validateSchema.errors);if(h.validateSchema==="log")d.logger.error(w);else throw new Error(w)}}return Te.validateKeywordUsage=f,Te}var Ge={},Ta;function my(){if(Ta)return Ge;Ta=1,Object.defineProperty(Ge,"__esModule",{value:!0}),Ge.extendSubschemaMode=Ge.extendSubschemaData=Ge.getSubschema=void 0;const e=G,t=D;function n(s,{keyword:i,schemaProp:a,schema:c,schemaPath:u,errSchemaPath:l,topSchemaRef:f}){if(i!==void 0&&c!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(i!==void 0){const p=s.schema[i];return a===void 0?{schema:p,schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(i)}`,errSchemaPath:`${s.errSchemaPath}/${i}`}:{schema:p[a],schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(i)}${(0,e.getProperty)(a)}`,errSchemaPath:`${s.errSchemaPath}/${i}/${(0,t.escapeFragment)(a)}`}}if(c!==void 0){if(u===void 0||l===void 0||f===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:c,schemaPath:u,topSchemaRef:f,errSchemaPath:l}}throw new Error('either "keyword" or "schema" must be passed')}Ge.getSubschema=n;function r(s,i,{dataProp:a,dataPropType:c,data:u,dataTypes:l,propertyName:f}){if(u!==void 0&&a!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:p}=i;if(a!==void 0){const{errorPath:d,dataPathArr:v,opts:m}=i,g=p.let("data",(0,e._)`${i.data}${(0,e.getProperty)(a)}`,!0);h(g),s.errorPath=(0,e.str)`${d}${(0,t.getErrorPath)(a,c,m.jsPropertySyntax)}`,s.parentDataProperty=(0,e._)`${a}`,s.dataPathArr=[...v,s.parentDataProperty]}if(u!==void 0){const d=u instanceof e.Name?u:p.let("data",u,!0);h(d),f!==void 0&&(s.propertyName=f)}l&&(s.dataTypes=l);function h(d){s.data=d,s.dataLevel=i.dataLevel+1,s.dataTypes=[],i.definedProperties=new Set,s.parentData=i.data,s.dataNames=[...i.dataNames,d]}}Ge.extendSubschemaData=r;function o(s,{jtdDiscriminator:i,jtdMetadata:a,compositeRule:c,createErrors:u,allErrors:l}){c!==void 0&&(s.compositeRule=c),u!==void 0&&(s.createErrors=u),l!==void 0&&(s.allErrors=l),s.jtdDiscriminator=i,s.jtdMetadata=a}return Ge.extendSubschemaMode=o,Ge}var he={},ml=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t=="object"&&typeof n=="object"){if(t.constructor!==n.constructor)return!1;var r,o,s;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!e(t[o],n[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(s=Object.keys(t),r=s.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[o]))return!1;for(o=r;o--!==0;){var i=s[o];if(!e(t[i],n[i]))return!1}return!0}return t!==t&&n!==n},gl={exports:{}},st=gl.exports=function(e,t,n){typeof t=="function"&&(n=t,t={}),n=t.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};tr(t,r,o,e,"",e)};st.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};st.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};st.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};st.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 tr(e,t,n,r,o,s,i,a,c,u){if(r&&typeof r=="object"&&!Array.isArray(r)){t(r,o,s,i,a,c,u);for(var l in r){var f=r[l];if(Array.isArray(f)){if(l in st.arrayKeywords)for(var p=0;p<f.length;p++)tr(e,t,n,f[p],o+"/"+l+"/"+p,s,o,l,r,p)}else if(l in st.propsKeywords){if(f&&typeof f=="object")for(var h in f)tr(e,t,n,f[h],o+"/"+l+"/"+gy(h),s,o,l,r,h)}else(l in st.keywords||e.allKeys&&!(l in st.skipKeywords))&&tr(e,t,n,f,o+"/"+l,s,o,l,r)}n(r,o,s,i,a,c,u)}}function gy(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var yy=gl.exports;Object.defineProperty(he,"__esModule",{value:!0});he.getSchemaRefs=he.resolveUrl=he.normalizeId=he._getFullPath=he.getFullPath=he.inlineRef=void 0;const vy=D,$y=ml,wy=yy,by=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Sy(e,t=!0){return typeof e=="boolean"?!0:t===!0?!_o(e):t?yl(e)<=t:!1}he.inlineRef=Sy;const Ey=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function _o(e){for(const t in e){if(Ey.has(t))return!0;const n=e[t];if(Array.isArray(n)&&n.some(_o)||typeof n=="object"&&_o(n))return!0}return!1}function yl(e){let t=0;for(const n in e)if(n==="$ref"||(t++,!by.has(n)&&(typeof e[n]=="object"&&(0,vy.eachItem)(e[n],r=>t+=yl(r)),t===1/0)))return 1/0;return t}function vl(e,t="",n){n!==!1&&(t=zt(t));const r=e.parse(t);return $l(e,r)}he.getFullPath=vl;function $l(e,t){return e.serialize(t).split("#")[0]+"#"}he._getFullPath=$l;const Ny=/#\/?$/;function zt(e){return e?e.replace(Ny,""):""}he.normalizeId=zt;function Oy(e,t,n){return n=zt(n),e.resolve(t,n)}he.resolveUrl=Oy;const _y=/^[a-z_][-a-z0-9._]*$/i;function ky(e,t){if(typeof e=="boolean")return{};const{schemaId:n,uriResolver:r}=this.opts,o=zt(e[n]||t),s={"":o},i=vl(r,o,!1),a={},c=new Set;return wy(e,{allKeys:!0},(f,p,h,d)=>{if(d===void 0)return;const v=i+p;let m=s[d];typeof f[n]=="string"&&(m=g.call(this,f[n])),$.call(this,f.$anchor),$.call(this,f.$dynamicAnchor),s[p]=m;function g(w){const S=this.opts.uriResolver.resolve;if(w=zt(m?S(m,w):w),c.has(w))throw l(w);c.add(w);let N=this.refs[w];return typeof N=="string"&&(N=this.refs[N]),typeof N=="object"?u(f,N.schema,w):w!==zt(v)&&(w[0]==="#"?(u(f,a[w],w),a[w]=f):this.refs[w]=v),w}function $(w){if(typeof w=="string"){if(!_y.test(w))throw new Error(`invalid anchor "${w}"`);g.call(this,`#${w}`)}}}),a;function u(f,p,h){if(p!==void 0&&!$y(f,p))throw l(h)}function l(f){return new Error(`reference "${f}" resolves to more than one schema`)}}he.getSchemaRefs=ky;var Ca;function Er(){if(Ca)return ze;Ca=1,Object.defineProperty(ze,"__esModule",{value:!0}),ze.getData=ze.KeywordCxt=ze.validateFunctionCode=void 0;const e=Yg(),t=ce,n=Ye,r=ce,o=py(),s=hy(),i=my(),a=G,c=Ke,u=he,l=D,f=kn;function p(E){if(N(E)&&(M(E),S(E))){m(E);return}h(E,()=>(0,e.topBoolOrEmptySchema)(E))}ze.validateFunctionCode=p;function h({gen:E,validateName:_,schema:I,schemaEnv:T,opts:U},z){U.code.es5?E.func(_,(0,a._)`${c.default.data}, ${c.default.valCxt}`,T.$async,()=>{E.code((0,a._)`"use strict"; ${$(I,U)}`),v(E,U),E.code(z)}):E.func(_,(0,a._)`${c.default.data}, ${d(U)}`,T.$async,()=>E.code($(I,U)).code(z))}function d(E){return(0,a._)`{${c.default.instancePath}="", ${c.default.parentData}, ${c.default.parentDataProperty}, ${c.default.rootData}=${c.default.data}${E.dynamicRef?(0,a._)`, ${c.default.dynamicAnchors}={}`:a.nil}}={}`}function v(E,_){E.if(c.default.valCxt,()=>{E.var(c.default.instancePath,(0,a._)`${c.default.valCxt}.${c.default.instancePath}`),E.var(c.default.parentData,(0,a._)`${c.default.valCxt}.${c.default.parentData}`),E.var(c.default.parentDataProperty,(0,a._)`${c.default.valCxt}.${c.default.parentDataProperty}`),E.var(c.default.rootData,(0,a._)`${c.default.valCxt}.${c.default.rootData}`),_.dynamicRef&&E.var(c.default.dynamicAnchors,(0,a._)`${c.default.valCxt}.${c.default.dynamicAnchors}`)},()=>{E.var(c.default.instancePath,(0,a._)`""`),E.var(c.default.parentData,(0,a._)`undefined`),E.var(c.default.parentDataProperty,(0,a._)`undefined`),E.var(c.default.rootData,c.default.data),_.dynamicRef&&E.var(c.default.dynamicAnchors,(0,a._)`{}`)})}function m(E){const{schema:_,opts:I,gen:T}=E;h(E,()=>{I.$comment&&_.$comment&&re(E),te(E),T.let(c.default.vErrors,null),T.let(c.default.errors,0),I.unevaluated&&g(E),q(E),se(E)})}function g(E){const{gen:_,validateName:I}=E;E.evaluated=_.const("evaluated",(0,a._)`${I}.evaluated`),_.if((0,a._)`${E.evaluated}.dynamicProps`,()=>_.assign((0,a._)`${E.evaluated}.props`,(0,a._)`undefined`)),_.if((0,a._)`${E.evaluated}.dynamicItems`,()=>_.assign((0,a._)`${E.evaluated}.items`,(0,a._)`undefined`))}function $(E,_){const I=typeof E=="object"&&E[_.schemaId];return I&&(_.code.source||_.code.process)?(0,a._)`/*# sourceURL=${I} */`:a.nil}function w(E,_){if(N(E)&&(M(E),S(E))){x(E,_);return}(0,e.boolOrEmptySchema)(E,_)}function S({schema:E,self:_}){if(typeof E=="boolean")return!E;for(const I in E)if(_.RULES.all[I])return!0;return!1}function N(E){return typeof E.schema!="boolean"}function x(E,_){const{schema:I,gen:T,opts:U}=E;U.$comment&&I.$comment&&re(E),ne(E),le(E);const z=T.const("_errs",c.default.errors);q(E,z),T.var(_,(0,a._)`${z} === ${c.default.errors}`)}function M(E){(0,l.checkUnknownRules)(E),Q(E)}function q(E,_){if(E.opts.jtd)return lt(E,[],!1,_);const I=(0,t.getSchemaTypes)(E.schema),T=(0,t.coerceAndCheckDataType)(E,I);lt(E,I,!T,_)}function Q(E){const{schema:_,errSchemaPath:I,opts:T,self:U}=E;_.$ref&&T.ignoreKeywordsWithRef&&(0,l.schemaHasRulesButRef)(_,U.RULES)&&U.logger.warn(`$ref: keywords ignored in schema at path "${I}"`)}function te(E){const{schema:_,opts:I}=E;_.default!==void 0&&I.useDefaults&&I.strictSchema&&(0,l.checkStrictMode)(E,"default is ignored in the schema root")}function ne(E){const _=E.schema[E.opts.schemaId];_&&(E.baseId=(0,u.resolveUrl)(E.opts.uriResolver,E.baseId,_))}function le(E){if(E.schema.$async&&!E.schemaEnv.$async)throw new Error("async schema in sync schema")}function re({gen:E,schemaEnv:_,schema:I,errSchemaPath:T,opts:U}){const z=I.$comment;if(U.$comment===!0)E.code((0,a._)`${c.default.self}.logger.log(${z})`);else if(typeof U.$comment=="function"){const fe=(0,a.str)`${T}/$comment`,xe=E.scopeValue("root",{ref:_.root});E.code((0,a._)`${c.default.self}.opts.$comment(${z}, ${fe}, ${xe}.schema)`)}}function se(E){const{gen:_,schemaEnv:I,validateName:T,ValidationError:U,opts:z}=E;I.$async?_.if((0,a._)`${c.default.errors} === 0`,()=>_.return(c.default.data),()=>_.throw((0,a._)`new ${U}(${c.default.vErrors})`)):(_.assign((0,a._)`${T}.errors`,c.default.vErrors),z.unevaluated&&qe(E),_.return((0,a._)`${c.default.errors} === 0`))}function qe({gen:E,evaluated:_,props:I,items:T}){I instanceof a.Name&&E.assign((0,a._)`${_}.props`,I),T instanceof a.Name&&E.assign((0,a._)`${_}.items`,T)}function lt(E,_,I,T){const{gen:U,schema:z,data:fe,allErrors:xe,opts:$e,self:we}=E,{RULES:de}=we;if(z.$ref&&($e.ignoreKeywordsWithRef||!(0,l.schemaHasRulesButRef)(z,de))){U.block(()=>L(E,"$ref",de.all.$ref.definition));return}$e.jtd||tn(E,_),U.block(()=>{for(const Ae of de.rules)xt(Ae);xt(de.post)});function xt(Ae){(0,n.shouldUseGroup)(z,Ae)&&(Ae.type?(U.if((0,r.checkDataType)(Ae.type,fe,$e.strictNumbers)),It(E,Ae),_.length===1&&_[0]===Ae.type&&I&&(U.else(),(0,r.reportTypeError)(E)),U.endIf()):It(E,Ae),xe||U.if((0,a._)`${c.default.errors} === ${T||0}`))}}function It(E,_){const{gen:I,schema:T,opts:{useDefaults:U}}=E;U&&(0,o.assignDefaults)(E,_.type),I.block(()=>{for(const z of _.rules)(0,n.shouldUseRule)(T,z)&&L(E,z.keyword,z.definition,_.type)})}function tn(E,_){E.schemaEnv.meta||!E.opts.strictTypes||(Pt(E,_),E.opts.allowUnionTypes||C(E,_),O(E,E.dataTypes))}function Pt(E,_){if(_.length){if(!E.dataTypes.length){E.dataTypes=_;return}_.forEach(I=>{k(E.dataTypes,I)||b(E,`type "${I}" not allowed by context "${E.dataTypes.join(",")}"`)}),y(E,_)}}function C(E,_){_.length>1&&!(_.length===2&&_.includes("null"))&&b(E,"use allowUnionTypes to allow union type keyword")}function O(E,_){const I=E.self.RULES.all;for(const T in I){const U=I[T];if(typeof U=="object"&&(0,n.shouldUseRule)(E.schema,U)){const{type:z}=U.definition;z.length&&!z.some(fe=>P(_,fe))&&b(E,`missing type "${z.join(",")}" for keyword "${T}"`)}}}function P(E,_){return E.includes(_)||_==="number"&&E.includes("integer")}function k(E,_){return E.includes(_)||_==="integer"&&E.includes("number")}function y(E,_){const I=[];for(const T of E.dataTypes)k(_,T)?I.push(T):_.includes("integer")&&T==="number"&&I.push("integer");E.dataTypes=I}function b(E,_){const I=E.schemaEnv.baseId+E.errSchemaPath;_+=` at "${I}" (strictTypes)`,(0,l.checkStrictMode)(E,_,E.opts.strictTypes)}class A{constructor(_,I,T){if((0,s.validateKeywordUsage)(_,I,T),this.gen=_.gen,this.allErrors=_.allErrors,this.keyword=T,this.data=_.data,this.schema=_.schema[T],this.$data=I.$data&&_.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,l.schemaRefOrVal)(_,this.schema,T,this.$data),this.schemaType=I.schemaType,this.parentSchema=_.schema,this.params={},this.it=_,this.def=I,this.$data)this.schemaCode=_.gen.const("vSchema",J(this.$data,_));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,I.schemaType,I.allowUndefined))throw new Error(`${T} value must be ${JSON.stringify(I.schemaType)}`);("code"in I?I.trackErrors:I.errors!==!1)&&(this.errsCount=_.gen.const("_errs",c.default.errors))}result(_,I,T){this.failResult((0,a.not)(_),I,T)}failResult(_,I,T){this.gen.if(_),T?T():this.error(),I?(this.gen.else(),I(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(_,I){this.failResult((0,a.not)(_),void 0,I)}fail(_){if(_===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(_),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(_){if(!this.$data)return this.fail(_);const{schemaCode:I}=this;this.fail((0,a._)`${I} !== undefined && (${(0,a.or)(this.invalid$data(),_)})`)}error(_,I,T){if(I){this.setParams(I),this._error(_,T),this.setParams({});return}this._error(_,T)}_error(_,I){(_?f.reportExtraError:f.reportError)(this,this.def.error,I)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(_){this.allErrors||this.gen.if(_)}setParams(_,I){I?Object.assign(this.params,_):this.params=_}block$data(_,I,T=a.nil){this.gen.block(()=>{this.check$data(_,T),I()})}check$data(_=a.nil,I=a.nil){if(!this.$data)return;const{gen:T,schemaCode:U,schemaType:z,def:fe}=this;T.if((0,a.or)((0,a._)`${U} === undefined`,I)),_!==a.nil&&T.assign(_,!0),(z.length||fe.validateSchema)&&(T.elseIf(this.invalid$data()),this.$dataError(),_!==a.nil&&T.assign(_,!1)),T.else()}invalid$data(){const{gen:_,schemaCode:I,schemaType:T,def:U,it:z}=this;return(0,a.or)(fe(),xe());function fe(){if(T.length){if(!(I instanceof a.Name))throw new Error("ajv implementation error");const $e=Array.isArray(T)?T:[T];return(0,a._)`${(0,r.checkDataTypes)($e,I,z.opts.strictNumbers,r.DataType.Wrong)}`}return a.nil}function xe(){if(U.validateSchema){const $e=_.scopeValue("validate$data",{ref:U.validateSchema});return(0,a._)`!${$e}(${I})`}return a.nil}}subschema(_,I){const T=(0,i.getSubschema)(this.it,_);(0,i.extendSubschemaData)(T,this.it,_),(0,i.extendSubschemaMode)(T,_);const U={...this.it,...T,items:void 0,props:void 0};return w(U,I),U}mergeEvaluated(_,I){const{it:T,gen:U}=this;T.opts.unevaluated&&(T.props!==!0&&_.props!==void 0&&(T.props=l.mergeEvaluated.props(U,_.props,T.props,I)),T.items!==!0&&_.items!==void 0&&(T.items=l.mergeEvaluated.items(U,_.items,T.items,I)))}mergeValidEvaluated(_,I){const{it:T,gen:U}=this;if(T.opts.unevaluated&&(T.props!==!0||T.items!==!0))return U.if(I,()=>this.mergeEvaluated(_,a.Name)),!0}}ze.KeywordCxt=A;function L(E,_,I,T){const U=new A(E,I,_);"code"in I?I.code(U,T):U.$data&&I.validate?(0,s.funcKeywordCode)(U,I):"macro"in I?(0,s.macroKeywordCode)(U,I):(I.compile||I.validate)&&(0,s.funcKeywordCode)(U,I)}const B=/^\/(?:[^~]|~0|~1)*$/,Y=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function J(E,{dataLevel:_,dataNames:I,dataPathArr:T}){let U,z;if(E==="")return c.default.rootData;if(E[0]==="/"){if(!B.test(E))throw new Error(`Invalid JSON-pointer: ${E}`);U=E,z=c.default.rootData}else{const we=Y.exec(E);if(!we)throw new Error(`Invalid JSON-pointer: ${E}`);const de=+we[1];if(U=we[2],U==="#"){if(de>=_)throw new Error($e("property/index",de));return T[_-de]}if(de>_)throw new Error($e("data",de));if(z=I[_-de],!U)return z}let fe=z;const xe=U.split("/");for(const we of xe)we&&(z=(0,a._)`${z}${(0,a.getProperty)((0,l.unescapeJsonPointer)(we))}`,fe=(0,a._)`${fe} && ${z}`);return fe;function $e(we,de){return`Cannot access ${we} ${de} levels up, current level is ${_}`}}return ze.getData=J,ze}var An={};Object.defineProperty(An,"__esModule",{value:!0});let Ay=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};An.default=Ay;var Zt={};Object.defineProperty(Zt,"__esModule",{value:!0});const qr=he;class jy extends Error{constructor(t,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,qr.resolveUrl)(t,n,r),this.missingSchema=(0,qr.normalizeId)((0,qr.getFullPath)(t,this.missingRef))}}Zt.default=jy;var Ne={};Object.defineProperty(Ne,"__esModule",{value:!0});Ne.resolveSchema=Ne.getCompilingSchema=Ne.resolveRef=Ne.compileSchema=Ne.SchemaEnv=void 0;const Ce=G,Iy=An,pt=Ke,Me=he,Ra=D,Py=Er();class Nr{constructor(t){var n;this.refs={},this.dynamicAnchors={};let r;typeof t.schema=="object"&&(r=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(n=t.baseId)!==null&&n!==void 0?n:(0,Me.normalizeId)(r==null?void 0:r[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=r==null?void 0:r.$async,this.refs={}}}Ne.SchemaEnv=Nr;function Es(e){const t=wl.call(this,e);if(t)return t;const n=(0,Me.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Ce.CodeGen(this.scope,{es5:r,lines:o,ownProperties:s});let a;e.$async&&(a=i.scopeValue("Error",{ref:Iy.default,code:(0,Ce._)`require("ajv/dist/runtime/validation_error").default`}));const c=i.scopeName("validate");e.validateName=c;const u={gen:i,allErrors:this.opts.allErrors,data:pt.default.data,parentData:pt.default.parentData,parentDataProperty:pt.default.parentDataProperty,dataNames:[pt.default.data],dataPathArr:[Ce.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Ce.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:n,baseId:e.baseId||n,schemaPath:Ce.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ce._)`""`,opts:this.opts,self:this};let l;try{this._compilations.add(e),(0,Py.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);const f=i.toString();l=`${i.scopeRefs(pt.default.scope)}return ${f}`,this.opts.code.process&&(l=this.opts.code.process(l,e));const p=new Function(`${pt.default.self}`,`${pt.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=e.schema,p.schemaEnv=e,e.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:f,scopeValues:i._values}),this.opts.unevaluated){const{props:h,items:d}=u;p.evaluated={props:h instanceof Ce.Name?void 0:h,items:d instanceof Ce.Name?void 0:d,dynamicProps:h instanceof Ce.Name,dynamicItems:d instanceof Ce.Name},p.source&&(p.source.evaluated=(0,Ce.stringify)(p.evaluated))}return e.validate=p,e}catch(f){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),f}finally{this._compilations.delete(e)}}Ne.compileSchema=Es;function xy(e,t,n){var r;n=(0,Me.resolveUrl)(this.opts.uriResolver,t,n);const o=e.refs[n];if(o)return o;let s=Ry.call(this,e,n);if(s===void 0){const i=(r=e.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;i&&(s=new Nr({schema:i,schemaId:a,root:e,baseId:t}))}if(s!==void 0)return e.refs[n]=Ty.call(this,s)}Ne.resolveRef=xy;function Ty(e){return(0,Me.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Es.call(this,e)}function wl(e){for(const t of this._compilations)if(Cy(t,e))return t}Ne.getCompilingSchema=wl;function Cy(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function Ry(e,t){let n;for(;typeof(n=this.refs[t])=="string";)t=n;return n||this.schemas[t]||Or.call(this,e,t)}function Or(e,t){const n=this.opts.uriResolver.parse(t),r=(0,Me._getFullPath)(this.opts.uriResolver,n);let o=(0,Me.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===o)return zr.call(this,n,e);const s=(0,Me.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){const a=Or.call(this,e,i);return typeof(a==null?void 0:a.schema)!="object"?void 0:zr.call(this,n,a)}if(typeof(i==null?void 0:i.schema)=="object"){if(i.validate||Es.call(this,i),s===(0,Me.normalizeId)(t)){const{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Me.resolveUrl)(this.opts.uriResolver,o,u)),new Nr({schema:a,schemaId:c,root:e,baseId:o})}return zr.call(this,n,i)}}Ne.resolveSchema=Or;const My=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function zr(e,{baseId:t,schema:n,root:r}){var o;if(((o=e.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(const a of e.fragment.slice(1).split("/")){if(typeof n=="boolean")return;const c=n[(0,Ra.unescapeFragment)(a)];if(c===void 0)return;n=c;const u=typeof n=="object"&&n[this.opts.schemaId];!My.has(a)&&u&&(t=(0,Me.resolveUrl)(this.opts.uriResolver,t,u))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,Ra.schemaHasRulesButRef)(n,this.RULES)){const a=(0,Me.resolveUrl)(this.opts.uriResolver,t,n.$ref);s=Or.call(this,r,a)}const{schemaId:i}=this.opts;if(s=s||new Nr({schema:n,schemaId:i,root:r,baseId:t}),s.schema!==s.root.schema)return s}const Dy="https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",Ly="Meta-schema for $data reference (JSON AnySchema extension proposal)",Uy="object",By=["$data"],Fy={$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},Vy=!1,Ky={$id:Dy,description:Ly,type:Uy,required:By,properties:Fy,additionalProperties:Vy};var Ns={},_r={exports:{}};const qy=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),bl=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),Os=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Sl=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),zy=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function El(e){let t="",n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[r]}return t}const Gy=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Ma(e){return e.length=0,!0}function Hy(e,t,n){if(e.length){const r=El(e);if(r!=="")t.push(r);else return n.error=!0,!1;e.length=0}return!0}function Jy(e){let t=0;const n={error:!1,address:"",zone:""},r=[],o=[];let s=!1,i=!1,a=Hy;for(let c=0;c<e.length;c++){const u=e[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,r,n))break;if(++t>7){n.error=!0;break}c>0&&e[c-1]===":"&&(s=!0),r.push(":");continue}else if(u==="%"){if(!a(o,r,n))break;a=Ma}else{o.push(u);continue}}return o.length&&(a===Ma?n.zone=o.join(""):i?r.push(o.join("")):r.push(El(o))),n.address=r.join(""),n}function Nl(e){if(Wy(e,":")<2)return{host:e,isIPV6:!1};const t=Jy(e);if(t.error)return{host:e,isIPV6:!1};{let n=t.address,r=t.address;return t.zone&&(n+="%"+t.zone,r+="%25"+t.zone),{host:n,isIPV6:!0,escapedHost:r}}}function Wy(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function Qy(e){let t=e;const n=[];let r=-1,o=0;for(;o=t.length;){if(o===1){if(t===".")break;if(t==="/"){n.push("/");break}else{n.push(t);break}}else if(o===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){n.push("/");break}}else if(o===3&&t==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf("/",1))===-1){n.push(t);break}else n.push(t.slice(0,r)),t=t.slice(r)}return n.join("")}const Yy={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Zy=/[@/?#:]/g,Xy=/[@/?#]/g;function Ol(e,t){const n=t?Xy:Zy;return n.lastIndex=0,e.replace(n,r=>Yy[r])}function ev(e,t=!1){if(e.indexOf("%")===-1)return e;let n="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){const o=e.slice(r+1,r+3);if(Os(o)){const s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));t&&Sl(i)?n+=i:n+="%"+s,r+=2;continue}}n+=e[r]}return n}function tv(e){let t="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){const r=e.slice(n+1,n+3);if(Os(r)){const o=r.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Sl(s)?t+=s:t+="%"+o,n+=2;continue}}zy(e[n])?t+=e[n]:t+=escape(e[n])}return t}function nv(e){let t="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){const r=e.slice(n+1,n+3);if(Os(r)){t+="%"+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function rv(e){const t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let n=unescape(e.host);if(!bl(n)){const r=Nl(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=Ol(n,!1)}t.push(n)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}var _l={nonSimpleDomain:Gy,recomposeAuthority:rv,reescapeHostDelimiters:Ol,normalizePercentEncoding:ev,normalizePathEncoding:tv,escapePreservingEscapes:nv,removeDotSegments:Qy,isIPv4:bl,isUUID:qy,normalizeIPv6:Nl};const{isUUID:ov}=_l,sv=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function kl(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function Al(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function jl(e){const t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function iv(e){return e.secure=kl(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function av(e){if((e.port===(kl(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){const[t,n]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function cv(e,t){if(!e.path)return e.error="URN can not be parsed",e;const n=e.path.match(sv);if(n){const r=t.scheme||e.scheme||"urn";e.nid=n[1].toLowerCase(),e.nss=n[2];const o=`${r}:${t.nid||e.nid}`,s=_s(o);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function uv(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");const n=t.scheme||e.scheme||"urn",r=e.nid.toLowerCase(),o=`${n}:${t.nid||r}`,s=_s(o);s&&(e=s.serialize(e,t));const i=e,a=e.nss;return i.path=`${r||t.nid}:${a}`,t.skipEscape=!0,i}function lv(e,t){const n=e;return n.uuid=n.nss,n.nss=void 0,!t.tolerant&&(!n.uuid||!ov(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function fv(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t}const Il={scheme:"http",domainHost:!0,parse:Al,serialize:jl},dv={scheme:"https",domainHost:Il.domainHost,parse:Al,serialize:jl},nr={scheme:"ws",domainHost:!0,parse:iv,serialize:av},pv={scheme:"wss",domainHost:nr.domainHost,parse:nr.parse,serialize:nr.serialize},hv={scheme:"urn",parse:cv,serialize:uv,skipNormalize:!0},mv={scheme:"urn:uuid",parse:lv,serialize:fv,skipNormalize:!0},ur={http:Il,https:dv,ws:nr,wss:pv,urn:hv,"urn:uuid":mv};Object.setPrototypeOf(ur,null);function _s(e){return e&&(ur[e]||ur[e.toLowerCase()])||void 0}var gv={SCHEMES:ur,getSchemeHandler:_s};const{normalizeIPv6:yv,removeDotSegments:ln,recomposeAuthority:vv,normalizePercentEncoding:$v,normalizePathEncoding:wv,escapePreservingEscapes:bv,reescapeHostDelimiters:Sv,isIPv4:Ev,nonSimpleDomain:Nv}=_l,{SCHEMES:Ov,getSchemeHandler:Pl}=gv;function _v(e,t){return typeof e=="string"?e=Pv(e,t):typeof e=="object"&&(e=Jt(At(e,t),t)),e}function kv(e,t,n){const r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=xl(Jt(e,r),Jt(t,r),r,!0);return r.skipEscape=!0,At(o,r)}function xl(e,t,n,r){const o={};return r||(e=Jt(At(e,n),n),t=Jt(At(t,n),n)),n=n||{},!n.tolerant&&t.scheme?(o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=ln(t.path||""),o.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=ln(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=ln(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?o.path="/"+t.path:e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path,o.path=ln(o.path)),o.query=t.query):(o.path=e.path,t.query!==void 0?o.query=t.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=t.fragment,o}function Av(e,t,n){const r=Da(e,n),o=Da(t,n);return r!==void 0&&o!==void 0&&r.toLowerCase()===o.toLowerCase()}function At(e,t){const n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},r=Object.assign({},t),o=[],s=Pl(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=$v(n.path):(n.path=bv(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");const i=vv(n);if(i!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(i),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!s||!s.absolutePath)&&(a=ln(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return n.query!==void 0&&o.push("?",n.query),n.fragment!==void 0&&o.push("#",n.fragment),o.join("")}const jv=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Iv(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port=="number"&&(e.port<0||e.port>65535))return"URI port is malformed."}function Tl(e,t){const n=Object.assign({},t),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let o=!1,s=!1;n.reference==="suffix"&&(n.scheme?e=n.scheme+":"+e:e="//"+e);const i=e.match(jv);if(i){r.scheme=i[1],r.userinfo=i[3],r.host=i[4],r.port=parseInt(i[5],10),r.path=i[6]||"",r.query=i[7],r.fragment=i[8],isNaN(r.port)&&(r.port=i[5]);const a=Iv(r,i);if(a!==void 0&&(r.error=r.error||a,o=!0),r.host)if(Ev(r.host)===!1){const u=yv(r.host);r.host=u.host.toLowerCase(),s=u.isIPV6}else s=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");const c=Pl(n.scheme||r.scheme);if(!n.unicodeSupport&&(!c||!c.unicodeSupport)&&r.host&&(n.domainHost||c&&c.domainHost)&&s===!1&&Nv(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(u){r.error=r.error||"Host's domain name can not be converted to ASCII: "+u}if((!c||c&&!c.skipNormalize)&&(e.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=Sv(unescape(r.host),s))),r.path&&(r.path=wv(r.path)),r.fragment))try{r.fragment=encodeURI(decodeURIComponent(r.fragment))}catch{r.error=r.error||"URI malformed"}c&&c.parse&&c.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return{parsed:r,malformedAuthorityOrPort:o}}function Jt(e,t){return Tl(e,t).parsed}function Pv(e,t){return Cl(e,t).normalized}function Cl(e,t){const{parsed:n,malformedAuthorityOrPort:r}=Tl(e,t);return{normalized:r?e:At(n,t),malformedAuthorityOrPort:r}}function Da(e,t){if(typeof e=="string"){const{normalized:n,malformedAuthorityOrPort:r}=Cl(e,t);return r?void 0:n}if(typeof e=="object")return At(e,t)}const ks={SCHEMES:Ov,normalize:_v,resolve:kv,resolveComponent:xl,equal:Av,serialize:At,parse:Jt};_r.exports=ks;_r.exports.default=ks;_r.exports.fastUri=ks;var xv=_r.exports;Object.defineProperty(Ns,"__esModule",{value:!0});const Rl=xv;Rl.code='require("ajv/dist/runtime/uri").default';Ns.default=Rl;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Er();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=G;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});const r=An,o=Zt,s=kt,i=Ne,a=G,c=he,u=ce,l=D,f=Ky,p=Ns,h=(C,O)=>new RegExp(C,O);h.code="new RegExp";const d=["removeAdditional","useDefaults","coerceTypes"],v=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),m={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."},g={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},$=200;function w(C){var O,P,k,y,b,A,L,B,Y,J,E,_,I,T,U,z,fe,xe,$e,we,de,xt,Ae,Cr,Rr;const nn=C.strict,Mr=(O=C.code)===null||O===void 0?void 0:O.optimize,xi=Mr===!0||Mr===void 0?1:Mr||0,Ti=(k=(P=C.code)===null||P===void 0?void 0:P.regExp)!==null&&k!==void 0?k:h,Td=(y=C.uriResolver)!==null&&y!==void 0?y:p.default;return{strictSchema:(A=(b=C.strictSchema)!==null&&b!==void 0?b:nn)!==null&&A!==void 0?A:!0,strictNumbers:(B=(L=C.strictNumbers)!==null&&L!==void 0?L:nn)!==null&&B!==void 0?B:!0,strictTypes:(J=(Y=C.strictTypes)!==null&&Y!==void 0?Y:nn)!==null&&J!==void 0?J:"log",strictTuples:(_=(E=C.strictTuples)!==null&&E!==void 0?E:nn)!==null&&_!==void 0?_:"log",strictRequired:(T=(I=C.strictRequired)!==null&&I!==void 0?I:nn)!==null&&T!==void 0?T:!1,code:C.code?{...C.code,optimize:xi,regExp:Ti}:{optimize:xi,regExp:Ti},loopRequired:(U=C.loopRequired)!==null&&U!==void 0?U:$,loopEnum:(z=C.loopEnum)!==null&&z!==void 0?z:$,meta:(fe=C.meta)!==null&&fe!==void 0?fe:!0,messages:(xe=C.messages)!==null&&xe!==void 0?xe:!0,inlineRefs:($e=C.inlineRefs)!==null&&$e!==void 0?$e:!0,schemaId:(we=C.schemaId)!==null&&we!==void 0?we:"$id",addUsedSchema:(de=C.addUsedSchema)!==null&&de!==void 0?de:!0,validateSchema:(xt=C.validateSchema)!==null&&xt!==void 0?xt:!0,validateFormats:(Ae=C.validateFormats)!==null&&Ae!==void 0?Ae:!0,unicodeRegExp:(Cr=C.unicodeRegExp)!==null&&Cr!==void 0?Cr:!0,int32range:(Rr=C.int32range)!==null&&Rr!==void 0?Rr:!0,uriResolver:Td}}class S{constructor(O={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,O=this.opts={...O,...w(O)};const{es5:P,lines:k}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:v,es5:P,lines:k}),this.logger=le(O.logger);const y=O.validateFormats;O.validateFormats=!1,this.RULES=(0,s.getRules)(),N.call(this,m,O,"NOT SUPPORTED"),N.call(this,g,O,"DEPRECATED","warn"),this._metaOpts=te.call(this),O.formats&&q.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),O.keywords&&Q.call(this,O.keywords),typeof O.meta=="object"&&this.addMetaSchema(O.meta),M.call(this),O.validateFormats=y}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:O,meta:P,schemaId:k}=this.opts;let y=f;k==="id"&&(y={...f},y.id=y.$id,delete y.$id),P&&O&&this.addMetaSchema(y,y[k],!1)}defaultMeta(){const{meta:O,schemaId:P}=this.opts;return this.opts.defaultMeta=typeof O=="object"?O[P]||O:void 0}validate(O,P){let k;if(typeof O=="string"){if(k=this.getSchema(O),!k)throw new Error(`no schema with key or ref "${O}"`)}else k=this.compile(O);const y=k(P);return"$async"in k||(this.errors=k.errors),y}compile(O,P){const k=this._addSchema(O,P);return k.validate||this._compileSchemaEnv(k)}compileAsync(O,P){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:k}=this.opts;return y.call(this,O,P);async function y(J,E){await b.call(this,J.$schema);const _=this._addSchema(J,E);return _.validate||A.call(this,_)}async function b(J){J&&!this.getSchema(J)&&await y.call(this,{$ref:J},!0)}async function A(J){try{return this._compileSchemaEnv(J)}catch(E){if(!(E instanceof o.default))throw E;return L.call(this,E),await B.call(this,E.missingSchema),A.call(this,J)}}function L({missingSchema:J,missingRef:E}){if(this.refs[J])throw new Error(`AnySchema ${J} is loaded but ${E} cannot be resolved`)}async function B(J){const E=await Y.call(this,J);this.refs[J]||await b.call(this,E.$schema),this.refs[J]||this.addSchema(E,J,P)}async function Y(J){const E=this._loading[J];if(E)return E;try{return await(this._loading[J]=k(J))}finally{delete this._loading[J]}}}addSchema(O,P,k,y=this.opts.validateSchema){if(Array.isArray(O)){for(const A of O)this.addSchema(A,void 0,k,y);return this}let b;if(typeof O=="object"){const{schemaId:A}=this.opts;if(b=O[A],b!==void 0&&typeof b!="string")throw new Error(`schema ${A} must be string`)}return P=(0,c.normalizeId)(P||b),this._checkUnique(P),this.schemas[P]=this._addSchema(O,k,P,y,!0),this}addMetaSchema(O,P,k=this.opts.validateSchema){return this.addSchema(O,P,!0,k),this}validateSchema(O,P){if(typeof O=="boolean")return!0;let k;if(k=O.$schema,k!==void 0&&typeof k!="string")throw new Error("$schema must be a string");if(k=k||this.opts.defaultMeta||this.defaultMeta(),!k)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const y=this.validate(k,O);if(!y&&P){const b="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(b);else throw new Error(b)}return y}getSchema(O){let P;for(;typeof(P=x.call(this,O))=="string";)O=P;if(P===void 0){const{schemaId:k}=this.opts,y=new i.SchemaEnv({schema:{},schemaId:k});if(P=i.resolveSchema.call(this,y,O),!P)return;this.refs[O]=P}return P.validate||this._compileSchemaEnv(P)}removeSchema(O){if(O instanceof RegExp)return this._removeAllSchemas(this.schemas,O),this._removeAllSchemas(this.refs,O),this;switch(typeof O){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const P=x.call(this,O);return typeof P=="object"&&this._cache.delete(P.schema),delete this.schemas[O],delete this.refs[O],this}case"object":{const P=O;this._cache.delete(P);let k=O[this.opts.schemaId];return k&&(k=(0,c.normalizeId)(k),delete this.schemas[k],delete this.refs[k]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(O){for(const P of O)this.addKeyword(P);return this}addKeyword(O,P){let k;if(typeof O=="string")k=O,typeof P=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),P.keyword=k);else if(typeof O=="object"&&P===void 0){if(P=O,k=P.keyword,Array.isArray(k)&&!k.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(se.call(this,k,P),!P)return(0,l.eachItem)(k,b=>qe.call(this,b)),this;It.call(this,P);const y={...P,type:(0,u.getJSONTypes)(P.type),schemaType:(0,u.getJSONTypes)(P.schemaType)};return(0,l.eachItem)(k,y.type.length===0?b=>qe.call(this,b,y):b=>y.type.forEach(A=>qe.call(this,b,y,A))),this}getKeyword(O){const P=this.RULES.all[O];return typeof P=="object"?P.definition:!!P}removeKeyword(O){const{RULES:P}=this;delete P.keywords[O],delete P.all[O];for(const k of P.rules){const y=k.rules.findIndex(b=>b.keyword===O);y>=0&&k.rules.splice(y,1)}return this}addFormat(O,P){return typeof P=="string"&&(P=new RegExp(P)),this.formats[O]=P,this}errorsText(O=this.errors,{separator:P=", ",dataVar:k="data"}={}){return!O||O.length===0?"No errors":O.map(y=>`${k}${y.instancePath} ${y.message}`).reduce((y,b)=>y+P+b)}$dataMetaSchema(O,P){const k=this.RULES.all;O=JSON.parse(JSON.stringify(O));for(const y of P){const b=y.split("/").slice(1);let A=O;for(const L of b)A=A[L];for(const L in k){const B=k[L];if(typeof B!="object")continue;const{$data:Y}=B.definition,J=A[L];Y&&J&&(A[L]=Pt(J))}}return O}_removeAllSchemas(O,P){for(const k in O){const y=O[k];(!P||P.test(k))&&(typeof y=="string"?delete O[k]:y&&!y.meta&&(this._cache.delete(y.schema),delete O[k]))}}_addSchema(O,P,k,y=this.opts.validateSchema,b=this.opts.addUsedSchema){let A;const{schemaId:L}=this.opts;if(typeof O=="object")A=O[L];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof O!="boolean")throw new Error("schema must be object or boolean")}let B=this._cache.get(O);if(B!==void 0)return B;k=(0,c.normalizeId)(A||k);const Y=c.getSchemaRefs.call(this,O,k);return B=new i.SchemaEnv({schema:O,schemaId:L,meta:P,baseId:k,localRefs:Y}),this._cache.set(B.schema,B),b&&!k.startsWith("#")&&(k&&this._checkUnique(k),this.refs[k]=B),y&&this.validateSchema(O,!0),B}_checkUnique(O){if(this.schemas[O]||this.refs[O])throw new Error(`schema with key or id "${O}" already exists`)}_compileSchemaEnv(O){if(O.meta?this._compileMetaSchema(O):i.compileSchema.call(this,O),!O.validate)throw new Error("ajv implementation error");return O.validate}_compileMetaSchema(O){const P=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,O)}finally{this.opts=P}}}S.ValidationError=r.default,S.MissingRefError=o.default,e.default=S;function N(C,O,P,k="error"){for(const y in C){const b=y;b in O&&this.logger[k](`${P}: option ${y}. ${C[b]}`)}}function x(C){return C=(0,c.normalizeId)(C),this.schemas[C]||this.refs[C]}function M(){const C=this.opts.schemas;if(C)if(Array.isArray(C))this.addSchema(C);else for(const O in C)this.addSchema(C[O],O)}function q(){for(const C in this.opts.formats){const O=this.opts.formats[C];O&&this.addFormat(C,O)}}function Q(C){if(Array.isArray(C)){this.addVocabulary(C);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const O in C){const P=C[O];P.keyword||(P.keyword=O),this.addKeyword(P)}}function te(){const C={...this.opts};for(const O of d)delete C[O];return C}const ne={log(){},warn(){},error(){}};function le(C){if(C===!1)return ne;if(C===void 0)return console;if(C.log&&C.warn&&C.error)return C;throw new Error("logger must implement log, warn and error methods")}const re=/^[a-z_$][a-z0-9_$:-]*$/i;function se(C,O){const{RULES:P}=this;if((0,l.eachItem)(C,k=>{if(P.keywords[k])throw new Error(`Keyword ${k} is already defined`);if(!re.test(k))throw new Error(`Keyword ${k} has invalid name`)}),!!O&&O.$data&&!("code"in O||"validate"in O))throw new Error('$data keyword must have "code" or "validate" function')}function qe(C,O,P){var k;const y=O==null?void 0:O.post;if(P&&y)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:b}=this;let A=y?b.post:b.rules.find(({type:B})=>B===P);if(A||(A={type:P,rules:[]},b.rules.push(A)),b.keywords[C]=!0,!O)return;const L={keyword:C,definition:{...O,type:(0,u.getJSONTypes)(O.type),schemaType:(0,u.getJSONTypes)(O.schemaType)}};O.before?lt.call(this,A,L,O.before):A.rules.push(L),b.all[C]=L,(k=O.implements)===null||k===void 0||k.forEach(B=>this.addKeyword(B))}function lt(C,O,P){const k=C.rules.findIndex(y=>y.keyword===P);k>=0?C.rules.splice(k,0,O):(C.rules.push(O),this.logger.warn(`rule ${P} is not defined`))}function It(C){let{metaSchema:O}=C;O!==void 0&&(C.$data&&this.opts.$data&&(O=Pt(O)),C.validateSchema=this.compile(O,!0))}const tn={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Pt(C){return{anyOf:[C,tn]}}})(ol);var As={},js={},Is={};Object.defineProperty(Is,"__esModule",{value:!0});const Tv={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Is.default=Tv;var jt={};Object.defineProperty(jt,"__esModule",{value:!0});jt.callRef=jt.getValidate=void 0;const Cv=Zt,La=Ue(),be=G,Ct=Ke,Ua=Ne,Un=D,Rv={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:n,it:r}=e,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=r,{root:u}=s;if((n==="#"||n==="#/")&&o===u.baseId)return f();const l=Ua.resolveRef.call(c,u,o,n);if(l===void 0)throw new Cv.default(r.opts.uriResolver,o,n);if(l instanceof Ua.SchemaEnv)return p(l);return h(l);function f(){if(s===u)return rr(e,i,s,s.$async);const d=t.scopeValue("root",{ref:u});return rr(e,(0,be._)`${d}.validate`,u,u.$async)}function p(d){const v=Ml(e,d);rr(e,v,d,d.$async)}function h(d){const v=t.scopeValue("schema",a.code.source===!0?{ref:d,code:(0,be.stringify)(d)}:{ref:d}),m=t.name("valid"),g=e.subschema({schema:d,dataTypes:[],schemaPath:be.nil,topSchemaRef:v,errSchemaPath:n},m);e.mergeEvaluated(g),e.ok(m)}}};function Ml(e,t){const{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):(0,be._)`${n.scopeValue("wrapper",{ref:t})}.validate`}jt.getValidate=Ml;function rr(e,t,n,r){const{gen:o,it:s}=e,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Ct.default.this:be.nil;r?l():f();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");const d=o.let("valid");o.try(()=>{o.code((0,be._)`await ${(0,La.callValidateCode)(e,t,u)}`),h(t),i||o.assign(d,!0)},v=>{o.if((0,be._)`!(${v} instanceof ${s.ValidationError})`,()=>o.throw(v)),p(v),i||o.assign(d,!1)}),e.ok(d)}function f(){e.result((0,La.callValidateCode)(e,t,u),()=>h(t),()=>p(t))}function p(d){const v=(0,be._)`${d}.errors`;o.assign(Ct.default.vErrors,(0,be._)`${Ct.default.vErrors} === null ? ${v} : ${Ct.default.vErrors}.concat(${v})`),o.assign(Ct.default.errors,(0,be._)`${Ct.default.vErrors}.length`)}function h(d){var v;if(!s.opts.unevaluated)return;const m=(v=n==null?void 0:n.validate)===null||v===void 0?void 0:v.evaluated;if(s.props!==!0)if(m&&!m.dynamicProps)m.props!==void 0&&(s.props=Un.mergeEvaluated.props(o,m.props,s.props));else{const g=o.var("props",(0,be._)`${d}.evaluated.props`);s.props=Un.mergeEvaluated.props(o,g,s.props,be.Name)}if(s.items!==!0)if(m&&!m.dynamicItems)m.items!==void 0&&(s.items=Un.mergeEvaluated.items(o,m.items,s.items));else{const g=o.var("items",(0,be._)`${d}.evaluated.items`);s.items=Un.mergeEvaluated.items(o,g,s.items,be.Name)}}}jt.callRef=rr;jt.default=Rv;Object.defineProperty(js,"__esModule",{value:!0});const Mv=Is,Dv=jt,Lv=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Mv.default,Dv.default];js.default=Lv;var Ps={},xs={};Object.defineProperty(xs,"__esModule",{value:!0});const lr=G,nt=lr.operators,fr={maximum:{okStr:"<=",ok:nt.LTE,fail:nt.GT},minimum:{okStr:">=",ok:nt.GTE,fail:nt.LT},exclusiveMaximum:{okStr:"<",ok:nt.LT,fail:nt.GTE},exclusiveMinimum:{okStr:">",ok:nt.GT,fail:nt.LTE}},Uv={message:({keyword:e,schemaCode:t})=>(0,lr.str)`must be ${fr[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,lr._)`{comparison: ${fr[e].okStr}, limit: ${t}}`},Bv={keyword:Object.keys(fr),type:"number",schemaType:"number",$data:!0,error:Uv,code(e){const{keyword:t,data:n,schemaCode:r}=e;e.fail$data((0,lr._)`${n} ${fr[t].fail} ${r} || isNaN(${n})`)}};xs.default=Bv;var Ts={};Object.defineProperty(Ts,"__esModule",{value:!0});const hn=G,Fv={message:({schemaCode:e})=>(0,hn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,hn._)`{multipleOf: ${e}}`},Vv={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Fv,code(e){const{gen:t,data:n,schemaCode:r,it:o}=e,s=o.opts.multipleOfPrecision,i=t.let("res"),a=s?(0,hn._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,hn._)`${i} !== parseInt(${i})`;e.fail$data((0,hn._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};Ts.default=Vv;var Cs={},Rs={};Object.defineProperty(Rs,"__esModule",{value:!0});function Dl(e){const t=e.length;let n=0,r=0,o;for(;r<t;)n++,o=e.charCodeAt(r++),o>=55296&&o<=56319&&r<t&&(o=e.charCodeAt(r),(o&64512)===56320&&r++);return n}Rs.default=Dl;Dl.code='require("ajv/dist/runtime/ucs2length").default';Object.defineProperty(Cs,"__esModule",{value:!0});const vt=G,Kv=D,qv=Rs,zv={message({keyword:e,schemaCode:t}){const n=e==="maxLength"?"more":"fewer";return(0,vt.str)`must NOT have ${n} than ${t} characters`},params:({schemaCode:e})=>(0,vt._)`{limit: ${e}}`},Gv={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:zv,code(e){const{keyword:t,data:n,schemaCode:r,it:o}=e,s=t==="maxLength"?vt.operators.GT:vt.operators.LT,i=o.opts.unicode===!1?(0,vt._)`${n}.length`:(0,vt._)`${(0,Kv.useFunc)(e.gen,qv.default)}(${n})`;e.fail$data((0,vt._)`${i} ${s} ${r}`)}};Cs.default=Gv;var Ms={};Object.defineProperty(Ms,"__esModule",{value:!0});const Hv=Ue(),Jv=D,Kt=G,Wv={message:({schemaCode:e})=>(0,Kt.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,Kt._)`{pattern: ${e}}`},Qv={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Wv,code(e){const{gen:t,data:n,$data:r,schema:o,schemaCode:s,it:i}=e,a=i.opts.unicodeRegExp?"u":"";if(r){const{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,Kt._)`new RegExp`:(0,Jv.useFunc)(t,c),l=t.let("valid");t.try(()=>t.assign(l,(0,Kt._)`${u}(${s}, ${a}).test(${n})`),()=>t.assign(l,!1)),e.fail$data((0,Kt._)`!${l}`)}else{const c=(0,Hv.usePattern)(e,o);e.fail$data((0,Kt._)`!${c}.test(${n})`)}}};Ms.default=Qv;var Ds={};Object.defineProperty(Ds,"__esModule",{value:!0});const mn=G,Yv={message({keyword:e,schemaCode:t}){const n=e==="maxProperties"?"more":"fewer";return(0,mn.str)`must NOT have ${n} than ${t} properties`},params:({schemaCode:e})=>(0,mn._)`{limit: ${e}}`},Zv={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Yv,code(e){const{keyword:t,data:n,schemaCode:r}=e,o=t==="maxProperties"?mn.operators.GT:mn.operators.LT;e.fail$data((0,mn._)`Object.keys(${n}).length ${o} ${r}`)}};Ds.default=Zv;var Ls={};Object.defineProperty(Ls,"__esModule",{value:!0});const sn=Ue(),gn=G,Xv=D,e$={message:({params:{missingProperty:e}})=>(0,gn.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,gn._)`{missingProperty: ${e}}`},t$={keyword:"required",type:"object",schemaType:"array",$data:!0,error:e$,code(e){const{gen:t,schema:n,schemaCode:r,data:o,$data:s,it:i}=e,{opts:a}=i;if(!s&&n.length===0)return;const c=n.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){const h=e.parentSchema.properties,{definedProperties:d}=e.it;for(const v of n)if((h==null?void 0:h[v])===void 0&&!d.has(v)){const m=i.schemaEnv.baseId+i.errSchemaPath,g=`required property "${v}" is not defined at "${m}" (strictRequired)`;(0,Xv.checkStrictMode)(i,g,i.opts.strictRequired)}}function u(){if(c||s)e.block$data(gn.nil,f);else for(const h of n)(0,sn.checkReportMissingProp)(e,h)}function l(){const h=t.let("missing");if(c||s){const d=t.let("valid",!0);e.block$data(d,()=>p(h,d)),e.ok(d)}else t.if((0,sn.checkMissingProp)(e,n,h)),(0,sn.reportMissingProp)(e,h),t.else()}function f(){t.forOf("prop",r,h=>{e.setParams({missingProperty:h}),t.if((0,sn.noPropertyInData)(t,o,h,a.ownProperties),()=>e.error())})}function p(h,d){e.setParams({missingProperty:h}),t.forOf(h,r,()=>{t.assign(d,(0,sn.propertyInData)(t,o,h,a.ownProperties)),t.if((0,gn.not)(d),()=>{e.error(),t.break()})},gn.nil)}}};Ls.default=t$;var Us={};Object.defineProperty(Us,"__esModule",{value:!0});const yn=G,n$={message({keyword:e,schemaCode:t}){const n=e==="maxItems"?"more":"fewer";return(0,yn.str)`must NOT have ${n} than ${t} items`},params:({schemaCode:e})=>(0,yn._)`{limit: ${e}}`},r$={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:n$,code(e){const{keyword:t,data:n,schemaCode:r}=e,o=t==="maxItems"?yn.operators.GT:yn.operators.LT;e.fail$data((0,yn._)`${n}.length ${o} ${r}`)}};Us.default=r$;var Bs={},jn={};Object.defineProperty(jn,"__esModule",{value:!0});const Ll=ml;Ll.code='require("ajv/dist/runtime/equal").default';jn.default=Ll;Object.defineProperty(Bs,"__esModule",{value:!0});const Gr=ce,pe=G,o$=D,s$=jn,i$={message:({params:{i:e,j:t}})=>(0,pe.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,pe._)`{i: ${e}, j: ${t}}`},a$={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:i$,code(e){const{gen:t,data:n,$data:r,schema:o,parentSchema:s,schemaCode:i,it:a}=e;if(!r&&!o)return;const c=t.let("valid"),u=s.items?(0,Gr.getSchemaTypes)(s.items):[];e.block$data(c,l,(0,pe._)`${i} === false`),e.ok(c);function l(){const d=t.let("i",(0,pe._)`${n}.length`),v=t.let("j");e.setParams({i:d,j:v}),t.assign(c,!0),t.if((0,pe._)`${d} > 1`,()=>(f()?p:h)(d,v))}function f(){return u.length>0&&!u.some(d=>d==="object"||d==="array")}function p(d,v){const m=t.name("item"),g=(0,Gr.checkDataTypes)(u,m,a.opts.strictNumbers,Gr.DataType.Wrong),$=t.const("indices",(0,pe._)`{}`);t.for((0,pe._)`;${d}--;`,()=>{t.let(m,(0,pe._)`${n}[${d}]`),t.if(g,(0,pe._)`continue`),u.length>1&&t.if((0,pe._)`typeof ${m} == "string"`,(0,pe._)`${m} += "_"`),t.if((0,pe._)`typeof ${$}[${m}] == "number"`,()=>{t.assign(v,(0,pe._)`${$}[${m}]`),e.error(),t.assign(c,!1).break()}).code((0,pe._)`${$}[${m}] = ${d}`)})}function h(d,v){const m=(0,o$.useFunc)(t,s$.default),g=t.name("outer");t.label(g).for((0,pe._)`;${d}--;`,()=>t.for((0,pe._)`${v} = ${d}; ${v}--;`,()=>t.if((0,pe._)`${m}(${n}[${d}], ${n}[${v}])`,()=>{e.error(),t.assign(c,!1).break(g)})))}}};Bs.default=a$;var Fs={};Object.defineProperty(Fs,"__esModule",{value:!0});const ko=G,c$=D,u$=jn,l$={message:"must be equal to constant",params:({schemaCode:e})=>(0,ko._)`{allowedValue: ${e}}`},f$={keyword:"const",$data:!0,error:l$,code(e){const{gen:t,data:n,$data:r,schemaCode:o,schema:s}=e;r||s&&typeof s=="object"?e.fail$data((0,ko._)`!${(0,c$.useFunc)(t,u$.default)}(${n}, ${o})`):e.fail((0,ko._)`${s} !== ${n}`)}};Fs.default=f$;var Vs={};Object.defineProperty(Vs,"__esModule",{value:!0});const fn=G,d$=D,p$=jn,h$={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,fn._)`{allowedValues: ${e}}`},m$={keyword:"enum",schemaType:"array",$data:!0,error:h$,code(e){const{gen:t,data:n,$data:r,schema:o,schemaCode:s,it:i}=e;if(!r&&o.length===0)throw new Error("enum must have non-empty array");const a=o.length>=i.opts.loopEnum;let c;const u=()=>c??(c=(0,d$.useFunc)(t,p$.default));let l;if(a||r)l=t.let("valid"),e.block$data(l,f);else{if(!Array.isArray(o))throw new Error("ajv implementation error");const h=t.const("vSchema",s);l=(0,fn.or)(...o.map((d,v)=>p(h,v)))}e.pass(l);function f(){t.assign(l,!1),t.forOf("v",s,h=>t.if((0,fn._)`${u()}(${n}, ${h})`,()=>t.assign(l,!0).break()))}function p(h,d){const v=o[d];return typeof v=="object"&&v!==null?(0,fn._)`${u()}(${n}, ${h}[${d}])`:(0,fn._)`${n} === ${v}`}}};Vs.default=m$;Object.defineProperty(Ps,"__esModule",{value:!0});const g$=xs,y$=Ts,v$=Cs,$$=Ms,w$=Ds,b$=Ls,S$=Us,E$=Bs,N$=Fs,O$=Vs,_$=[g$.default,y$.default,v$.default,$$.default,w$.default,b$.default,S$.default,E$.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},N$.default,O$.default];Ps.default=_$;var Ks={},Xt={};Object.defineProperty(Xt,"__esModule",{value:!0});Xt.validateAdditionalItems=void 0;const $t=G,Ao=D,k$={message:({params:{len:e}})=>(0,$t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,$t._)`{limit: ${e}}`},A$={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:k$,code(e){const{parentSchema:t,it:n}=e,{items:r}=t;if(!Array.isArray(r)){(0,Ao.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}Ul(e,r)}};function Ul(e,t){const{gen:n,schema:r,data:o,keyword:s,it:i}=e;i.items=!0;const a=n.const("len",(0,$t._)`${o}.length`);if(r===!1)e.setParams({len:t.length}),e.pass((0,$t._)`${a} <= ${t.length}`);else if(typeof r=="object"&&!(0,Ao.alwaysValidSchema)(i,r)){const u=n.var("valid",(0,$t._)`${a} <= ${t.length}`);n.if((0,$t.not)(u),()=>c(u)),e.ok(u)}function c(u){n.forRange("i",t.length,a,l=>{e.subschema({keyword:s,dataProp:l,dataPropType:Ao.Type.Num},u),i.allErrors||n.if((0,$t.not)(u),()=>n.break())})}}Xt.validateAdditionalItems=Ul;Xt.default=A$;var qs={},en={};Object.defineProperty(en,"__esModule",{value:!0});en.validateTuple=void 0;const Ba=G,or=D,j$=Ue(),I$={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:n}=e;if(Array.isArray(t))return Bl(e,"additionalItems",t);n.items=!0,!(0,or.alwaysValidSchema)(n,t)&&e.ok((0,j$.validateArray)(e))}};function Bl(e,t,n=e.schema){const{gen:r,parentSchema:o,data:s,keyword:i,it:a}=e;l(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=or.mergeEvaluated.items(r,n.length,a.items));const c=r.name("valid"),u=r.const("len",(0,Ba._)`${s}.length`);n.forEach((f,p)=>{(0,or.alwaysValidSchema)(a,f)||(r.if((0,Ba._)`${u} > ${p}`,()=>e.subschema({keyword:i,schemaProp:p,dataProp:p},c)),e.ok(c))});function l(f){const{opts:p,errSchemaPath:h}=a,d=n.length,v=d===f.minItems&&(d===f.maxItems||f[t]===!1);if(p.strictTuples&&!v){const m=`"${i}" is ${d}-tuple, but minItems or maxItems/${t} are not specified or different at path "${h}"`;(0,or.checkStrictMode)(a,m,p.strictTuples)}}}en.validateTuple=Bl;en.default=I$;Object.defineProperty(qs,"__esModule",{value:!0});const P$=en,x$={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,P$.validateTuple)(e,"items")};qs.default=x$;var zs={};Object.defineProperty(zs,"__esModule",{value:!0});const Fa=G,T$=D,C$=Ue(),R$=Xt,M$={message:({params:{len:e}})=>(0,Fa.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Fa._)`{limit: ${e}}`},D$={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:M$,code(e){const{schema:t,parentSchema:n,it:r}=e,{prefixItems:o}=n;r.items=!0,!(0,T$.alwaysValidSchema)(r,t)&&(o?(0,R$.validateAdditionalItems)(e,o):e.ok((0,C$.validateArray)(e)))}};zs.default=D$;var Gs={};Object.defineProperty(Gs,"__esModule",{value:!0});const je=G,Bn=D,L$={message:({params:{min:e,max:t}})=>t===void 0?(0,je.str)`must contain at least ${e} valid item(s)`:(0,je.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,je._)`{minContains: ${e}}`:(0,je._)`{minContains: ${e}, maxContains: ${t}}`},U$={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:L$,code(e){const{gen:t,schema:n,parentSchema:r,data:o,it:s}=e;let i,a;const{minContains:c,maxContains:u}=r;s.opts.next?(i=c===void 0?1:c,a=u):i=1;const l=t.const("len",(0,je._)`${o}.length`);if(e.setParams({min:i,max:a}),a===void 0&&i===0){(0,Bn.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Bn.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Bn.alwaysValidSchema)(s,n)){let v=(0,je._)`${l} >= ${i}`;a!==void 0&&(v=(0,je._)`${v} && ${l} <= ${a}`),e.pass(v);return}s.items=!0;const f=t.name("valid");a===void 0&&i===1?h(f,()=>t.if(f,()=>t.break())):i===0?(t.let(f,!0),a!==void 0&&t.if((0,je._)`${o}.length > 0`,p)):(t.let(f,!1),p()),e.result(f,()=>e.reset());function p(){const v=t.name("_valid"),m=t.let("count",0);h(v,()=>t.if(v,()=>d(m)))}function h(v,m){t.forRange("i",0,l,g=>{e.subschema({keyword:"contains",dataProp:g,dataPropType:Bn.Type.Num,compositeRule:!0},v),m()})}function d(v){t.code((0,je._)`${v}++`),a===void 0?t.if((0,je._)`${v} >= ${i}`,()=>t.assign(f,!0).break()):(t.if((0,je._)`${v} > ${a}`,()=>t.assign(f,!1).break()),i===1?t.assign(f,!0):t.if((0,je._)`${v} >= ${i}`,()=>t.assign(f,!0)))}}};Gs.default=U$;var Fl={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=G,n=D,r=Ue();e.error={message:({params:{property:c,depsCount:u,deps:l}})=>{const f=u===1?"property":"properties";return(0,t.str)`must have ${f} ${l} when property ${c} is present`},params:({params:{property:c,depsCount:u,deps:l,missingProperty:f}})=>(0,t._)`{property: ${c},
160
- missingProperty: ${f},
161
- depsCount: ${u},
162
- deps: ${l}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(c){const[u,l]=s(c);i(c,u),a(c,l)}};function s({schema:c}){const u={},l={};for(const f in c){if(f==="__proto__")continue;const p=Array.isArray(c[f])?u:l;p[f]=c[f]}return[u,l]}function i(c,u=c.schema){const{gen:l,data:f,it:p}=c;if(Object.keys(u).length===0)return;const h=l.let("missing");for(const d in u){const v=u[d];if(v.length===0)continue;const m=(0,r.propertyInData)(l,f,d,p.opts.ownProperties);c.setParams({property:d,depsCount:v.length,deps:v.join(", ")}),p.allErrors?l.if(m,()=>{for(const g of v)(0,r.checkReportMissingProp)(c,g)}):(l.if((0,t._)`${m} && (${(0,r.checkMissingProp)(c,v,h)})`),(0,r.reportMissingProp)(c,h),l.else())}}e.validatePropertyDeps=i;function a(c,u=c.schema){const{gen:l,data:f,keyword:p,it:h}=c,d=l.name("valid");for(const v in u)(0,n.alwaysValidSchema)(h,u[v])||(l.if((0,r.propertyInData)(l,f,v,h.opts.ownProperties),()=>{const m=c.subschema({keyword:p,schemaProp:v},d);c.mergeValidEvaluated(m,d)},()=>l.var(d,!0)),c.ok(d))}e.validateSchemaDeps=a,e.default=o})(Fl);var Hs={};Object.defineProperty(Hs,"__esModule",{value:!0});const Vl=G,B$=D,F$={message:"property name must be valid",params:({params:e})=>(0,Vl._)`{propertyName: ${e.propertyName}}`},V$={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:F$,code(e){const{gen:t,schema:n,data:r,it:o}=e;if((0,B$.alwaysValidSchema)(o,n))return;const s=t.name("valid");t.forIn("key",r,i=>{e.setParams({propertyName:i}),e.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),t.if((0,Vl.not)(s),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(s)}};Hs.default=V$;var kr={};Object.defineProperty(kr,"__esModule",{value:!0});const Fn=Ue(),Re=G,K$=Ke,Vn=D,q$={message:"must NOT have additional properties",params:({params:e})=>(0,Re._)`{additionalProperty: ${e.additionalProperty}}`},z$={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:q$,code(e){const{gen:t,schema:n,parentSchema:r,data:o,errsCount:s,it:i}=e;if(!s)throw new Error("ajv implementation error");const{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Vn.alwaysValidSchema)(i,n))return;const u=(0,Fn.allSchemaProperties)(r.properties),l=(0,Fn.allSchemaProperties)(r.patternProperties);f(),e.ok((0,Re._)`${s} === ${K$.default.errors}`);function f(){t.forIn("key",o,m=>{!u.length&&!l.length?d(m):t.if(p(m),()=>d(m))})}function p(m){let g;if(u.length>8){const $=(0,Vn.schemaRefOrVal)(i,r.properties,"properties");g=(0,Fn.isOwnProperty)(t,$,m)}else u.length?g=(0,Re.or)(...u.map($=>(0,Re._)`${m} === ${$}`)):g=Re.nil;return l.length&&(g=(0,Re.or)(g,...l.map($=>(0,Re._)`${(0,Fn.usePattern)(e,$)}.test(${m})`))),(0,Re.not)(g)}function h(m){t.code((0,Re._)`delete ${o}[${m}]`)}function d(m){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){h(m);return}if(n===!1){e.setParams({additionalProperty:m}),e.error(),a||t.break();return}if(typeof n=="object"&&!(0,Vn.alwaysValidSchema)(i,n)){const g=t.name("valid");c.removeAdditional==="failing"?(v(m,g,!1),t.if((0,Re.not)(g),()=>{e.reset(),h(m)})):(v(m,g),a||t.if((0,Re.not)(g),()=>t.break()))}}function v(m,g,$){const w={keyword:"additionalProperties",dataProp:m,dataPropType:Vn.Type.Str};$===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(w,g)}}};kr.default=z$;var Js={};Object.defineProperty(Js,"__esModule",{value:!0});const G$=Er(),Va=Ue(),Hr=D,Ka=kr,H$={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,parentSchema:r,data:o,it:s}=e;s.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&Ka.default.code(new G$.KeywordCxt(s,Ka.default,"additionalProperties"));const i=(0,Va.allSchemaProperties)(n);for(const f of i)s.definedProperties.add(f);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Hr.mergeEvaluated.props(t,(0,Hr.toHash)(i),s.props));const a=i.filter(f=>!(0,Hr.alwaysValidSchema)(s,n[f]));if(a.length===0)return;const c=t.name("valid");for(const f of a)u(f)?l(f):(t.if((0,Va.propertyInData)(t,o,f,s.opts.ownProperties)),l(f),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(f),e.ok(c);function u(f){return s.opts.useDefaults&&!s.compositeRule&&n[f].default!==void 0}function l(f){e.subschema({keyword:"properties",schemaProp:f,dataProp:f},c)}}};Js.default=H$;var Ws={};Object.defineProperty(Ws,"__esModule",{value:!0});const qa=Ue(),Kn=G,za=D,Ga=D,J$={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,data:r,parentSchema:o,it:s}=e,{opts:i}=s,a=(0,qa.allSchemaProperties)(n),c=a.filter(v=>(0,za.alwaysValidSchema)(s,n[v]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;const u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=t.name("valid");s.props!==!0&&!(s.props instanceof Kn.Name)&&(s.props=(0,Ga.evaluatedPropsToName)(t,s.props));const{props:f}=s;p();function p(){for(const v of a)u&&h(v),s.allErrors?d(v):(t.var(l,!0),d(v),t.if(l))}function h(v){for(const m in u)new RegExp(v).test(m)&&(0,za.checkStrictMode)(s,`property ${m} matches pattern ${v} (use allowMatchingProperties)`)}function d(v){t.forIn("key",r,m=>{t.if((0,Kn._)`${(0,qa.usePattern)(e,v)}.test(${m})`,()=>{const g=c.includes(v);g||e.subschema({keyword:"patternProperties",schemaProp:v,dataProp:m,dataPropType:Ga.Type.Str},l),s.opts.unevaluated&&f!==!0?t.assign((0,Kn._)`${f}[${m}]`,!0):!g&&!s.allErrors&&t.if((0,Kn.not)(l),()=>t.break())})})}}};Ws.default=J$;var Qs={};Object.defineProperty(Qs,"__esModule",{value:!0});const W$=D,Q$={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:n,it:r}=e;if((0,W$.alwaysValidSchema)(r,n)){e.fail();return}const o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Qs.default=Q$;var Ys={};Object.defineProperty(Ys,"__esModule",{value:!0});const Y$=Ue(),Z$={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Y$.validateUnion,error:{message:"must match a schema in anyOf"}};Ys.default=Z$;var Zs={};Object.defineProperty(Zs,"__esModule",{value:!0});const sr=G,X$=D,e0={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,sr._)`{passingSchemas: ${e.passing}}`},t0={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:e0,code(e){const{gen:t,schema:n,parentSchema:r,it:o}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;const s=n,i=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(u),e.result(i,()=>e.reset(),()=>e.error(!0));function u(){s.forEach((l,f)=>{let p;(0,X$.alwaysValidSchema)(o,l)?t.var(c,!0):p=e.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},c),f>0&&t.if((0,sr._)`${c} && ${i}`).assign(i,!1).assign(a,(0,sr._)`[${a}, ${f}]`).else(),t.if(c,()=>{t.assign(i,!0),t.assign(a,f),p&&e.mergeEvaluated(p,sr.Name)})})}}};Zs.default=t0;var Xs={};Object.defineProperty(Xs,"__esModule",{value:!0});const n0=D,r0={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:n,it:r}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");const o=t.name("valid");n.forEach((s,i)=>{if((0,n0.alwaysValidSchema)(r,s))return;const a=e.subschema({keyword:"allOf",schemaProp:i},o);e.ok(o),e.mergeEvaluated(a)})}};Xs.default=r0;var ei={};Object.defineProperty(ei,"__esModule",{value:!0});const dr=G,Kl=D,o0={message:({params:e})=>(0,dr.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,dr._)`{failingKeyword: ${e.ifClause}}`},s0={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:o0,code(e){const{gen:t,parentSchema:n,it:r}=e;n.then===void 0&&n.else===void 0&&(0,Kl.checkStrictMode)(r,'"if" without "then" and "else" is ignored');const o=Ha(r,"then"),s=Ha(r,"else");if(!o&&!s)return;const i=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),o&&s){const l=t.let("ifClause");e.setParams({ifClause:l}),t.if(a,u("then",l),u("else",l))}else o?t.if(a,u("then")):t.if((0,dr.not)(a),u("else"));e.pass(i,()=>e.error(!0));function c(){const l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(l)}function u(l,f){return()=>{const p=e.subschema({keyword:l},a);t.assign(i,a),e.mergeValidEvaluated(p,i),f?t.assign(f,(0,dr._)`${l}`):e.setParams({ifClause:l})}}}};function Ha(e,t){const n=e.schema[t];return n!==void 0&&!(0,Kl.alwaysValidSchema)(e,n)}ei.default=s0;var ti={};Object.defineProperty(ti,"__esModule",{value:!0});const i0=D,a0={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:n}){t.if===void 0&&(0,i0.checkStrictMode)(n,`"${e}" without "if" is ignored`)}};ti.default=a0;Object.defineProperty(Ks,"__esModule",{value:!0});const c0=Xt,u0=qs,l0=en,f0=zs,d0=Gs,p0=Fl,h0=Hs,m0=kr,g0=Js,y0=Ws,v0=Qs,$0=Ys,w0=Zs,b0=Xs,S0=ei,E0=ti;function N0(e=!1){const t=[v0.default,$0.default,w0.default,b0.default,S0.default,E0.default,h0.default,m0.default,p0.default,g0.default,y0.default];return e?t.push(u0.default,f0.default):t.push(c0.default,l0.default),t.push(d0.default),t}Ks.default=N0;var ni={},ri={};Object.defineProperty(ri,"__esModule",{value:!0});const ie=G,O0={message:({schemaCode:e})=>(0,ie.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,ie._)`{format: ${e}}`},_0={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:O0,code(e,t){const{gen:n,data:r,$data:o,schema:s,schemaCode:i,it:a}=e,{opts:c,errSchemaPath:u,schemaEnv:l,self:f}=a;if(!c.validateFormats)return;o?p():h();function p(){const d=n.scopeValue("formats",{ref:f.formats,code:c.code.formats}),v=n.const("fDef",(0,ie._)`${d}[${i}]`),m=n.let("fType"),g=n.let("format");n.if((0,ie._)`typeof ${v} == "object" && !(${v} instanceof RegExp)`,()=>n.assign(m,(0,ie._)`${v}.type || "string"`).assign(g,(0,ie._)`${v}.validate`),()=>n.assign(m,(0,ie._)`"string"`).assign(g,v)),e.fail$data((0,ie.or)($(),w()));function $(){return c.strictSchema===!1?ie.nil:(0,ie._)`${i} && !${g}`}function w(){const S=l.$async?(0,ie._)`(${v}.async ? await ${g}(${r}) : ${g}(${r}))`:(0,ie._)`${g}(${r})`,N=(0,ie._)`(typeof ${g} == "function" ? ${S} : ${g}.test(${r}))`;return(0,ie._)`${g} && ${g} !== true && ${m} === ${t} && !${N}`}}function h(){const d=f.formats[s];if(!d){$();return}if(d===!0)return;const[v,m,g]=w(d);v===t&&e.pass(S());function $(){if(c.strictSchema===!1){f.logger.warn(N());return}throw new Error(N());function N(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function w(N){const x=N instanceof RegExp?(0,ie.regexpCode)(N):c.code.formats?(0,ie._)`${c.code.formats}${(0,ie.getProperty)(s)}`:void 0,M=n.scopeValue("formats",{key:s,ref:N,code:x});return typeof N=="object"&&!(N instanceof RegExp)?[N.type||"string",N.validate,(0,ie._)`${M}.validate`]:["string",N,M]}function S(){if(typeof d=="object"&&!(d instanceof RegExp)&&d.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ie._)`await ${g}(${r})`}return typeof m=="function"?(0,ie._)`${g}(${r})`:(0,ie._)`${g}.test(${r})`}}}};ri.default=_0;Object.defineProperty(ni,"__esModule",{value:!0});const k0=ri,A0=[k0.default];ni.default=A0;var Wt={};Object.defineProperty(Wt,"__esModule",{value:!0});Wt.contentVocabulary=Wt.metadataVocabulary=void 0;Wt.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Wt.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];Object.defineProperty(As,"__esModule",{value:!0});const j0=js,I0=Ps,P0=Ks,x0=ni,Ja=Wt,T0=[j0.default,I0.default,(0,P0.default)(),x0.default,Ja.metadataVocabulary,Ja.contentVocabulary];As.default=T0;var oi={},Ar={};Object.defineProperty(Ar,"__esModule",{value:!0});Ar.DiscrError=void 0;var Wa;(function(e){e.Tag="tag",e.Mapping="mapping"})(Wa||(Ar.DiscrError=Wa={}));Object.defineProperty(oi,"__esModule",{value:!0});const Dt=G,jo=Ar,Qa=Ne,C0=Zt,R0=D,M0={message:({params:{discrError:e,tagName:t}})=>e===jo.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:n}})=>(0,Dt._)`{error: ${e}, tag: ${n}, tagValue: ${t}}`},D0={keyword:"discriminator",type:"object",schemaType:"object",error:M0,code(e){const{gen:t,data:n,schema:r,parentSchema:o,it:s}=e,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");const a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");const c=t.let("valid",!1),u=t.const("tag",(0,Dt._)`${n}${(0,Dt.getProperty)(a)}`);t.if((0,Dt._)`typeof ${u} == "string"`,()=>l(),()=>e.error(!1,{discrError:jo.DiscrError.Tag,tag:u,tagName:a})),e.ok(c);function l(){const h=p();t.if(!1);for(const d in h)t.elseIf((0,Dt._)`${u} === ${d}`),t.assign(c,f(h[d]));t.else(),e.error(!1,{discrError:jo.DiscrError.Mapping,tag:u,tagName:a}),t.endIf()}function f(h){const d=t.name("valid"),v=e.subschema({keyword:"oneOf",schemaProp:h},d);return e.mergeEvaluated(v,Dt.Name),d}function p(){var h;const d={},v=g(o);let m=!0;for(let S=0;S<i.length;S++){let N=i[S];if(N!=null&&N.$ref&&!(0,R0.schemaHasRulesButRef)(N,s.self.RULES)){const M=N.$ref;if(N=Qa.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,M),N instanceof Qa.SchemaEnv&&(N=N.schema),N===void 0)throw new C0.default(s.opts.uriResolver,s.baseId,M)}const x=(h=N==null?void 0:N.properties)===null||h===void 0?void 0:h[a];if(typeof x!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);m=m&&(v||g(N)),$(x,S)}if(!m)throw new Error(`discriminator: "${a}" must be required`);return d;function g({required:S}){return Array.isArray(S)&&S.includes(a)}function $(S,N){if(S.const)w(S.const,N);else if(S.enum)for(const x of S.enum)w(x,N);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function w(S,N){if(typeof S!="string"||S in d)throw new Error(`discriminator: "${a}" values must be unique strings`);d[S]=N}}}};oi.default=D0;const L0="http://json-schema.org/draft-07/schema#",U0="http://json-schema.org/draft-07/schema#",B0="Core schema meta-schema",F0={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:[]}},V0=["object","boolean"],K0={$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:"#"}},q0={$schema:L0,$id:U0,title:B0,definitions:F0,type:V0,properties:K0,default:!0};(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const n=ol,r=As,o=oi,s=q0,i=["/properties"],a="http://json-schema.org/draft-07/schema";class c extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(d=>this.addVocabulary(d)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const d=this.opts.$data?this.$dataMetaSchema(s,i):s;this.addMetaSchema(d,a,!1),this.refs["http://json-schema.org/schema"]=a}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a)?a:void 0)}}t.Ajv=c,e.exports=t=c,e.exports.Ajv=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var u=Er();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=G;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var f=An;Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return f.default}});var p=Zt;Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})(So,So.exports);var z0=So.exports;const G0=am(z0);class ql extends Error{constructor(t){super(t.length>0?`Config validation failed: ${t.map(n=>`${n.field} ${n.message}`).join("; ")}`:"Config validation failed"),this.fieldErrors=t,this.name="ValidationError"}}function H0(e,t){if(!t)return;const n=t,r=n.properties;if(r!==void 0&&Object.keys(r).length===0)return;const o=new G0({allErrors:!0,strict:!1}).compile(n);if(!o(e))throw new ql(J0(o.errors??[]))}function J0(e){return e.map(t=>({field:W0(t),message:t.message??"is invalid",keyword:t.keyword}))}function W0(e){var t;return(e.instancePath??"").replace(/^\//,"").replace(/\//g,".")||(((t=e.params)==null?void 0:t.missingProperty)??"(root)")}function Q0(e,t){return F.join(fu(e,t),vg)}const Y0=384,Z0=448;function X0(e,t,n={}){const r=n.mode??Y0,o=n.dirMode??Z0,s=F.dirname(e);W.mkdirSync(s,{recursive:!0,mode:o}),W.chmodSync(s,o);const i=`${e}.tmp`,a=typeof t=="string"?t:JSON.stringify(t,null,2);try{W.writeFileSync(i,a,{encoding:"utf8",mode:r}),W.chmodSync(i,r),W.renameSync(i,e),W.chmodSync(e,r)}catch(c){try{W.existsSync(i)&&W.unlinkSync(i)}catch{}throw c}}const ew="0.1.0";function Ya(e,t){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a non-empty path segment with no '.', '..', path separators, or NUL: ${JSON.stringify(e)}`)}function tw(){return`${process.pid}-${Kc.randomBytes(3).toString("hex")}`}function zl(e,t,n={}){if(!e)throw new Error("Environment requires a non-empty 'project' name");Ya(e,"project");const r=t.orgNamespace??gg,o=t.envPrefixOverride??Eg(e),s=t.namespaces&&t.namespaces.length>0?t.namespaces:[yg],i=n.namespace??s[0];if(!s.includes(i))throw new Error(`Namespace "${i}" is not declared for project "${e}" (declared: ${s.join(", ")})`);Ya(i,"namespace");const a=n.processEnv??process.env,{scope:c,projectRoot:u}=om({scope:n.scope,cwd:n.cwd},a),l=im({project:e,namespace:i,orgNamespace:r,projectRoot:u,adhdRoot:n.adhdRoot});return{project:e,namespace:i,orgNamespace:r,envPrefix:o,scope:c,projectRoot:u,roots:l}}function nw(e,t,n={}){const{namespace:r,orgNamespace:o,envPrefix:s,scope:i,projectRoot:a,roots:c}=zl(e,t,n),u=n.processEnv??process.env,l=Tg(c),f=n.instanceId??tw(),{raw:p,nested:h,typedRaw:d,provenance:v,fields:m}=Mg(t.config,l,u,{prefix:s,activeScope:i}),g={};for(const N of Object.keys(m)){const x=m[N];x.live&&(g[N]={env:x.env,type:x.type,fallback:x.secret===!0?void 0:x.fallbackValue})}const $=Og(t.config);H0(rl(d),$);const w=Lg(t.dirs,{roots:c,activeScope:i,instanceId:f,projectRoot:a,namespace:r}),S=Ug(t.files,w);return{version:mg,libraryVersion:ew,generatedAt:new Date().toISOString(),project:e,namespace:r,orgNamespace:o,envPrefix:s,scope:i,instanceId:f,config:h,raw:p,liveFields:g,fieldSchema:$,configHash:bg(Object.fromEntries(Object.entries(d).map(([N,x])=>[N,String(x)]))),structureHash:Sg(Object.values(w).map(N=>({name:N.name,kind:N.kind,scope:N.scope}))),dirs:Object.values(w),files:Object.values(S),provenance:v}}let Nn=class extends Error{constructor(t){super(t),this.name="EnvironmentError"}};class rw extends Nn{constructor(t){super(`adhd-environment snapshot not found: ${t}`),this.snapshotPath=t,this.name="SnapshotNotFoundError"}}class ow extends Nn{constructor(t,n){super(`lock "${t}" is already held (${n})`),this.lockName=t,this.lockPath=n,this.name="LockHeldError"}}function sw(e,t){let n=e;for(const r of t.split("."))if(n!==null&&typeof n=="object"&&r in n)n=n[r];else return;return n}function Io(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>Io(n));const t={};for(const[n,r]of Object.entries(e))t[n]=Io(r);return t}function iw(e,t){const n=Io(e);for(const r of Object.keys(t)){const o=t[r],s=r.split(".");let i=n;for(let c=0;c<s.length-1;c++){const u=s[c],l=i[u];(typeof l!="object"||l===null||Array.isArray(l))&&(i[u]={}),i=i[u]}const a=s[s.length-1];Object.defineProperty(i,a,{enumerable:!0,configurable:!0,get(){const c=process.env[o.env];return c!==void 0?bo(c,o.type):o.fallback}})}return n}function aw(e){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw new Nn(`lock name must be a non-empty path segment with no path separators: ${JSON.stringify(e)}`)}class si{constructor(t,n,r={}){let o,s;try{o=nw(t,n,r);const i=zl(t,n,r);s=Q0(i.roots,o.scope)}catch(i){throw i instanceof ql||i instanceof Nn?i:new Nn(i instanceof Error?i.message:String(i))}return Za(this,o,s)}static fromSnapshot(t){if(!W.existsSync(t))throw new rw(t);const n=JSON.parse(W.readFileSync(t,"utf8")),r=Object.create(si.prototype);return Za(r,n,t)}get(t){const n=t.indexOf(".");if(n===-1)return;const r=t.slice(0,n),o=t.slice(n+1);switch(r){case"config":return sw(this.config,o);case"path":return this.paths[o];case"env":return this.resolveEnvName(o);case"provenance":return this._data.provenance[o];default:return}}isEnvNameAllowed(t){return t.startsWith(this.prefix)}resolveEnvName(t){if(this.isEnvNameAllowed(t))return process.env[t]}lock(t="singleton"){aw(t);const n=this.paths.run??this._runDirFallback();W.mkdirSync(n,{recursive:!0});const r=F.join(n,`${t}.lock`);let o;try{o=W.openSync(r,"wx")}catch(i){throw(i==null?void 0:i.code)==="EEXIST"?new ow(t,r):i}W.writeSync(o,`${process.pid}
163
- ${this.instanceId}
164
- `),W.closeSync(o);let s=!1;return()=>{if(!s){s=!0;try{W.unlinkSync(r)}catch{}}}}_runDirFallback(){return F.join(F.dirname(this.snapshotPath),"run")}ensureDirs(){for(const t of Object.values(this.paths))W.mkdirSync(t,{recursive:!0})}write(){return X0(this.snapshotPath,this._data),this.snapshotPath}toJSON(){return Object.freeze(JSON.parse(JSON.stringify(this._data)))}}function Za(e,t,n){const r={};for(const i of t.dirs)r[i.name]=i.path;const o={};for(const i of t.files)o[i.name]=i.path;const s=iw(t.config,t.liveFields??{});return Object.defineProperties(e,{project:{value:t.project,enumerable:!0},namespace:{value:t.namespace,enumerable:!0},orgNamespace:{value:t.orgNamespace,enumerable:!0},scope:{value:t.scope,enumerable:!0},prefix:{value:t.envPrefix,enumerable:!0},instanceId:{value:t.instanceId,enumerable:!0},hash:{value:t.configHash,enumerable:!0},version:{value:{configHash:t.configHash,structureHash:t.structureHash,generatedAt:t.generatedAt,libraryVersion:t.libraryVersion},enumerable:!0},provenance:{value:t.provenance,enumerable:!0},dirs:{value:t.dirs,enumerable:!0},snapshotPath:{value:n,enumerable:!0},config:{value:s,enumerable:!0},paths:{value:r,enumerable:!0},files:{value:o,enumerable:!0},_data:{value:t,enumerable:!1}}),new Proxy(e,{get(i,a,c){return typeof a=="string"&&!(a in i)?i.get(a):Reflect.get(i,a,c)}})}const Gl={envPrefixOverride:"ADHD_BACKLOG",namespaces:["production"],dirs:{data:{kind:"data"}},files:{db:{in:"data",name:"backlog.db"}},config:{"db.path":{type:"string",env:"ADHD_BACKLOG_DATABASE_PATH",description:"SQLite backlog-graph DB path. Unset ⇒ falls back to env.files.db under the resolved scope root."},"db.busyTimeoutMs":{type:"integer",env:"ADHD_BACKLOG_DATABASE_BUSY_TIMEOUT_MS",default:5e3,description:"SQLite `busy_timeout` (ms) each write waits for a contended lock before retrying (DEBT-BACKLOG-CONCURRENCY-BUSY-RETRY-001). Raise this when scaling toward more concurrent agents writing the same global-scope store."},"logging.level":{type:"string",env:"ADHD_BACKLOG_LOG_LEVEL",default:"info",enum:["trace","debug","info","warn","error","fatal","silent"]},"migration.phase":{type:"string",env:"ADHD_BACKLOG_MIGRATION_PHASE",default:"not-started",enum:["not-started","phase-1","phase-2","phase-3","phase-4","phase-5","complete"],description:"MIGRATION.md §4.4 — a queried signal (never hardcoded prose) for whether BACKLOG.md or the tool is authoritative right now. Read via `migrationStatus(ctx)`/`backlog migration-status`. NOT yet per-repo-keyed (MIGRATION.md §9 open decision 6) — one global value."}}};function Hl(e){if(e)return e;const t=process.env.ADHD_BACKLOG_SCOPE;if(t)return t;const n=process.env.ADHD_ENV_SCOPE;return n||"global"}function ii(e={}){const t={namespace:"production",scope:Hl(e.scope)};return e.adhdRoot!==void 0&&(t.adhdRoot=e.adhdRoot),e.cwd!==void 0&&(t.cwd=e.cwd),e.instanceId!==void 0&&(t.instanceId=e.instanceId),new si("backlog",Gl,t)}function cw(e,t){return`${e}:${t}`}const uw={"decimal.js":"Decimal"};function lw(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(uw).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${lw(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));const fw=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],dw={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};let pw=class extends Error{constructor(t,n,r){super(n),this.name="ApiError",this.code=t,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const t={code:this.code,message:this.message};return this.details!==void 0&&(t.details=this.details),t}};function ai(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&fw.includes(e.code)&&typeof e.toJSON=="function"}const Po="$apigen";let Xa=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function hw(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new Xa(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);t.set(n.id,n)},resolve(n){for(const r of t.values())if(r.matches(n))return r},get(n){return t.get(n)},ids(){return[...t.keys()]},freeze(){const n=new Map(t),r={register(){throw new Xa("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const s of n.values())if(s.matches(o))return s},get(o){return n.get(o)},ids(){return[...n.keys()]},freeze(){return r}};return r}}}const ci="x-apigen-logical",ui="x-apigen-codec",xo="x-apigen-ctor",To="x-apigen-tojson",mw="0.1.0";function ec(e,t){return{registry:e,resolve:n=>{throw new Error(`[apigen-logical] $ref "${n}" cannot be resolved in run-mode without a descriptor root. Supply a resolve() in the ctx override to handle $ref.`)},seen:new WeakSet,path:"",mode:"strict",...t}}function Lt(e,t,n){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Lt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Jl(e,s,t);return Lt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return Jr(e,t,n);const a=t.items;if(!a)return e.map(u=>Et(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?Et(u):Lt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Lt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return Jr(e,t,n);const a=t.properties;if(!a)return Et(e);const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Lt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?Jr(e,t,n):Et(e)}function Ut(e,t,n){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Ut(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Jl(e,s,t);return Ut(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return e;const a=t.items;if(!a)return e;const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?u:Ut(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Ut(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Ut(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?gw(e,n):e}function Jl(e,t,n,r){const o=n.discriminator;if(o!=null&&o.propertyName){const s=e!==null&&typeof e=="object"?e[o.propertyName]:void 0;if(typeof s=="string"&&o.mapping){const i=o.mapping[s];if(i){const a=t.find(c=>c.$ref===i);if(a)return a}}}return t[0]??{}}function Jr(e,t,n){for(const r of n.registry.ids()){const o=n.registry.get(r);if(o)try{const s=o.encode(e,o.schema,n);return{[Po]:r,v:s}}catch{}}return Et(e)}function gw(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&Po in e){const n=e,r=n[Po],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function Et(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(Et);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=Et(r));return t}return null}function yw(e){return{encode(t,n,r){const o=ec(e,r);return Lt(t,n,o)},decode(t,n,r){const o=ec(e,r);return Ut(t,n,o)}}}const li={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},encode(e,t,n){return e.toISOString()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof e}`);return new Date(String(e))}if(n.mode==="strict"&&Number.isNaN(new Date(e).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(e)}`);return new Date(e)}},fi={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},encode(e,t,n){return String(e)},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof e}`);try{return BigInt(Math.trunc(Number(e)))}catch{return BigInt(0)}}if(n.mode==="strict")return BigInt(e);if(/^-?\d+$/.test(e))try{return BigInt(e)}catch{return BigInt(0)}return BigInt(0)}},di={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(e){return e.type==="string"&&e.format==="decimal"},encode(e,t,n){return e},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e)}if(n.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(e))throw new TypeError(`[decimal] wire value "${e}" at "${n.path}" is not a valid decimal string`);return e}},pi={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},encode(e,t,n){return Buffer.from(e).toString("base64")},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof e}`);return new Uint8Array(0)}if(n.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(e))throw new TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${e}"`);return new Uint8Array(Buffer.from(e,"base64"))}},vw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,hi={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(e){return e.type==="string"&&e.format==="uuid"},encode(e,t,n){return e.toLowerCase()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e).toLowerCase()}if(n.mode==="strict"&&!vw.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},Co="NaN",Ro="Infinity",Mo="-Infinity",$w=new Set([Co,Ro,Mo]),mi={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,n){return Number.isNaN(e)?Co:e===1/0?Ro:e===-1/0?Mo:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===Co)return NaN;if(e===Ro)return 1/0;if(e===Mo)return-1/0;const r=Number(e);if(!Number.isNaN(r))return r}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(e)}. Expected a number or one of ${[...$w].join(", ")}.`);return NaN}},ww=[li,fi,di,pi,hi,mi];function bw(e,t={}){for(const n of ww)e.register(n,{override:t.override??!1})}li.id,fi.id,di.id,pi.id,hi.id,mi.id;const Wl=hw();bw(Wl);const Ql=yw(Wl.freeze());function Sw(e,t){var n;const r=((n=e.input)==null?void 0:n.properties)??{};return t in r}function Ew(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data;return Object.keys((r==null?void 0:r.properties)??{})}function Nw(e,t){var n,r,o;const s=(o=(r=(n=e.input)==null?void 0:n.properties)==null?void 0:r.data)==null?void 0:o.properties,i=s==null?void 0:s[t];return i!==void 0?i:void 0}function Ow(e,t){return t===void 0||e===void 0?e:Ql.decode(e,t)}function Wr(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:Ql.encode(e,n)}async function _w(e,t,n,r,o,s){const i=Ew(n).map(c=>Ow(s[c],Nw(n,c)));if(Sw(n,"session")&&t){const c=await t({session:o.session}),u=await e[r](c,...i);return Wr(u,n)}if(n.hasCtx){const c=t?await t(o):void 0,u=await e[r](c,...i);return Wr(u,n)}const a=await e[r](...i);return Wr(a,n)}let kw=class{constructor(){this._map=new Map}set(t,n){this._map.set(t,n)}get(t){return this._map.get(t)}has(t){return this._map.has(t)}};function Aw(e=[]){return async function(t,n,r){const o=r.schemas[t];if(!o)throw new Error(`apigen/invoke: no schema found for operation "${t}"`);const s=()=>_w(r.fns,r.createClient,o,t,n.envelope,n.domainArgs);return e.reduceRight((i,a)=>()=>a(n,i),s)()}}const tc=new Set(["string","number","boolean","integer"]);function jw(e){if(typeof e!="object"||e===null)return!1;const t=e;if(t.$ref!==void 0||t.oneOf||t.anyOf||t.allOf)return!1;const{type:n}=t;return typeof n=="string"?tc.has(n):Array.isArray(n)?n.every(r=>tc.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function Iw(e){if(!e||typeof e!="object")return!1;const t=e.properties;return t===void 0||typeof t!="object"||t===null?!1:Object.values(t).every(jw)}const Pw={"decimal.js":"Decimal"};function xw(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Pw).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${xw(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Tw(e={}){const t=e.level??"info",n=typeof e.destination=="string"&&e.destination.length>0,r=!n&&!!process.stderr.isTTY,o=e.format??(r?"pretty":"json"),s={level:t};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:e.destination,mkdir:!0}:{destination:2}}},Ie(s);const i=n?Ie.destination({dest:e.destination,mkdir:!0,sync:!0}):Ie.destination(2);return Ie(s,i)}function Yl(e){return e?e.type==="array"?`${Yl(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function Zl(e){var t;const n=(t=((e==null?void 0:e.input)??{}).properties)==null?void 0:t.data,r=(n==null?void 0:n.properties)??{},o=new Set((n==null?void 0:n.required)??[]),s=Object.entries(r).map(([a,c])=>({name:a,type:Yl(c),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}function Cw(e){let t;return Array.isArray(e)?t=e:e?t=[e]:t=[],t.find(n=>n==="number"||n==="integer"||n==="boolean")}function Rw(e,t){var n,r;const o=((r=(n=((t==null?void 0:t.input)??{}).properties)==null?void 0:n.data)==null?void 0:r.properties)??{},s={...e};for(const[i,a]of Object.entries(o)){const c=s[i];if(typeof c!="string")continue;const u=Cw(a==null?void 0:a.type);if(u==="number"||u==="integer"){const l=Number(c);!Number.isNaN(l)&&c.trim()!==""&&(s[i]=l)}else u==="boolean"&&(c==="true"?s[i]=!0:c==="false"&&(s[i]=!1))}return s}let Mw=class extends Error{constructor(t,n,r){super(n),this.name="ApiError",this.code=t,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const t={code:this.code,message:this.message};return this.details!==void 0&&(t.details=this.details),t}};const jr=new Ho({allErrors:!0});Jo(jr);for(const e of[ci,ui,xo,To,"discriminator"])jr.addKeyword({keyword:e,valid:!0});jr.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function Dw(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function Lw(e){return async function(t,n){const r=t.operation.id,o=e[r];if(o===void 0)return n();const s={data:t.domainArgs,...t.envelope},i=jr.compile(o.input);if(!i(s)){const a=i.errors??[];throw new Mw("invalid_argument",`Validation failed: ${Dw(a)}`,a)}return n()}}function Uw(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}let ht=class extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}};function Qr(e){const t=e.discriminator;if(t===null||typeof t!="object"||Array.isArray(t))return;const n=t;if(typeof n.propertyName!="string")return;const r=n.mapping;if(!(r===null||typeof r!="object"||Array.isArray(r)))return{propertyName:n.propertyName,mapping:r}}function Xl(e,t){const n=e[ui];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function Bw(e,t,n){const r=Xl(t,n);return r?r.encode(e,t,n):e}function Fw(e,t,n){const r=Xl(t,n);return r?r.decode(e,t,n):e}function Vw(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[ci]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:Qr(r)!==void 0},encode(r,o,s){const i=Qr(o);if(!i)throw new ht("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=i,u=r[a];if(u==null)throw new ht("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),f=c[l];if(!f)throw new ht("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const p=s.resolve(f);return Bw(r,p,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let d;throw r===null?d="null":Array.isArray(r)?d="array":d=typeof r,new ht("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${d}.`)}const i=r,a=Qr(o);if(!a)throw new ht("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:u}=a,l=i[c];if(l==null)throw new ht("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const f=String(l),p=u[f];if(!p)throw new ht("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${f}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const h=s.resolve(p);return Fw(r,h,{...s,path:`${s.path}[${f}]`})}}}const Kw="x-apigen-instances";let qn=class extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}};function nc(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function qw(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function rc(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function zw(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function Gw(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[ci]==="nominal"?!0:o[ui]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new qn("E_NOMINAL_CYCLE",`[${t}] cycle detected at "${i.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN §8.3); break the cycle or use 'lossy' mode.`);return null}i.seen.add(o);try{const a=nc(s),c=typeof s[To]=="string"?s[To]:"toJSON",u=o[c];if(typeof u=="function"){const d=u.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const v={};for(const[m,g]of Object.entries(d))v[m]=rc(g,a[m],{...i,path:`${i.path}/${m}`});return v}return d}const l={},f=Object.keys(a),p=o,h=f.length>0?f:Object.keys(p);for(const d of h){const v=p[d];v!==void 0&&(l[d]=rc(v,a[d],{...i,path:`${i.path}/${d}`}))}return l}finally{i.seen.delete(o)}},decode(o,s,i){if(o===null||typeof o!="object"||Array.isArray(o)){let l;throw o===null?l="null":Array.isArray(o)?l="array":l=typeof o,new qn("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of qw(s))if(!(l in a))throw new qn("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[Kw]===!1)throw new qn("E_NOMINAL_NONRECONSTRUCTABLE",`[${t}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=nc(s),u={};for(const[l,f]of Object.entries(a))u[l]=zw(f,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[xo]=="string"?s[xo]:"fromJSON",f=r[l];if(typeof f=="function")return f.call(r,u);const p=r;return new p(u)}return u}}}const Hw=[li,fi,di,pi,hi,mi],Jw={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},oc=Gw({id:"ts.NominalSentinel",schema:Jw}),Ww={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},sc=Vw({id:"ts.UnionSentinel",schema:Ww});function Qw(){const e=[...Hw.map(t=>[t.id,t]),[oc.id,oc],[sc.id,sc]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:mw,codecs:Qw()});function ic(e){return e.words.join("-")}function ac(e){return e.words.map(tb).join("")}function cc(e){return e.words.join("_")}function Yw(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||Iw(e.input)?"GET":"POST",i=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??s,a="/"+o.map(h=>ic(h)).join("/"),c=o.map(h=>cc(h)).join("_"),u=o.map(h=>cc(h)).slice(0,-1).join("."),l=ac(o[o.length-2]??o[0]),f=ac(o[o.length-1]),p=o.map(h=>ic(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function Zw(e,t){return`x-${e}-${t}`}function Xw(e,t){return`--${e}-${t}`}function eb(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function tb(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function ef(e){return e.anyOf??e.oneOf}function nb(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=ef(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function rb(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=ef(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function ob(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function sb(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data,o=(r==null?void 0:r.properties)??{},s=(r==null?void 0:r.required)??[];return{props:o,required:s}}function uc(e){return typeof e.handler=="function"}function ib(e){var t;const n=((t=e.input)==null?void 0:t.properties)??{},r=e["x-apigen-envelope"],o=[];for(const s of Object.keys(n)){if(s==="data")continue;const i=(r==null?void 0:r[s])??"adhd",a=Zw(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:Xw(i,s),envVar:eb(i,s)})}return o}function ab(e,t){const n=new Map,{props:r}=sb(e);for(const[o,s]of Object.entries(r)){let i="string";rb(s)?i="boolean":nb(s)&&(i="json"),n.set(ob(o),{camelKey:o,kind:"domain",valueKind:i})}for(const o of t){const s=o.cliFlag.replace(/^--/,"");n.set(s,{camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar})}return n}function lc(e){const{op:t,schema:n,transport:r,projection:o}=e,s=Yw(t,o),i=n?ib(n):[],a=n?ab(n,i):new Map,c=n?Zl(n).params:void 0,u={op:t,transport:r,http:s.http,mcp:s.mcp,cli:s.cli,grpc:s.grpc,params:c,envelope:i,cliFlags:a,streaming:t.streaming,isMount:uc(t)};if(uc(t)){const l=t.handler;u.mountHandler=async f=>l(f)}return u}function cb(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function ub(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function lb(e){return async function(t,n){const r=Object.assign(t,{data:t.domainArgs});return await e.layer(r,n)}}function fc(e,t){var n;const r=[];for(const o of t){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(lb(s))}return r.push(Lw(e)),Aw(r)}function fb(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const db={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function dc(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new kw};if(e.isMount){const s=e.mountHandler;if(!s)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${e.op.id}" has isMount=true but no mountHandler`);const i={operation:e.op,data:n.domainArgs,envelope:n.envelope,ctx:fb(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>s(i)},schemas:{[e.op.id]:db}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}const pb={"decimal.js":"Decimal"};function hb(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(pb).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${hb(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Do(e){return e.split(/[-_.]+/).flatMap(t=>t.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").split("_").filter(Boolean)).map(t=>t.toLowerCase()).filter(Boolean)}function pc(e){return{raw:e,words:Do(e)}}function mb(e,t,n,r){for(const o of r??[]){const s=o.path[o.path.length-1];if(o.namespace.raw===e&&(s==null?void 0:s.raw)===t)return o}return{id:`${Do(e).join("-")}/${Do(t).join("-")}`,host:"ts",namespace:pc(e),path:[pc(t)],kind:"action",async:!1,streaming:!1,safe:n["x-apigen-safe"]??!1,input:n.input??{},output:n.output??{},envelope:{},typeText:null}}function gb(e){return`data: ${e}
165
-
166
- `}function yb(e){return`event: error
167
- data: ${e}
168
-
169
- `}async function vb(e,t,n){const r=new AbortController;t.raw.once("close",()=>r.abort());const o=n.raw;let s=!1;try{for await(const i of e){if(r.signal.aborted)break;s||(o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Transfer-Encoding":"chunked"}),s=!0),o.write(gb(JSON.stringify(i)))}s||o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),o.end()}catch(i){const a=ai(i)?i:new pw("internal",i instanceof Error?i.message:String(i));if(s)o.write(yb(JSON.stringify(a.toJSON()))),o.end();else{const c=wb(a.code);o.writeHead(c,{"Content-Type":"application/json"}),o.end(JSON.stringify(a.toJSON()))}}n.hijack()}const $b={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};function wb(e){return $b[e]??500}function tf(e){return ai(e)?dw[e.code]??500:500}function nf(e){return ai(e)?e.toJSON():{code:"internal",message:e instanceof Error?e.message:"Internal error"}}function bb(e,t){if(e)for(const n of t){const r={method:n.method,route:n.route};let o=`${n.method} ${n.route}`;n.params.length&&(r.method==="GET"?o+=` params {${n.text?` ${n.text} `:""}}`:o+=` body { data: {${n.text?` ${n.text} `:""}} }`),e.info(n,o)}}let Sb=class{constructor(t,n,r){this.app=t,this.routePrefix=n,this.signal=r,this.schemasByOpId=new Map}bindSchema(t,n){this.schemasByOpId.set(t,n)}routeFor(t){return t.isMount?`${this.routePrefix}/${t.op.id}`:this.routePrefix+t.http.route}registerRoute(t,n){const r=this.routeFor(t),o=async(s,i)=>{const a={req:s,reply:i};try{const c=await this.readCall(a,t),u=await n(c);await this.writeResult(a,u,t)}catch(c){await this.writeError(a,c,t)}};t.http.verb==="GET"?this.app.get(r,o):this.app.post(r,o)}readCall(t,n){const{req:r}=t,o=r.headers,s={};for(const a of n.envelope){const c=o[a.httpHeader];c!==void 0&&(s[a.field]=c)}let i={};if(!n.isMount){const a=this.schemasByOpId.get(n.op.id);if(n.http.verb==="GET"){const c=r.query??{};i=a?Rw(c,a):c}else{const{data:c={}}=r.body??{};i=c}}return{envelope:s,domainArgs:i,signal:this.signal}}async writeResult(t,n,r){const{req:o,reply:s}=t;if(Uw(n)){await vb(n,o,s);return}s.type("application/json"),s.send(JSON.stringify(n===void 0?null:n))}writeError(t,n,r){const{reply:o}=t;o.status(tf(n)).send(nf(n))}};function Eb(e,t,n,r){var o;const s=[],i={host:n,operations:r};for(const a of e){const c=(o=a.capabilities)==null?void 0:o.mount;if(!c)continue;const u=c.operations(i,t[a.id]);for(const l of u)l.transports&&!l.transports.includes("http")||s.push(l)}return s}async function Nb(e){var t;const n=e.options.port??3e3,r=e.options.host??"127.0.0.1",o=e.options.routePrefix??"",s=e.options.projection??{},i=cb(e.options),a=ub(e.options),c=e.logger??Tw(),u=Kd({logger:c});u.setErrorHandler((d,v,m)=>{m.status(tf(d)).send(nf(d))});const l=new Sb(u,o,e.signal),f=[];for(const d of e.packages){if(!d.fns)throw new Error(`Package "${d.id}" is missing fns`);const v=d.fns,m=Object.entries(d.schemas).map(([N,x])=>({fnName:N,fnSchema:x,op:mb(d.id,N,x,e.operations)})),g={},$={};for(const{fnName:N,fnSchema:x,op:M}of m)g[M.id]=x,$[M.id]=v[N];const w=fc(g,i),S={fns:$,createClient:d.createClient,schemas:g};for(const{fnSchema:N,op:x}of m){const M=lc({op:x,schema:N,transport:"http",projection:s});l.bindSchema(x.id,N),l.registerRoute(M,te=>dc(M,w,te,S));const{params:q,text:Q}=Zl(N);f.push({method:M.http.verb,route:o+M.http.route,text:Q,params:q})}}const p=((t=e.packages[0])==null?void 0:t.id)??"ts",h=Eb(i,a,p,e.operations??[]);if(h.length>0){const d=fc({},i),v={fns:{},schemas:{}};for(const m of h){const g=lc({op:m,transport:"http",projection:s});l.registerRoute(g,$=>dc(g,d,$,v)),f.push({method:g.http.verb,route:`${o}/${m.id}`,text:"",params:[]})}}return await u.listen({port:n,host:r}),c.info({host:r,port:n},`listening on http://${r}:${n}`),bb(c,f),new Promise(d=>{e.signal&&e.signal.addEventListener("abort",async()=>{await u.close(),d()})})}const Ob={id:"api-fastify",run(e){return Nb(e)}},hc=new Set(["string","number","boolean","integer"]);function _b(e){if(typeof e!="object"||e===null)return!1;const t=e;if(t.$ref!==void 0||t.oneOf||t.anyOf||t.allOf)return!1;const{type:n}=t;return typeof n=="string"?hc.has(n):Array.isArray(n)?n.every(r=>hc.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function kb(e){if(!e||typeof e!="object")return!1;const t=e.properties;return t===void 0||typeof t!="object"||t===null?!1:Object.values(t).every(_b)}const Ab={"decimal.js":"Decimal"};function jb(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Ab).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${jb(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function mc(e){return e.words.join("-")}function gc(e){return e.words.map(Pb).join("")}function yc(e){return e.words.join("_")}function Ib(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||kb(e.input)?"GET":"POST",i=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??s,a="/"+o.map(h=>mc(h)).join("/"),c=o.map(h=>yc(h)).join("_"),u=o.map(h=>yc(h)).slice(0,-1).join("."),l=gc(o[o.length-2]??o[0]),f=gc(o[o.length-1]),p=o.map(h=>mc(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function Pb(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function xb(e,t={}){const n=t.title??"API",r=t.version??"0.0.0",o={};for(const s of e){const i=Ib(s),{verb:a,route:c}=i.http,u=a.toLowerCase(),l={operationId:s.id,summary:s.id,responses:{200:Tb(s.output)}};if(a==="GET")l.parameters=Cb(s.input);else{const f=s.input;typeof f=="object"&&f!==null&&Object.keys(f).length>0&&(l.requestBody={required:!0,content:{"application/json":{schema:f}}})}o[c]===void 0&&(o[c]={}),o[c][u]=l}return{openapi:"3.1.0",info:{title:n,version:r},paths:o}}function Tb(e){return typeof e=="object"&&e!==null&&Object.keys(e).length>0?{description:"Success",content:{"application/json":{schema:e}}}:{description:"Success"}}function Cb(e){if(typeof e!="object"||e===null||typeof e.properties!="object"||e.properties===null)return[];const t=Array.isArray(e.required)?e.required:[],n=e.properties;return Object.entries(n).map(([r,o])=>({name:r,in:"query",required:t.includes(r),schema:o}))}function vc(e){return{raw:e,words:e.split(/(?=[A-Z])|[-_]/).map(t=>t.toLowerCase()).filter(Boolean)}}function Rb(e,t={}){return[{id:"_meta/openapi",host:e.host,namespace:vc("meta"),path:[vc("openapi")],kind:"query",async:!1,streaming:!1,safe:!0,input:{},output:{type:"object"},envelope:{},typeText:null,transports:["http"],handler:n=>xb(e.operations,{title:t.title,version:t.version})}]}const Mb={id:"openapi",description:"Mount plugin: serves the OpenAPI 3.1 doc at GET /meta/openapi",language:"ts",optionsSchema:{type:"object",properties:{title:{type:"string",description:"OpenAPI info.title"},version:{type:"string",description:"OpenAPI info.version"}},additionalProperties:!1},capabilities:{mount:{operations(e,t){return Rb(e,t)}}}},Lo="$apigen";class $c extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}}function Db(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new $c(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);t.set(n.id,n)},resolve(n){for(const r of t.values())if(r.matches(n))return r},get(n){return t.get(n)},ids(){return[...t.keys()]},freeze(){const n=new Map(t),r={register(){throw new $c("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const s of n.values())if(s.matches(o))return s},get(o){return n.get(o)},ids(){return[...n.keys()]},freeze(){return r}};return r}}}const gi="x-apigen-logical",yi="x-apigen-codec",Uo="x-apigen-ctor",Bo="x-apigen-tojson",Lb="0.1.0";function wc(e,t){return{registry:e,resolve:n=>{throw new Error(`[apigen-logical] $ref "${n}" cannot be resolved in run-mode without a descriptor root. Supply a resolve() in the ctx override to handle $ref.`)},seen:new WeakSet,path:"",mode:"strict",...t}}function Bt(e,t,n){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Bt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=rf(e,s,t);return Bt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return Yr(e,t,n);const a=t.items;if(!a)return e.map(u=>Nt(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?Nt(u):Bt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Bt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return Yr(e,t,n);const a=t.properties;if(!a)return Nt(e);const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Bt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?Yr(e,t,n):Nt(e)}function Ft(e,t,n){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Ft(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=rf(e,s,t);return Ft(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return e;const a=t.items;if(!a)return e;const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?u:Ft(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Ft(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Ft(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?Ub(e,n):e}function rf(e,t,n,r){const o=n.discriminator;if(o!=null&&o.propertyName){const s=e!==null&&typeof e=="object"?e[o.propertyName]:void 0;if(typeof s=="string"&&o.mapping){const i=o.mapping[s];if(i){const a=t.find(c=>c.$ref===i);if(a)return a}}}return t[0]??{}}function Yr(e,t,n){for(const r of n.registry.ids()){const o=n.registry.get(r);if(o)try{const s=o.encode(e,o.schema,n);return{[Lo]:r,v:s}}catch{}}return Nt(e)}function Ub(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&Lo in e){const n=e,r=n[Lo],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function Nt(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(Nt);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=Nt(r));return t}return null}function Bb(e){return{encode(t,n,r){const o=wc(e,r);return Bt(t,n,o)},decode(t,n,r){const o=wc(e,r);return Ft(t,n,o)}}}const vi={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},encode(e,t,n){return e.toISOString()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof e}`);return new Date(String(e))}if(n.mode==="strict"&&Number.isNaN(new Date(e).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(e)}`);return new Date(e)}},$i={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},encode(e,t,n){return String(e)},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof e}`);try{return BigInt(Math.trunc(Number(e)))}catch{return BigInt(0)}}if(n.mode==="strict")return BigInt(e);if(/^-?\d+$/.test(e))try{return BigInt(e)}catch{return BigInt(0)}return BigInt(0)}},wi={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(e){return e.type==="string"&&e.format==="decimal"},encode(e,t,n){return e},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e)}if(n.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(e))throw new TypeError(`[decimal] wire value "${e}" at "${n.path}" is not a valid decimal string`);return e}},bi={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},encode(e,t,n){return Buffer.from(e).toString("base64")},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof e}`);return new Uint8Array(0)}if(n.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(e))throw new TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${e}"`);return new Uint8Array(Buffer.from(e,"base64"))}},Fb=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Si={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(e){return e.type==="string"&&e.format==="uuid"},encode(e,t,n){return e.toLowerCase()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e).toLowerCase()}if(n.mode==="strict"&&!Fb.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},Fo="NaN",Vo="Infinity",Ko="-Infinity",Vb=new Set([Fo,Vo,Ko]),Ei={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,n){return Number.isNaN(e)?Fo:e===1/0?Vo:e===-1/0?Ko:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===Fo)return NaN;if(e===Vo)return 1/0;if(e===Ko)return-1/0;const r=Number(e);if(!Number.isNaN(r))return r}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(e)}. Expected a number or one of ${[...Vb].join(", ")}.`);return NaN}},Kb=[vi,$i,wi,bi,Si,Ei];function qb(e,t={}){for(const n of Kb)e.register(n,{override:t.override??!1})}vi.id,$i.id,wi.id,bi.id,Si.id,Ei.id;const of=Db();qb(of);const sf=Bb(of.freeze());function zb(e,t){var n;const r=((n=e.input)==null?void 0:n.properties)??{};return t in r}function Gb(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data;return Object.keys((r==null?void 0:r.properties)??{})}function Hb(e,t){var n,r,o;const s=(o=(r=(n=e.input)==null?void 0:n.properties)==null?void 0:r.data)==null?void 0:o.properties,i=s==null?void 0:s[t];return i!==void 0?i:void 0}function Jb(e,t){return t===void 0||e===void 0?e:sf.decode(e,t)}function Zr(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:sf.encode(e,n)}async function Wb(e,t,n,r,o,s){const i=Gb(n).map(c=>Jb(s[c],Hb(n,c)));if(zb(n,"session")&&t){const c=await t({session:o.session}),u=await e[r](c,...i);return Zr(u,n)}if(n.hasCtx){const c=t?await t(o):void 0,u=await e[r](c,...i);return Zr(u,n)}const a=await e[r](...i);return Zr(a,n)}class Qb{constructor(){this._map=new Map}set(t,n){this._map.set(t,n)}get(t){return this._map.get(t)}has(t){return this._map.has(t)}}function Yb(e=[]){return async function(t,n,r){const o=r.schemas[t];if(!o)throw new Error(`apigen/invoke: no schema found for operation "${t}"`);const s=()=>Wb(r.fns,r.createClient,o,t,n.envelope,n.domainArgs);return e.reduceRight((i,a)=>()=>a(n,i),s)()}}const bc=new Set(["string","number","boolean","integer"]);function Zb(e){if(typeof e!="object"||e===null)return!1;const t=e;if(t.$ref!==void 0||t.oneOf||t.anyOf||t.allOf)return!1;const{type:n}=t;return typeof n=="string"?bc.has(n):Array.isArray(n)?n.every(r=>bc.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function Xb(e){if(!e||typeof e!="object")return!1;const t=e.properties;return t===void 0||typeof t!="object"||t===null?!1:Object.values(t).every(Zb)}const eS={"decimal.js":"Decimal"};function tS(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(eS).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${tS(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function nS(e={}){const t=e.level??"info",n=typeof e.destination=="string"&&e.destination.length>0,r=!n&&!!process.stderr.isTTY,o=e.format??(r?"pretty":"json"),s={level:t};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:e.destination,mkdir:!0}:{destination:2}}},Ie(s);const i=n?Ie.destination({dest:e.destination,mkdir:!0,sync:!0}):Ie.destination(2);return Ie(s,i)}function af(e){return e?e.type==="array"?`${af(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function rS(e){var t;const n=(t=((e==null?void 0:e.input)??{}).properties)==null?void 0:t.data,r=(n==null?void 0:n.properties)??{},o=new Set((n==null?void 0:n.required)??[]),s=Object.entries(r).map(([a,c])=>({name:a,type:af(c),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}const oS=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];class cf extends Error{constructor(t,n,r){super(n),this.name="ApiError",this.code=t,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const t={code:this.code,message:this.message};return this.details!==void 0&&(t.details=this.details),t}}function sS(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&oS.includes(e.code)&&typeof e.toJSON=="function"}function Sc(e,t,n=0){return e==="before-first-chunk"?{phase:e,error:t}:{phase:e,error:t,chunksDelivered:n}}const Ir=new Ho({allErrors:!0});Jo(Ir);for(const e of[gi,yi,Uo,Bo,"discriminator"])Ir.addKeyword({keyword:e,valid:!0});Ir.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function iS(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function aS(e){return async function(t,n){const r=t.operation.id,o=e[r];if(o===void 0)return n();const s={data:t.domainArgs,...t.envelope},i=Ir.compile(o.input);if(!i(s)){const a=i.errors??[];throw new cf("invalid_argument",`Validation failed: ${iS(a)}`,a)}return n()}}async function cS(e){const t=[];try{for await(const n of e)t.push(n);return{ok:!0,chunks:t}}catch(n){const r=sS(n)?n:new cf("internal",n instanceof Error?n.message:String(n));return t.length===0?{ok:!1,carrier:Sc("before-first-chunk",r)}:{ok:!1,carrier:Sc("after-first-chunk",r,t.length)}}}function uS(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}class mt extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}}function Xr(e){const t=e.discriminator;if(t===null||typeof t!="object"||Array.isArray(t))return;const n=t;if(typeof n.propertyName!="string")return;const r=n.mapping;if(!(r===null||typeof r!="object"||Array.isArray(r)))return{propertyName:n.propertyName,mapping:r}}function uf(e,t){const n=e[yi];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function lS(e,t,n){const r=uf(t,n);return r?r.encode(e,t,n):e}function fS(e,t,n){const r=uf(t,n);return r?r.decode(e,t,n):e}function dS(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[gi]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:Xr(r)!==void 0},encode(r,o,s){const i=Xr(o);if(!i)throw new mt("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=i,u=r[a];if(u==null)throw new mt("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),f=c[l];if(!f)throw new mt("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const p=s.resolve(f);return lS(r,p,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let d;throw r===null?d="null":Array.isArray(r)?d="array":d=typeof r,new mt("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${d}.`)}const i=r,a=Xr(o);if(!a)throw new mt("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:u}=a,l=i[c];if(l==null)throw new mt("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const f=String(l),p=u[f];if(!p)throw new mt("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${f}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const h=s.resolve(p);return fS(r,h,{...s,path:`${s.path}[${f}]`})}}}const pS="x-apigen-instances";class zn extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}}function Ec(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function hS(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Nc(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function mS(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function gS(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[gi]==="nominal"?!0:o[yi]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new zn("E_NOMINAL_CYCLE",`[${t}] cycle detected at "${i.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN §8.3); break the cycle or use 'lossy' mode.`);return null}i.seen.add(o);try{const a=Ec(s),c=typeof s[Bo]=="string"?s[Bo]:"toJSON",u=o[c];if(typeof u=="function"){const d=u.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const v={};for(const[m,g]of Object.entries(d))v[m]=Nc(g,a[m],{...i,path:`${i.path}/${m}`});return v}return d}const l={},f=Object.keys(a),p=o,h=f.length>0?f:Object.keys(p);for(const d of h){const v=p[d];v!==void 0&&(l[d]=Nc(v,a[d],{...i,path:`${i.path}/${d}`}))}return l}finally{i.seen.delete(o)}},decode(o,s,i){if(o===null||typeof o!="object"||Array.isArray(o)){let l;throw o===null?l="null":Array.isArray(o)?l="array":l=typeof o,new zn("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of hS(s))if(!(l in a))throw new zn("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[pS]===!1)throw new zn("E_NOMINAL_NONRECONSTRUCTABLE",`[${t}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=Ec(s),u={};for(const[l,f]of Object.entries(a))u[l]=mS(f,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[Uo]=="string"?s[Uo]:"fromJSON",f=r[l];if(typeof f=="function")return f.call(r,u);const p=r;return new p(u)}return u}}}const yS=[vi,$i,wi,bi,Si,Ei],vS={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},Oc=gS({id:"ts.NominalSentinel",schema:vS}),$S={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},_c=dS({id:"ts.UnionSentinel",schema:$S});function wS(){const e=[...yS.map(t=>[t.id,t]),[Oc.id,Oc],[_c.id,_c]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:Lb,codecs:wS()});function kc(e,t,n){var r;const o=typeof((r=t==null?void 0:t.input)==null?void 0:r.description)=="string"?t.input.description:void 0,s=[n,o].filter(i=>typeof i=="string"&&i.length>0);return s.length>0?s.join(" — "):e}function lf(e){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0)return{outputSchema:void 0,wrapped:!1};const t=e;return t.type==="object"?{outputSchema:t,wrapped:!1}:{outputSchema:{type:"object",properties:{result:t},required:["result"]},wrapped:!0}}function bS(e,t){return e?{result:t}:t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function Ac(e){return e.words.join("-")}function jc(e){return e.words.map(_S).join("")}function Ic(e){return e.words.join("_")}function SS(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||Xb(e.input)?"GET":"POST",i=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??s,a="/"+o.map(h=>Ac(h)).join("/"),c=o.map(h=>Ic(h)).join("_"),u=o.map(h=>Ic(h)).slice(0,-1).join("."),l=jc(o[o.length-2]??o[0]),f=jc(o[o.length-1]),p=o.map(h=>Ac(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function ES(e,t){return`x-${e}-${t}`}function NS(e,t){return`--${e}-${t}`}function OS(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function _S(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function ff(e){return e.anyOf??e.oneOf}function kS(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=ff(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function AS(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=ff(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function jS(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function IS(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data,o=(r==null?void 0:r.properties)??{},s=(r==null?void 0:r.required)??[];return{props:o,required:s}}function Pc(e){return typeof e.handler=="function"}function PS(e){var t;const n=((t=e.input)==null?void 0:t.properties)??{},r=e["x-apigen-envelope"],o=[];for(const s of Object.keys(n)){if(s==="data")continue;const i=(r==null?void 0:r[s])??"adhd",a=ES(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:NS(i,s),envVar:OS(i,s)})}return o}function xS(e,t){const n=new Map,{props:r}=IS(e);for(const[o,s]of Object.entries(r)){let i="string";AS(s)?i="boolean":kS(s)&&(i="json"),n.set(jS(o),{camelKey:o,kind:"domain",valueKind:i})}for(const o of t){const s=o.cliFlag.replace(/^--/,"");n.set(s,{camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar})}return n}function xc(e){const{op:t,schema:n,transport:r,projection:o}=e,s=SS(t,o),i=n?PS(n):[],a=n?xS(n,i):new Map,c=n?rS(n).params:void 0,u={op:t,transport:r,http:s.http,mcp:s.mcp,cli:s.cli,grpc:s.grpc,params:c,envelope:i,cliFlags:a,streaming:t.streaming,isMount:Pc(t)};if(Pc(t)){const l=t.handler;u.mountHandler=async f=>l(f)}return u}function TS(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function CS(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function RS(e){return async function(t,n){const r=Object.assign(t,{data:t.domainArgs});return await e.layer(r,n)}}function Tc(e,t){var n;const r=[];for(const o of t){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(RS(s))}return r.push(aS(e)),Yb(r)}function MS(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const DS={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function Cc(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new Qb};if(e.isMount){const s=e.mountHandler;if(!s)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${e.op.id}" has isMount=true but no mountHandler`);const i={operation:e.op,data:n.domainArgs,envelope:n.envelope,ctx:MS(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>s(i)},schemas:{[e.op.id]:DS}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}const LS={"decimal.js":"Decimal"};function US(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(LS).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${US(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function BS(e){return e.split(/[-_.]+/).flatMap(t=>t.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").split("_").filter(Boolean)).map(t=>t.toLowerCase()).filter(Boolean)}const FS={"decimal.js":"Decimal"};function VS(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(FS).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${VS(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function KS(e){return e.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function qo(e){return{raw:e,words:BS(e)}}function qS(e){return qo(KS(no.basename(e)))}function zS(e,t,n){if(n){const r=n.find(o=>{var s;return o.kind==="action"&&o.namespace.raw===e.id&&((s=o.path[o.path.length-1])==null?void 0:s.raw)===t});if(!r)throw new Error(`@adhd/apigen-plugin-mcp: no Operation found for package "${e.id}" fn "${t}" in the supplied operations[] — every fn in pkg.schemas must correspond to a real extracted Operation (orchestrator.ts buildDescriptor Step 5 invariant). This indicates a correlation bug, not a naming gap.`);return r}return{id:`${e.id}/${t}`,host:"ts",namespace:qo(e.id),path:[qS(e.importPath),qo(t)],kind:"action",async:!1,streaming:!1,safe:!1,input:{},output:{},envelope:{},typeText:null}}const GS=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];function HS(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&GS.includes(e.code)&&typeof e.toJSON=="function"}async function JS(e){const t=await cS(e);if(t.ok){const o=t.chunks.map(s=>({type:"text",text:JSON.stringify(s)}));return o.push({type:"text",text:"[stream complete]"}),{content:o}}const{carrier:n}=t;if(n.phase==="before-first-chunk")return{content:[{type:"text",text:JSON.stringify(n.error.toJSON())}],isError:!0};const r={...n.error.toJSON(),chunksDelivered:n.chunksDelivered};return{content:[{type:"text",text:JSON.stringify(r)}],isError:!0}}class WS{constructor(){this.plans=new Map,this.dispatchers=new Map,this.schemasByOpId=new Map,this.toolMeta=new Map}bindSchema(t,n){this.schemasByOpId.set(t,n)}bindToolMeta(t,n){this.toolMeta.set(t,n)}registerRoute(t,n){this.plans.set(t.mcp.name,t),this.dispatchers.set(t.mcp.name,n)}getPlan(t){return this.plans.get(t)}getDispatch(t){return this.dispatchers.get(t)}listTools(){return[...this.plans.keys()].map(t=>{const n=this.toolMeta.get(t);return{name:t,description:(n==null?void 0:n.description)??t,inputSchema:(n==null?void 0:n.inputSchema)??{type:"object",properties:{}},...n!=null&&n.outputSchema?{outputSchema:n.outputSchema}:{}}})}readCall(t,n){const r={};for(const s of n.envelope){const i=t.meta[s.mcpMetaKey];i!==void 0&&(r[s.field]=i)}const o=t.args.data??{};return{envelope:r,domainArgs:o}}async writeResult(t,n,r){if(uS(n)){t.output=await JS(n);return}const o=this.schemasByOpId.get(r.op.id),{wrapped:s}=lf(o==null?void 0:o.output),i=bS(s,n);t.output={content:[{type:"text",text:JSON.stringify(n)}],...i?{structuredContent:i}:{}}}writeError(t,n,r){throw HS(n)&&n.code,n}}function QS(e,t,n,r){var o;const s=[],i={host:n,operations:r};for(const a of e){const c=(o=a.capabilities)==null?void 0:o.mount;if(!c)continue;const u=c.operations(i,t[a.id]);for(const l of u)l.transports&&!l.transports.includes("mcp")||s.push(l)}return s}function YS(e,t){var n;const r=e.options.projection??{},o=e.options.toolDescriptions??{},s=TS(e.options),i=CS(e.options);for(const u of e.packages){if(!u.fns)throw new Error(`Package "${u.id}" is missing fns`);const l=u.fns,f=Object.entries(u.schemas).map(([m,g])=>({fnName:m,fnSchema:g,op:zS({id:u.id,importPath:u.importPath},m,e.operations)})),p={},h={};for(const{fnName:m,fnSchema:g,op:$}of f)p[$.id]=g,h[$.id]=l[m];const d=Tc(p,s),v={fns:h,createClient:u.createClient,schemas:p};for(const{fnName:m,fnSchema:g,op:$}of f){const w=xc({op:$,schema:g,transport:"mcp",projection:r});t.bindSchema($.id,g);const{outputSchema:S}=lf(g.output),N=kc(w.mcp.name,g,o[w.mcp.name]??o[m]);t.bindToolMeta(w.mcp.name,{description:N,inputSchema:g.input,outputSchema:S}),t.registerRoute(w,x=>Cc(w,d,x,v))}}const a=((n=e.packages[0])==null?void 0:n.id)??"ts",c=QS(s,i,a,e.operations??[]);if(c.length>0){const u=Tc({},s),l={fns:{},schemas:{}};for(const f of c){const p=xc({op:f,transport:"mcp",projection:r}),h=kc(p.mcp.name,void 0,o[p.mcp.name]),d=f.input&&typeof f.input=="object"&&f.input.type==="object"?f.input:{type:"object",properties:{}};t.bindToolMeta(p.mcp.name,{description:h,inputSchema:d}),t.registerRoute(p,v=>Cc(p,u,v,l))}}}function eo(e,t){const n=new qd.Server({name:"apigen-mcp",version:"1.0.0"},{capabilities:{tools:{}}});return n.setRequestHandler(Di.ListToolsRequestSchema,async()=>({tools:e.listTools()})),n.setRequestHandler(Di.CallToolRequestSchema,async r=>{const{name:o,arguments:s={}}=r.params,i=e.getPlan(o),a=e.getDispatch(o);if(!i||!a)throw new Error(`Unknown tool: ${o}`);const c=s,u=c._meta??{},l={args:c,meta:u},f=Date.now();try{const p=await e.readCall(l,i),h=await a(p);return await e.writeResult(l,h,i),t.info({tool:o,ms:Date.now()-f},`→ ${o}`),l.output}catch(p){throw t.error({tool:o,ms:Date.now()-f,err:p},`✗ ${o}`),e.writeError(l,p,i),p}}),n}function Rc(e,t){return async(n,r)=>{try{await t(n,r)}catch(o){e.error({err:o},"mcp http transport handler error"),r.headersSent||r.writeHead(500),r.writableEnded||r.end("Internal Server Error")}}}async function ZS(e){const t=e.options.transport??"stdio",n=e.options.port??3e3,r=e.options.host??"127.0.0.1",o=e.logger??nS();o.info(`mcp server starting (${t})`);const s=new WS;YS(e,s);const i=s.listTools().map(c=>c.name);o.info({tools:i},`${i.length} tools available`);for(const c of i){const u=s.getPlan(c),l=(u==null?void 0:u.params)??[],f=l.map(p=>`${p.name}${p.required?"":"?"}: ${p.type}`).join(", ");o.info({tool:c,args:{data:l}},`tool: ${c} args { data: {${f?` ${f} `:""}} }`)}if(t==="stdio"){const c=eo(s,o),u=new zd.StdioServerTransport;return await c.connect(u),o.info("stdio transport ready"),new Promise(l=>{e.signal&&e.signal.addEventListener("abort",()=>{o.info("mcp server shutting down"),l()})})}if(t==="sse"){const c=new Map,u=Mi.createServer(Rc(o,async(l,f)=>{const p=l.url??"";if(l.method==="GET"&&p==="/sse"){const h=eo(s,o),d=new Gd.SSEServerTransport("/messages",f);c.set(d.sessionId,d),d.onclose=()=>c.delete(d.sessionId),await h.connect(d)}else if(l.method==="POST"&&p.startsWith("/messages")){const h=new URLSearchParams(p.split("?")[1]??"").get("sessionId"),d=h?c.get(h):void 0;if(!d){f.writeHead(404),f.end("Session not found");return}await d.handlePostMessage(l,f)}else f.writeHead(404),f.end("Not found")}));return u.listen(n,r,()=>{o.info({host:r,port:n},`listening on http://${r}:${n}`)}),new Promise(l=>{e.signal&&e.signal.addEventListener("abort",()=>{o.info("mcp server shutting down"),u.close(()=>l())})})}const a=Mi.createServer(Rc(o,async(c,u)=>{const l=eo(s,o),f=new Hd.StreamableHTTPServerTransport({sessionIdGenerator:void 0});await l.connect(f),await f.handleRequest(c,u)}));return a.listen(n,r,()=>{o.info({host:r,port:n},`listening on http://${r}:${n}`)}),new Promise(c=>{e.signal&&e.signal.addEventListener("abort",()=>{o.info("mcp server shutting down"),a.close(()=>c())})})}const XS={id:"mcp",run(e){return ZS(e)}},df=new Set(["FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED"]),pf=new Set(["MITIGATED"]),hf=new Set(["SUPERSEDED","INVALID","DUPLICATE","WONTFIX"]),Ni=new Set(["FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED","MITIGATED","SUPERSEDED","INVALID","DUPLICATE","WONTFIX"]);function Ve(e){return Ni.has(e)}function pr(e){return df.has(e)||pf.has(e)}function hr(e){return hf.has(e)}class _e extends Error{constructor(t,n){super(`backlog item not found: ${t}::${n}`),this.name="BacklogItemNotFoundError"}}class mf extends Error{constructor(t){super(`transition to terminal status "${t}" requires at least one citation (either already attached via addCitation or passed inline to transitionStatus/resolveItem) — per the global CLAUDE.md rule "No citation, no claim."`),this.name="CitationRequiredError"}}class gf extends Error{constructor(t){super(`transition to terminal-dismissed status "${t}" requires a reason string`),this.name="ReasonRequiredError"}}class yf extends Error{constructor(t,n){super(`item is claimed by "${t}" since ${n} (not stale) — cannot start work`),this.heldBy=t,this.heldSince=n,this.name="ClaimHeldError"}}class eE extends Error{constructor(t){super(`dependency cycle detected: ${t.join(" -> ")}`),this.cycle=t,this.name="DependencyCycleError"}}function tE(e,t){const n=t??F.join(Gt.homedir(),`.${e.orgNamespace}`);return F.join(n,e.project,e.namespace,"config.yaml")}function nE(e,t,n){const r=tE(e,n);let o={};if(W.existsSync(r))try{const a=Li.parse(W.readFileSync(r,"utf8"));a!==null&&typeof a=="object"&&!Array.isArray(a)&&(o=a)}catch{o={}}const s=o.migration&&typeof o.migration=="object"&&!Array.isArray(o.migration)?o.migration:{},i={...o,migration:{...s,phase:t}};return W.mkdirSync(F.dirname(r),{recursive:!0}),W.writeFileSync(r,Li.stringify(i),"utf8"),r}const De="backlog-item",Mc="backlog-plan",Dc="backlog-assignee",rE="adhd-backlog:";function oE(e){return Kc.createHash("sha256").update(e.trim().toLowerCase()).digest("hex")}function vf(e){return e.replace(/[^\p{L}\p{N}_\s]/gu," ").trim().replace(/\s+/g," ")}function Pr(e){return e.split("-")[0]??e}function xr(e){return e.replace(/-\d+$/,"")}function Oi(e,t,n,r){return`${n}
170
-
171
- ${r}
172
-
173
- <!-- ${rE}${e}::${t} -->`}function _i(e,t){return`${e}::${t}`}function ki(e){switch(e){case"CRITICAL":return 10;case"HIGH":return 8;case"MEDIUM":return 5;case"LOW":return 2;default:return 1}}function $f(e,t,n=[]){return[...new Set([De,e,t,...n])]}function it(e){return e.tags.includes(De)&&!e.isSuperseded}function ue(e){const t=e.metadata??{},n=t.humanId??"",r=t.kind??Pr(n),o=t.family??xr(n),s=new Set([De,r,o]);return{nodeId:e.id,humanId:n,kind:r,family:o,title:t.title??e.summary??"",body:t.body??"",status:t.status??"UNKNOWN",priority:t.priority,repo:t.repo??e.namespace,projectPath:t.projectPath,plan:t.plan,importedFrom:t.importedFrom,assignee:t.assignee,claimedBy:t.claimedBy,claimedAt:t.claimedAt,citations:t.citations??[],notes:t.notes??[],tags:e.tags.filter(i=>!s.has(i)),createdAt:t.createdAt??e.tCreated,updatedAt:t.updatedAt??t.createdAt??e.tCreated}}const sE=5,iE=20,aE=500;function cE(e){const t=e==null?void 0:e.code;return t==="SQLITE_BUSY"||t==="SQLITE_BUSY_TIMEOUT"||t==="SQLITE_BUSY_SNAPSHOT"}function uE(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,Math.max(0,Math.round(e)))}function wf(e,t={}){const n=t.maxAttempts??sE;for(let r=0;;r++)try{return e()}catch(o){if(!cE(o)||r>=n-1)throw o;const s=Math.min(aE,iE*2**r);uE(s*(.5+Math.random()*.5))}}function lE(e,t,n){const r=e.graph.queryNodes({kind:"generic",tags:[De],namespace:t,metadata:{family:n}});let o=0;for(const s of r){const i=s.metadata,a=/-(\d+)$/.exec((i==null?void 0:i.humanId)??"");a&&(o=Math.max(o,Number(a[1])))}return`${n}-${String(o+1).padStart(3,"0")}`}function fE(e,t,n){return e.graph.queryNodes({kind:"generic",tags:[De],namespace:t,metadata:{humanId:n}}).find(o=>{var s;return it(o)&&((s=o.metadata)==null?void 0:s.humanId)===n})??null}function bf(e,t,n,r,o){return wf(()=>e.db.transaction(()=>{if(r){const i=fE(e,t,r);return o(r,i)}const s=lE(e,t,n);return o(s,null)}).immediate())}const Sf="backlog-audit-event";function Ef(e,t,n,r,o,s){const i=new Date().toISOString(),a={itemNodeId:t,kind:o,at:i,detail:s},c=`audit-event::${n}::${r}::${o}::${i}::${Math.random().toString(36).slice(2)}`,u=e.graph.writeNode(c,{kind:"generic",name:`audit-event::${n}::${r}::${i}`,tags:[Sf],namespace:n,metadata:a});e.graph.writeEdge(u,t,"DERIVED_FROM")}function dE(e,t){return e.graph.queryNodes({kind:"generic",tags:[Sf],metadata:{itemNodeId:t}}).map(r=>r.metadata).filter(r=>r!==void 0&&r.itemNodeId===t).map(r=>({at:r.at,kind:r.kind,detail:r.detail})).sort((r,o)=>r.at.localeCompare(o.at))}const Lc={CRITICAL:0,HIGH:1,MEDIUM:2,LOW:3};function Uc(e){const t=[De];e.kind&&t.push(e.kind),e.tags&&t.push(...e.tags);const n={};e.family&&(n.family=e.family),e.priority&&(n.priority=e.priority),e.plan&&(n.plan=e.plan),e.importedFrom&&(n.importedFrom=e.importedFrom),e.assignee&&(n.assignee=e.assignee),e.claimedBy&&(n.claimedBy=e.claimedBy),e.status&&e.status!=="open"&&e.status!=="closed"&&(n.status=e.status);const r={kind:"generic",tags:t,tagsMatchAll:!0};return e.repo!==void 0&&(r.namespace=e.repo),e.projectPath!==void 0&&(r.projectPath=e.projectPath),Object.keys(n).length>0&&(r.metadata=n),r}function pE(e,t){return t.status==="open"?e.filter(n=>!Ve(n.status)):t.status==="closed"?e.filter(n=>Ve(n.status)):e}function Bc(e,t){return t.rootLevel?e.filter(n=>{const r=n.metadata;return!(r!=null&&r.projectPath)&&!(r!=null&&r.plan)}):e}function Nf(e,t={}){if(t.grep){const o=Uc({...t}),s=vf(t.grep);if(!s)return[];const i=e.graph.searchNodes(s,{limit:t.limit??1e3,filter:o});let a=Bc(i.filter(it),t);return t.offset&&(a=a.slice(t.offset)),a}const n=Uc(t);t.limit!==void 0&&(n.limit=t.limit),t.offset!==void 0&&(n.offset=t.offset);const r=e.graph.queryNodes(n);return Bc(r.filter(it),t)}function ut(e,t={}){const r=Nf(e,t).map(ue);return pE(r,t)}function et(e,t,n){const r=_i(t,n),s=e.graph.queryNodes({kind:"generic",tags:[De],namespace:t,metadata:{humanId:n}}).filter(it);return s.find(i=>i.name===r)??s[0]??null}function an(e,t){const n={};for(const r of e){const o=t(r);o&&(n[o]=(n[o]??0)+1)}return n}function hE(e,t={}){const n=ut(e,{repo:t.repo,projectPath:t.projectPath}),r=n.filter(s=>!Ve(s.status)),o=n.filter(s=>Ve(s.status));return{total:n.length,open:r.length,closed:o.length,byStatus:an(n,s=>s.status),byKind:an(n,s=>s.kind),byFamily:an(n,s=>s.family),byPriority:an(n,s=>s.priority),byRepo:t.repo===void 0?an(n,s=>s.repo):{}}}function mE(e,t={},n=20){const o=ut(e,{repo:t.repo,projectPath:t.projectPath,status:"open"}).filter(s=>s.priority!==void 0);return o.sort((s,i)=>{const a=Lc[s.priority??""]??4,c=Lc[i.priority??""]??4;return a-c||s.humanId.localeCompare(i.humanId)}),o.slice(0,n)}function Of(e,t){const n=e.graph.getEdges({src:t,rel:"DEPENDS_ON"}),r=[];for(const o of n){const s=e.graph.getNode(o.dst);s&&r.push(s)}return r}function gE(e,t,n){const r=et(e,t,n);return r?Of(e,r.id).filter(o=>!o.tInvalid).map(ue).filter(o=>!Ve(o.status)):[]}function yE(e,t={}){return ut(e,{repo:t.repo,projectPath:t.projectPath,status:"open"}).filter(r=>{if(r.claimedBy)return!1;const o=et(e,r.repo,r.humanId);return o?Of(e,o.id).filter(i=>!i.tInvalid).every(i=>Ve(ue(i).status)):!1})}function _f(e,t={}){const n=ut(e,{repo:t.repo,projectPath:t.projectPath}),r=n.map(s=>({humanId:s.humanId,title:s.title,status:s.status})),o=[];for(const s of n){const i=et(e,s.repo,s.humanId);if(i)for(const a of["DEPENDS_ON","RELATES_TO","PART_OF"])for(const c of e.graph.getEdges({src:i.id,rel:a})){const u=e.graph.getNode(c.dst);if(!u||u.tInvalid)continue;const l=u.metadata;l!=null&&l.humanId&&o.push({from:s.humanId,to:l.humanId,rel:a})}}return{nodes:r,edges:o}}function vE(e,t={}){var c;const n=_f(e,t),r=n.edges.filter(u=>u.rel==="DEPENDS_ON"),o=new Map;for(const u of n.nodes)o.set(u.humanId,new Set);for(const u of r)(c=o.get(u.from))==null||c.add(u.to);const s=new Set(n.nodes.map(u=>u.humanId)),i=[];let a=!0;for(;s.size>0&&a;){a=!1;for(const u of[...s].sort())[...o.get(u)??new Set].every(p=>!s.has(p))&&(i.push(u),s.delete(u),a=!0)}return s.size>0?{ok:!1,cycle:$E([...s],o)}:{ok:!0,order:i}}function $E(e,t){const n=new Set(e),r=new Set,o=[];function s(i){if(r.has(i)){const a=o.indexOf(i);return[...o.slice(a),i]}if(!n.has(i))return null;r.add(i),o.push(i);for(const a of t.get(i)??[]){const c=s(a);if(c)return c}return o.pop(),r.delete(i),null}for(const i of e){const a=s(i);if(a)return a}return e}function wE(e,t,n={}){const r=ut(e,{repo:n.repo,projectPath:n.projectPath}),o=t*6e4,s=Date.now();return r.filter(i=>!i.claimedBy||!i.claimedAt?!1:s-Date.parse(i.claimedAt)>=o)}function bE(e,t,n){var u,l,f,p;const r=et(e,t,n);if(!r)throw new _e(t,n);const o=ue(r),s=[{at:o.createdAt,kind:"created",detail:{title:o.title,repo:o.repo}}];for(const h of o.citations)s.push({at:o.updatedAt,kind:"citation",detail:{...h}});for(const h of o.notes)s.push({at:h.at,kind:"note",detail:{by:h.by,text:h.text}});s.push(...dE(e,r.id)),s.sort((h,d)=>h.at.localeCompare(d.at));const i=e.graph.getSupersessionChain(r.id);let a;if(i.length>1){const h=i.findIndex(m=>m.id===r.id),d=h>0?((l=(u=i[h-1])==null?void 0:u.metadata)==null?void 0:l.humanId)??void 0:void 0,v=h>=0&&h<i.length-1?((p=(f=i[h+1])==null?void 0:f.metadata)==null?void 0:p.humanId)??void 0:void 0;a={},d&&(a.supersedes=d),v&&(a.supersededBy=v)}const c={humanId:o.humanId,history:s};return a&&(c.supersessionChain=a),c}class SE extends Error{constructor(t){super(`backlog item not found or invalidated: node ${t}`),this.nodeId=t,this.name="NotFoundError"}}function ke(e,t,n){return wf(()=>e.db.transaction(()=>{const r=e.graph.getNode(t);if(!r||r.tInvalid)throw new SE(t);const o=r.metadata??{},s=n(o);return e.graph.touch(t,{metadata:s}),s}).immediate())}function EE(e,t,n){const r=new Map,o=vf(n.title);if(o)for(const i of e.graph.searchNodes(o,{limit:10,filter:{tags:[De],namespace:t}}))it(i)&&r.set(i.id,i);const s=n.dedupeScan;if(s!=null&&s.symbol)for(const i of e.graph.queryNodes({kind:"generic",tags:[De],namespace:t,metadata:{dedupeSymbol:s.symbol}}))it(i)&&r.set(i.id,i);if(s!=null&&s.path)for(const i of e.graph.queryNodes({kind:"generic",tags:[De],namespace:t,metadata:{dedupePath:s.path}}))it(i)&&r.set(i.id,i);if(s!=null&&s.errorText)for(const i of e.graph.queryNodes({kind:"generic",tags:[De],namespace:t,metadata:{dedupeErrorText:s.errorText}}))it(i)&&r.set(i.id,i);return[...r.values()].map(ue)}function Ai(e,t){if(t.idOverride){const r=et(e,t.repo,t.idOverride);if(r){const o=ue(r);return{item:o,created:!1,duplicateCandidates:[o]}}}const n=t.force?[]:EE(e,t.repo,t);return n.length>0&&!t.force?{item:n[0],created:!1,duplicateCandidates:n}:bf(e,t.repo,t.family,t.idOverride,(r,o)=>{var f,p,h;if(o){const d=ue(o);return{item:d,created:!1,duplicateCandidates:[d]}}const s=Pr(r),i=xr(r),a=new Date().toISOString(),c={humanId:r,kind:s,family:i,title:t.title,body:t.body,status:"OPEN",repo:t.repo,citations:[],notes:[],createdAt:a,updatedAt:a};t.priority!==void 0&&(c.priority=t.priority),t.projectPath!==void 0&&(c.projectPath=t.projectPath),t.plan!==void 0&&(c.plan=t.plan),t.importedFrom!==void 0&&(c.importedFrom=t.importedFrom),((f=t.dedupeScan)==null?void 0:f.symbol)!==void 0&&(c.dedupeSymbol=t.dedupeScan.symbol),((p=t.dedupeScan)==null?void 0:p.path)!==void 0&&(c.dedupePath=t.dedupeScan.path),((h=t.dedupeScan)==null?void 0:h.errorText)!==void 0&&(c.dedupeErrorText=t.dedupeScan.errorText);const u=e.graph.writeNode(Oi(t.repo,r,t.title,t.body),{kind:"generic",name:_i(t.repo,r),summary:t.title,tags:$f(s,i,t.tags),namespace:t.repo,importance:ki(t.priority),confidence:"confirmed",...t.projectPath!==void 0?{projectPath:t.projectPath}:{},metadata:c}),l=e.graph.getNode(u);if(!l)throw new Error(`backlog: writeNode returned an id that does not resolve: ${u}`);return{item:ue(l),created:!0,duplicateCandidates:[]}})}function kf(e,t,n){const r=et(e,t,n);return r?ue(r):null}function Af(e,t,n){const r=et(e,t,n);if(!r)throw new _e(t,n);return r}function jf(e,t,n,r){const o=Af(e,t,n);let s="",i="";if(ke(e,o.id,c=>{const u={...c,updatedAt:new Date().toISOString()};return r.title!==void 0&&(u.title=r.title),r.body!==void 0&&(u.body=r.body),r.projectPath!==void 0&&(u.projectPath=r.projectPath),r.importedFrom!==void 0&&(u.importedFrom=r.importedFrom),s=u.title,i=u.body,u}),r.title!==void 0||r.tags!==void 0||r.projectPath!==void 0){const c={};if(r.title!==void 0&&(c.summary=r.title),r.tags!==void 0){const u=Pr(n),l=xr(n);c.tags=$f(u,l,r.tags)}r.projectPath!==void 0&&(c.projectPath=r.projectPath),e.graph.touch(o.id,c)}if(r.title!==void 0||r.body!==void 0){const c=Oi(t,n,s,i);e.db.prepare("UPDATE node SET content = ?, content_hash = ? WHERE rowid = ? AND t_invalid IS NULL").run(c,oE(c),o.id)}const a=e.graph.getNode(o.id);if(!a)throw new _e(t,n);return ue(a)}function NE(e,t,n,r){const o=Af(e,t,n);e.graph.invalidate(o.id,r)}function ji(e,t,n){const r=e.graph.getNode(t),o=r==null?void 0:r.metadata;o!=null&&o.repo&&(o!=null&&o.humanId)&&Ef(e,t,o.repo,o.humanId,"claim",n)}const OE=30;class _E extends Error{constructor(t,n){super(`cannot release claim held by "${t}" as "${n}" without force`),this.heldBy=t,this.name="ClaimContentionError"}}function If(e,t,n,r={}){const o=(r.staleAfterMin??OE)*6e4;let s;return ke(e,t,i=>{const a=Date.now(),c=new Date(a).toISOString();return!i.claimedBy||i.claimedBy===n?(s={status:i.claimedBy?"renewed":"claimed",claimedBy:n,claimedAt:c},{...i,claimedBy:n,claimedAt:c,updatedAt:c}):(i.claimedAt?a-Date.parse(i.claimedAt):Number.POSITIVE_INFINITY)<=o&&!r.force?(s={status:"held",claimedBy:n,claimedAt:c,heldBy:i.claimedBy,...i.claimedAt!==void 0?{heldSince:i.claimedAt}:{}},i):(s={status:"reclaimed-stale",claimedBy:n,claimedAt:c,previousClaimant:i.claimedBy},{...i,claimedBy:n,claimedAt:c,updatedAt:c})}),s.status!=="held"&&ji(e,t,{status:s.status,by:n}),s}function kE(e,t,n){let r;return ke(e,t,o=>{const s=new Date().toISOString();return r={status:o.claimedBy?"renewed":"claimed",claimedBy:n,claimedAt:s},{...o,claimedBy:n,claimedAt:s,updatedAt:s}}),ji(e,t,{status:r.status,by:n}),r}function AE(e,t,n,r={}){let o;return ke(e,t,s=>{if(!s.claimedBy)return o={status:"release-noop"},s;if(s.claimedBy!==n&&!r.force)throw new _E(s.claimedBy,n);o={status:"released",wasClaimedBy:s.claimedBy};const a=new Date().toISOString(),c={...s,updatedAt:a};return delete c.claimedBy,delete c.claimedAt,c}),o.status!=="release-noop"&&ji(e,t,{status:o.status,by:n,wasClaimedBy:o.wasClaimedBy}),o}function Tr(e,t,n){const r=et(e,t,n);if(!r)throw new _e(t,n);return r}function On(e,t,n,r,o){const s=Tr(e,t,n);let i;ke(e,s.id,c=>{i=c.status;const u=o.citations&&o.citations.length>0?[...c.citations,...o.citations]:c.citations;if(pr(r)&&u.length===0)throw new mf(r);if(hr(r)&&!o.reason)throw new gf(r);const l=new Date().toISOString(),f=[...c.notes];o.note&&f.push({by:o.by,at:l,text:o.note}),o.reason&&f.push({by:o.by,at:l,text:`[transition to ${r}] ${o.reason}`});const p={...c,status:r,citations:u,notes:f,updatedAt:l};return Ni.has(r)&&(delete p.claimedBy,delete p.claimedAt),p}),Ef(e,s.id,t,n,"transition",{from:i,to:r,by:o.by,...o.reason?{reason:o.reason}:{}});const a=e.graph.getNode(s.id);if(!a)throw new _e(t,n);return ue(a)}function jE(e,t,n,r,o){return On(e,t,n,r,o)}function IE(e,t,n,r){const o=Tr(e,t,n),s=If(e,o.id,r);if(s.status==="held")throw new yf(s.heldBy??"unknown",s.heldSince??"unknown");return On(e,t,n,"IN_PROGRESS",{by:r})}function PE(e,t,n,r){const o=Tr(e,t,n);ke(e,o.id,i=>({...i,citations:[...i.citations,r],updatedAt:new Date().toISOString()}));const s=e.graph.getNode(o.id);if(!s)throw new _e(t,n);return ue(s)}function xE(e,t,n,r,o){const s=Tr(e,t,n);ke(e,s.id,a=>{const c=new Date().toISOString();return{...a,notes:[...a.notes,{by:r,at:c,text:o}],updatedAt:c}});const i=e.graph.getNode(s.id);if(!i)throw new _e(t,n);return ue(i)}function TE(e,t,n={}){const r=new Set((n.exclude??[]).map(i=>i.toUpperCase())),o=ut(e,{repo:t.repo,projectPath:t.projectPath,status:"closed"}),s=[];for(const i of o){if(r.has(i.humanId.toUpperCase())||!Ve(i.status))continue;const a=new Date().toISOString();ke(e,i.nodeId,u=>({...u,archivedAt:a,updatedAt:a}));const c=e.graph.getNode(i.nodeId);c&&s.push(ue(c))}return s}function Oe(e,t,n){const r=et(e,t,n);if(!r)throw new _e(t,n);return r}function CE(e,t,n,r){const o=Oe(e,t,n),s=Oe(e,t,r);e.graph.writeEdge(o.id,s.id,"DEPENDS_ON")}function RE(e,t,n,r){const o=Oe(e,t,n),s=Oe(e,t,r);e.db.prepare("DELETE FROM edge WHERE src = ? AND dst = ? AND rel = 'DEPENDS_ON'").run(o.id,s.id)}function ME(e,t,n,r){const o=Oe(e,t,n),s=Oe(e,t,r);e.graph.writeEdge(o.id,s.id,"RELATES_TO")}function DE(e,t,n,r,o){const s=Oe(e,t,n),i=new Date().toISOString();let a="";const c=bf(e,t,r.family,r.idOverride,l=>{a=l;const f=Pr(a),p=xr(a),h={humanId:a,kind:f,family:p,title:r.title,body:r.body,status:"OPEN",repo:t,citations:[],notes:[],createdAt:i,updatedAt:i};return r.priority!==void 0&&(h.priority=r.priority),r.projectPath!==void 0&&(h.projectPath=r.projectPath),r.plan!==void 0&&(h.plan=r.plan),e.graph.supersede(s.id,Oi(t,a,r.title,r.body),{kind:"generic",name:_i(t,a),summary:r.title,tags:["backlog-item",f,p,...r.tags??[]],namespace:t,importance:ki(r.priority),confidence:"confirmed",...r.projectPath!==void 0?{projectPath:r.projectPath}:{},metadata:h})});ke(e,s.id,l=>{const f=[...l.notes,{by:"system",at:i,text:`[superseded by ${a}] ${o}`}],p={...l,status:"SUPERSEDED",notes:f,updatedAt:i};return delete p.claimedBy,delete p.claimedAt,p}),e.graph.invalidate(s.id,o);const u=e.graph.getNode(c);if(!u)throw new Error(`backlog: supersede() returned an id that does not resolve: ${c}`);return ue(u)}function LE(e,t,n,r){const o=Oe(e,t,n),s=[];for(const i of r){const a=Ai(e,{...i,repo:t});e.graph.writeEdge(a.item.nodeId,o.id,"PART_OF"),s.push(a.item)}return s}function UE(e,t,n,r,o){const s=Oe(e,t,n),i=Oe(e,t,r);ke(e,i.id,c=>{const u=new Date().toISOString(),l={...c,status:"DUPLICATE",notes:[...c.notes,{by:"system",at:u,text:`[merged into ${n}] ${o}`}],updatedAt:u};return delete l.claimedBy,delete l.claimedAt,l}),e.graph.writeEdge(i.id,s.id,"SAME_AS"),e.graph.invalidate(i.id,o);const a=e.graph.getNode(s.id);if(!a)throw new _e(t,n);return ue(a)}function Pf(e,t,n,r){const o=Oe(e,t,n);ke(e,o.id,i=>({...i,priority:r,updatedAt:new Date().toISOString()})),e.graph.touch(o.id,{importance:ki(r)});const s=e.graph.getNode(o.id);if(!s)throw new _e(t,n);return ue(s)}function BE(e,t,n){const r=`${t}::plan:${n}`,s=e.graph.queryNodes({kind:"generic",tags:[Mc],namespace:t,metadata:{planSlug:n}}).find(i=>i.name===r&&!i.isSuperseded);return s?s.id:e.graph.writeNode(`plan:${n}`,{kind:"generic",name:r,summary:n,tags:[Mc],namespace:t,metadata:{planSlug:n}})}function zo(e,t,n,r){const o=Oe(e,t,n),s=BE(e,t,r);ke(e,o.id,i=>({...i,plan:r,updatedAt:new Date().toISOString()})),e.graph.writeEdge(o.id,s,"MEMBER_OF")}function FE(e,t){const r=e.graph.queryNodes({kind:"entity",tags:[Dc],metadata:{identity:t}}).find(o=>o.name===t&&!o.isSuperseded);return r?r.id:e.graph.writeNode(`assignee:${t}`,{kind:"entity",name:t,summary:t,tags:[Dc],metadata:{identity:t}})}function VE(e,t,n,r,o){const s=Oe(e,t,n),i=FE(e,r);ke(e,s.id,c=>{const u=new Date().toISOString();return{...c,assignee:r,notes:[...c.notes,{by:o,at:u,text:`assigned to ${r}`}],updatedAt:u}}),e.graph.writeEdge(s.id,i,"ASSIGNED_TO");const a=e.graph.getNode(s.id);if(!a)throw new _e(t,n);return ue(a)}const Fc=/^(#{2,3})\s+([A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+)/,KE=["FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED","CLOSED"],qE=["MITIGATED"],zE=["INVALID","SUPERSEDED","DUPLICATE","WONTFIX"],GE=new Set([...KE,...qE,...zE]),HE=new Set(["OPEN","IN_PROGRESS","PARTIAL","OUTSTANDING","DEFERRED","BLOCKED","MIXED","UNKNOWN","FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED","MITIGATED","SUPERSEDED","INVALID","DUPLICATE","WONTFIX"]);function xf(e){const t=e.toUpperCase();return t==="IN-PROGRESS"?"IN_PROGRESS":t==="CLOSED"?"RESOLVED":HE.has(t)?t:"UNKNOWN"}function Tf(e){var s;const t=(e??"").toLowerCase();if(!t.trim())return null;const n=i=>t.includes(i);if(n("outstanding"))return{label:"OUTSTANDING",open:!0};if(n("partially"))return{label:"PARTIAL",open:!0};if(n("in progress"))return{label:"IN-PROGRESS",open:!0};const r=n("shipped")&&"SHIPPED"||n("superseded")&&"SUPERSEDED"||n("invalid")&&"INVALID"||n("mitigated")&&"MITIGATED"||n("removed")&&!n("open")&&"REMOVED"||n("fixed")&&"FIXED"||n("resolved")&&"RESOLVED"||n("done")&&"DONE"||null,o=n("open")&&"OPEN"||(n("deferred")||n("defer"))&&"DEFERRED"||null;return r&&o?{label:"MIXED",open:!0}:r?{label:r,open:!1}:o?{label:o,open:!0}:n("downgraded")?{label:"OPEN",open:!0}:{label:((s=t.trim().split(/\s+/)[0])==null?void 0:s.toUpperCase().replace(/[^A-Z]/g,""))||"UNKNOWN",open:!0}}function Cf(e,t){const n=t.match(/^\s*-?\s*\*\*Status:\*?\*?\s*([^\n]+)/im),r=n?Tf(n[1]):null;if(r)return r;const o=e.toUpperCase();for(const s of["RESOLVED","FIXED","MITIGATED","DONE","CLOSED"])if(o.includes(s))return{label:s,open:!1};return{label:"UNKNOWN",open:!0}}function Rf(e,t){const r=`${e}
174
- ${t}`.match(/\*{0,2}priority:?\*{0,2}\s*[:-]?\s*(CRITICAL|HIGH|MEDIUM|LOW)/i);return r?r[1].toUpperCase():/—\s*CRITICAL\b/i.test(e)||/\bCRITICAL\b/.test(e)?"CRITICAL":""}const JE=/^[A-Z][A-Z0-9_-]*$/;function WE(e){const t=e.trim().split(/\s+/)[0]??"";return JE.test(t)&&/[0-9_]/.test(t)}function Mf(e){const t=e.split(`
175
- `),n=[],r=[];let o=null;const s=()=>{if(!o)return;const i=o.bodyLines.join(`
176
- `),a=Cf(o.headerLine,i),c=Rf(o.headerLine,i),{bodyLines:u,...l}=o,f=!GE.has(a.label);n.push({...l,status:a.label,open:f,terminal:!f,priority:c,body:i.trim()}),o=null};return t.forEach((i,a)=>{const c=i.match(Fc),u=/^#{2,3}\s/.test(i);if(c&&/\d/.test(c[2])){s();const l=c[2],f=i.replace(Fc,"").replace(/^\s*[—–-]\s*/,"").trim(),p=l.split("-");o={id:l,kind:p[0]??l,family:l.replace(/-\d+[a-z]?$/i,""),title:f,level:c[1].length,line:a+1,headerLine:i,bodyLines:[]}}else if(u){const l=i.replace(/^#{2,3}\s+/,"");WE(l)&&r.push({line:a+1,headerLine:i}),s(),o=null}else o&&o.bodyLines.push(i)}),s(),{items:n,malformedHeaders:r}}function QE(e){return Mf(e).items}function Df(e){return Mf(e)}function YE(e){return`**Citations:** [${e.map(n=>{const r=n.lines?`${n.file}:${n.lines}`:n.file;return n.context?`${r} (${n.context})`:r}).join(", ")}]`}function ZE(e){return e==="IN_PROGRESS"?"IN PROGRESS":e}function Lf(e){const t=[];t.push(`### ${e.humanId} — ${e.title}`),t.push(""),t.push(`**Status:** ${ZE(e.status)}`),e.priority&&t.push(`**Priority:** ${e.priority}`),e.assignee&&t.push(`**Assignee:** ${e.assignee}`),e.plan&&t.push(`**Plan:** ${e.plan}`),t.push(""),e.body&&t.push(e.body,""),e.citations.length>0&&t.push(YE(e.citations));for(const n of e.notes)t.push(`- Note (${n.by}, ${n.at}): ${n.text}`);return t.join(`
177
- `).trimEnd()}function Uf(e){return e.length===0?"":`${e.map(Lf).join(`
178
-
179
- `)}
180
- `}function XE(e){return e.split(`
181
- `).map(eN).join(`
182
- `)}function eN(e){return/^###\s/.test(e)?`##${e}`:/^##\s/.test(e)?`##${e}`:e}function Bf(e,t){let n=`### Archived — resolved/terminal backlog items relocated in batch (${t})
183
-
184
- `;return n+="> Moved via `@adhd/backlog`'s `archiveResolved` (canonical terminal statuses: FIXED/RESOLVED/DONE/\n",n+=`> SHIPPED/VERIFIED/REMOVED/MITIGATED/SUPERSEDED/INVALID/DUPLICATE/WONTFIX). The graph node itself is
185
- `,n+=`> NEVER deleted — this is a rendered snapshot; full history remains queryable via auditTrail.
186
-
187
- `,n+=e.map(r=>XE(Lf(r))).join(`
188
-
189
- `),n+=`
190
- `,n}function Ff(e){return e.map(t=>{const n={humanId:t.id,title:t.title,body:t.body,status:xf(t.status)};return t.priority&&(t.priority==="CRITICAL"||t.priority==="HIGH"||t.priority==="MEDIUM"||t.priority==="LOW")&&(n.priority=t.priority),n})}function Ii(e,t,n){const r=kf(e.store,t,n);if(!r)throw new _e(t,n);return r}async function Vf(e,t){return Ai(e.store,t)}async function Kf(e,t,n){return kf(e.store,t,n)}async function qf(e,t,n,r){return jf(e.store,t,n,r)}async function zf(e,t){return ut(e.store,t??{})}async function Gf(e,t,n,r){NE(e.store,t,n,r)}async function Hf(e,t){return hE(e.store,t??{})}async function Jf(e,t,n){return mE(e.store,t??{},n??20)}async function Wf(e,t){return yE(e.store,t??{})}async function Qf(e,t,n){return gE(e.store,t,n)}async function Yf(e,t){return _f(e.store,t??{})}async function Zf(e,t){return vE(e.store,t??{})}async function Xf(e,t,n){return wE(e.store,t,n??{})}async function ed(e,t,n,r,o){const s=Ii(e,t,n);return If(e.store,s.nodeId,r,o??{})}async function td(e,t,n,r){const o=Ii(e,t,n);return kE(e.store,o.nodeId,r)}async function nd(e,t,n,r,o){const s=Ii(e,t,n);return AE(e.store,s.nodeId,r,o??{})}async function rd(e,t,n,r,o){return VE(e.store,t,n,r,o)}async function od(e,t,n,r){return IE(e.store,t,n,r)}async function sd(e,t,n,r,o){return On(e.store,t,n,r,o)}async function id(e,t,n,r){return PE(e.store,t,n,r)}async function ad(e,t,n,r,o){return xE(e.store,t,n,r,o)}async function cd(e,t,n,r,o){return jE(e.store,t,n,r,o)}async function ud(e,t,n){const r=TE(e.store,t,n??{}),o=r.length>0?Bf(r,new Date().toISOString().slice(0,10)):"";return{archivedCount:r.length,changelogMarkdown:o}}async function ld(e,t,n,r){CE(e.store,t,n,r)}async function fd(e,t,n,r){RE(e.store,t,n,r)}async function dd(e,t,n,r){ME(e.store,t,n,r)}async function pd(e,t,n,r,o){return DE(e.store,t,n,r,o)}async function hd(e,t,n,r){return LE(e.store,t,n,r)}async function md(e,t,n,r,o){return UE(e.store,t,n,r,o)}async function gd(e,t,n,r){return Pf(e.store,t,n,r)}async function yd(e,t,n,r){zo(e.store,t,n,r)}async function vd(e,t){const n=W.readFileSync(t.path,"utf8"),{items:r,malformedHeaders:o}=Df(n),s=Ff(r),i=t.sourcePath??t.path,a={parsed:s.length,created:0,skippedDuplicates:0,updated:0,errors:[],malformedHeaders:o};if(t.dryRun)return a;for(const c of s)try{const u=Ai(e.store,{family:c.humanId.replace(/-\d+$/,""),idOverride:c.humanId,title:c.title,body:c.body,repo:t.repo,...t.projectPath!==void 0?{projectPath:t.projectPath}:{},...t.plan!==void 0?{plan:t.plan}:{},importedFrom:i,...c.priority!==void 0?{priority:c.priority}:{},force:!0});if(u.created&&t.plan!==void 0&&zo(e.store,t.repo,c.humanId,t.plan),u.created&&c.status!=="OPEN"&&On(e.store,t.repo,c.humanId,c.status,{by:"system:importFromMarkdown",...pr(c.status)?{citations:[{file:t.path}]}:{},...hr(c.status)?{reason:`imported from markdown at status ${c.status}`}:{}}),u.created){a.created+=1;continue}a.skippedDuplicates+=1;const l=u.duplicateCandidates[0]??u.item;let f=!1;if(l.importedFrom===void 0||l.importedFrom===i){const h={};l.title!==c.title&&(h.title=c.title),l.body!==c.body&&(h.body=c.body),l.importedFrom===void 0&&(h.importedFrom=i),t.projectPath!==void 0&&l.projectPath!==t.projectPath&&(h.projectPath=t.projectPath),Object.keys(h).length>0&&(jf(e.store,t.repo,c.humanId,h),f=!0),c.priority!==void 0&&l.priority!==c.priority&&(Pf(e.store,t.repo,c.humanId,c.priority),f=!0),l.status!==c.status&&(On(e.store,t.repo,c.humanId,c.status,{by:"system:importFromMarkdown",...pr(c.status)?{citations:[{file:t.path}]}:{},...hr(c.status)?{reason:`re-imported from markdown at status ${c.status}`}:{}}),f=!0)}t.plan!==void 0&&l.plan!==t.plan&&(zo(e.store,t.repo,c.humanId,t.plan),f=!0),f&&(a.updated+=1)}catch(u){a.errors.push({humanId:c.humanId,message:u instanceof Error?u.message:String(u)})}return a}async function $d(e,t){let r=Nf(e.store,t??{}).filter(o=>{var s;return!((s=o.metadata)!=null&&s.archivedAt)}).map(ue);return(t==null?void 0:t.status)==="open"?r=r.filter(o=>!Ve(o.status)):(t==null?void 0:t.status)==="closed"&&(r=r.filter(o=>Ve(o.status))),Uf(r)}async function wd(e,t){return ut(e.store,t??{})}async function bd(e,t,n){return bE(e.store,t,n)}const tN={"not-started":"not-started: BACKLOG.md is authoritative everywhere; the tool has not been adopted for this repo yet.","phase-1":"phase-1: seed import complete (or in progress) — BACKLOG.md remains authoritative; the graph is a read-only shadow copy.","phase-2":"phase-2: BACKLOG.md is still authoritative; the tool is shadow-running in parity-check mode (render vs. hand-edited markdown, non-blocking).","phase-3":"phase-3: the graph is authoritative. File/claim/transition/resolve via the backlog CLI/MCP — every BACKLOG.md is a generated projection, never hand-edited.","phase-4":"phase-4: phase-3 write path is live; the backlog-usage skill is published and distributed for agent discovery.","phase-5":"phase-5: the legacy tools/util/backlog.mjs parser has been deprecated/removed.",complete:"complete: migration fully done, including cross-repo rollout (Phase 6) where applicable."};async function Sd(e){const t=e.env.config.migration.phase;return Ed(t)}function Ed(e){const t=tN[e]??`unknown phase value: ${e}`;return{phase:e,description:t,toolIsAuthoritative:e==="phase-3"||e==="phase-4"||e==="phase-5"||e==="complete"}}async function Nd(e,t){const n=nE(e.env,t,e.adhdRoot);return{...Ed(t),configPath:n}}const nN=Object.freeze(Object.defineProperty({__proto__:null,addCitation:id,addDependency:ld,appendNote:ad,archiveResolved:ud,assignItem:rd,attachToPlan:yd,auditTrail:bd,blockers:Qf,claimItem:ed,createItem:Vf,dependencyGraph:Yf,exportJson:wd,getItem:Kf,importFromMarkdown:vd,linkRelated:dd,listItems:zf,mergeItems:md,migrationStatus:Sd,readyItems:Wf,releaseClaim:nd,removeDependency:fd,renderToMarkdown:$d,renewClaim:td,resolveItem:cd,setMigrationPhase:Nd,setPriority:gd,softDeleteItem:Gf,splitItem:hd,spotlight:Jf,staleClaims:Xf,startWork:od,stats:Hf,supersedeItem:pd,topoOrder:Zf,transitionStatus:sd,updateItem:qf},Symbol.toStringTag,{value:"Module"}));function Go(e){if(!e.run)throw new Error(`@adhd/backlog: apigen plugin "${e.id}" declares no run() — cannot mount live`);return e.run}function Od(){return F.join(F.dirname(mr.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:Pe&&Pe.tagName.toUpperCase()==="SCRIPT"&&Pe.src||new URL("index.js",document.baseURI).href)),"..","dist")}function Vc(e){if(!e||typeof e!="object")return e;const t={},n=o=>{if(Array.isArray(o)){for(const i of o)n(i);return}if(!o||typeof o!="object")return;const s=o;for(const i of["definitions","$defs"]){const a=s[i];if(a&&typeof a=="object"&&!Array.isArray(a))for(const[c,u]of Object.entries(a))c in t||(t[c]=u)}for(const[i,a]of Object.entries(s))i==="definitions"||i==="$defs"||n(a)};if(n(e),n(t),Object.keys(t).length===0)return e;const r=(o,s)=>{if(Array.isArray(o))return o.map(u=>r(u,s));if(!o||typeof o!="object")return o;const i=o,a=i.$ref;if(typeof a=="string"){const u=a.replace(/^#\/(?:definitions|\$defs)\//,"");return s.has(u)||!(u in t)?{}:r(t[u],new Set([...s,u]))}const c={};for(const[u,l]of Object.entries(i))u==="definitions"||u==="$defs"||(c[u]=r(l,s));return c};return r(e,new Set)}async function rN(){const e=F.join(Od(),"client.d.ts");if(!W.existsSync(e))throw new Error(`@adhd/backlog: cannot mount — ${e} does not exist. Run "nx build backlog" first (extract() needs the built .d.ts for type information).`);return zh({sourceFile:e,namespace:"backlog"})}async function Pi(e){const t=typeof e=="function"?e:()=>e,n=await rN(),r={schemas:Object.fromEntries(n.filter(s=>s.kind==="action").map(s=>{var i;return[((i=s.path[s.path.length-1])==null?void 0:i.raw)??"",{input:Vc(s.input),output:Vc(s.output),hasCtx:s.hasCtx,safe:s.safe}]}))};return{pkg:{id:"backlog",schemas:vh(r,[]),importPath:F.join(Od(),"client.js"),fns:nN,createClient:async()=>t()},operations:n}}async function _d(e){const t=ii({scope:e.scope,adhdRoot:e.adhdRoot,cwd:e.cwd});t.ensureDirs();const n=ss(t.files.db,t.config.db.busyTimeoutMs),r={store:n,env:t},{pkg:o,operations:s}=await Pi(r),i=[];(e.transport==="http"||e.transport==="both")&&i.push(Go(Ob)({packages:[o],outputDir:"",options:{port:e.port??3300,host:e.host??"127.0.0.1",usePlugins:[Mb]},signal:e.signal,operations:s})),(e.transport==="mcp"||e.transport==="both")&&i.push(Go(XS)({packages:[o],outputDir:"",options:{transport:"stdio"},signal:e.signal,operations:s}));try{await Promise.all(i)}finally{is(n)}}const to=["claude","codex","opencode"],oN={claude:".claude",codex:".codex",opencode:".opencode"};function sN(e,t,n,r){if(t==="project")return F.join(n,oN[e],"skills");const o=r??Gt.homedir();if(e==="claude")return F.join(o,".claude","skills");if(e==="codex"){const s=r?F.join(o,".codex"):process.env.CODEX_HOME??F.join(o,".codex");return F.join(s,"skills")}return F.join(o,".config","opencode","skills")}function iN(){const e=F.dirname(mr.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:Pe&&Pe.tagName.toUpperCase()==="SCRIPT"&&Pe.src||new URL("index.js",document.baseURI).href));return F.join(e,"..","skill","SKILL.md")}function aN(e){let t="all",n="user";for(let o=0;o<e.length;o++){const s=e[o];if(s==="--host")t=e[++o]??"all";else if(s==="--scope")n=e[++o]??"user";else throw new Error(`backlog install-skill: unknown argument "${s}" (expected --host/--scope)`)}if(n!=="user"&&n!=="project")throw new Error(`backlog install-skill: --scope must be "user" or "project", got "${n}"`);const r=t==="all"?[...to]:[t];for(const o of r)if(!to.includes(o))throw new Error(`backlog install-skill: --host must be one of ${to.join("|")}|all, got "${t}"`);return{hosts:r,scope:n}}function kd(e,t=process.cwd(),n){const{hosts:r,scope:o}=aN(e),s=iN();if(!W.existsSync(s))throw new Error(`backlog install-skill: packaged skill file not found at ${s} — was @adhd/backlog built/installed correctly?`);const i=W.readFileSync(s,"utf8"),a=F.join(F.dirname(mr.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:Pe&&Pe.tagName.toUpperCase()==="SCRIPT"&&Pe.src||new URL("index.js",document.baseURI).href)),"..","package.json"),c=JSON.parse(W.readFileSync(a,"utf8")),u=[];for(const l of r){const f=F.join(sN(l,o,t,n),"backlog");W.mkdirSync(f,{recursive:!0});const p=F.join(f,"SKILL.md");W.writeFileSync(p,i,"utf8"),W.writeFileSync(F.join(f,"extension.json"),JSON.stringify({name:c.name,version:c.version,type:"skill",entrypoint:"SKILL.md"},null,2)+`
191
- `,"utf8"),u.push({host:l,scope:o,path:p})}return u}async function Ad(e){const t=kd(e);console.log(JSON.stringify({installed:t}))}function cN(e){let t="mcp",n,r;for(let s=0;s<e.length;s++){const i=e[s];if(i==="--transport")t=e[++s];else if(i==="--port")n=Number(e[++s]);else if(i==="--host")r=e[++s];else throw new Error(`backlog serve: unknown argument "${i}" (expected --transport/--port/--host)`)}if(t!=="mcp"&&t!=="http"&&t!=="both")throw new Error(`backlog serve: --transport must be mcp|http|both, got "${t}"`);const o={transport:t};return n!==void 0&&(o.port=n),r!==void 0&&(o.host=r),o}async function jd(e,t={}){const n=cN(e),r=new AbortController;process.on("SIGTERM",()=>r.abort()),process.on("SIGINT",()=>r.abort()),await _d({...n,...t,signal:r.signal})}function Id(e){const t=e.find(n=>n.kind==="action");if(!t)throw new Error('@adhd/backlog: cli mount found zero "action" operations in client.ts — cannot derive a command prefix');return em(t).cli.path.slice(0,-1)}function Pd(e,t){var r;return e.length===0?[...e]:(r=e[0])!=null&&r.startsWith("-")?[...e]:t.length>0&&t.every((o,s)=>e[s]===o)?[...e]:[...t,...e]}async function xd(e,t={}){const n=e??process.argv.slice(2);if(n[0]==="install-skill"){await Ad(n.slice(1));return}if(n[0]==="serve"){await jd(n.slice(1),t);return}let r;const o=()=>{if(!r){const s=ii({scope:t.scope,adhdRoot:t.adhdRoot,cwd:t.cwd});s.ensureDirs();const i=ss(s.files.db,s.config.db.busyTimeoutMs);r={store:i,ctx:{store:i,env:s}}}return r.ctx};try{const{pkg:s,operations:i}=await Pi(o),a=n,c=Id(i);await Go(fh)({packages:[s],operations:i,outputDir:"",options:{argv:Pd(a,c)},signal:t.signal??new AbortController().signal})}finally{r&&is(r.store)}}process.argv[1]&&(typeof document>"u"?require("url").pathToFileURL(__filename).href:Pe&&Pe.tagName.toUpperCase()==="SCRIPT"&&Pe.src||new URL("index.js",document.baseURI).href)===mr.pathToFileURL(W.realpathSync(process.argv[1])).href&&xd().catch(e=>{console.error(e instanceof Error?e.stack??e.message:String(e)),process.exitCode=1});exports.BacklogItemNotFoundError=_e;exports.CitationRequiredError=mf;exports.ClaimHeldError=yf;exports.DependencyCycleError=eE;exports.ReasonRequiredError=gf;exports.TERMINAL_DISMISSED_STATUSES=hf;exports.TERMINAL_DONE_STATUSES=df;exports.TERMINAL_STATUSES=Ni;exports.TERMINAL_WORKAROUND_STATUSES=pf;exports.addCitation=id;exports.addDependency=ld;exports.appendNote=ad;exports.archiveResolved=ud;exports.assignItem=rd;exports.attachToPlan=yd;exports.auditTrail=bd;exports.backlogEnvironmentSpec=Gl;exports.blockers=Qf;exports.buildBacklogApigenPackage=Pi;exports.buildBacklogEnv=ii;exports.buildChangelogSection=Bf;exports.claimItem=ed;exports.classifyStatus=Tf;exports.closeGraphBacklogStore=is;exports.createItem=Vf;exports.dependencyGraph=Yf;exports.detectPriority=Rf;exports.detectStatus=Cf;exports.exportJson=wd;exports.getItem=Kf;exports.importFromMarkdown=vd;exports.installSkill=kd;exports.isTerminalStatus=Ve;exports.linkRelated=dd;exports.listItems=zf;exports.mergeItems=md;exports.migrationStatus=Sd;exports.normalizeLegacyStatus=xf;exports.openGraphBacklogStore=ss;exports.parseBacklogMarkdown=QE;exports.parseBacklogMarkdownWithDiagnostics=Df;exports.prefixCommand=Pd;exports.readyItems=Wf;exports.releaseClaim=nd;exports.removeDependency=fd;exports.renderItemsToMarkdown=Uf;exports.renderToMarkdown=$d;exports.renewClaim=td;exports.requiresCitation=pr;exports.requiresReason=hr;exports.resolveBacklogScope=Hl;exports.resolveCommandPrefix=Id;exports.resolveItem=cd;exports.runBacklogCli=xd;exports.runInstallSkillCommand=Ad;exports.runServeCommand=jd;exports.setMigrationPhase=Nd;exports.setPriority=gd;exports.softDeleteItem=Gf;exports.splitItem=hd;exports.spotlight=Jf;exports.staleClaims=Xf;exports.startBacklogServer=_d;exports.startWork=od;exports.stats=Hf;exports.suggestClaimantIdentity=cw;exports.supersedeItem=pd;exports.toImportItems=Ff;exports.topoOrder=Zf;exports.transitionStatus=sd;exports.updateItem=qf;