@acrasie/dev-flow 0.0.0-stage → 1.0.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.
Files changed (58) hide show
  1. package/.codex-plugin/plugin.json +20 -0
  2. package/LICENSE +21 -0
  3. package/README.md +181 -2
  4. package/dist/codex-dev-flow.mjs +3 -0
  5. package/dist/dev-flow.mjs +241 -0
  6. package/docs/adr/0001-hybrid-portable-workflow.md +23 -0
  7. package/docs/adr/0002-share-an-invalidable-context-capsule.md +55 -0
  8. package/docs/adr/0004-scale-assurance-lanes-by-applicable-risk.md +36 -0
  9. package/docs/adr/0006-make-intake-adaptive-user-authoritative-and-token-efficient.md +76 -0
  10. package/docs/adr/0007-collect-opt-in-local-benchmark-feedback.md +82 -0
  11. package/docs/adr/0008-automate-maintainer-releases-with-an-interactive-bun-workflow.md +121 -0
  12. package/docs/adr/0009-separate-intake-decisions-from-shape-discovery.md +200 -0
  13. package/docs/adr/0010-choose-quick-or-plan-after-discovery.md +161 -0
  14. package/docs/adr/0011-separate-fast-local-and-authoritative-ci-quality-gates.md +49 -0
  15. package/docs/adr/0012-use-bun-test-and-require-node-24.md +41 -0
  16. package/docs/adr/0013-layer-source-distribution-and-runtime-tests.md +42 -0
  17. package/docs/adr/0014-ratchet-source-coverage-with-bun.md +51 -0
  18. package/docs/adr/0015-split-fast-and-type-aware-linting.md +41 -0
  19. package/docs/adr/0016-use-husky-with-a-tested-bun-staged-file-adapter.md +45 -0
  20. package/docs/adr/0017-format-conservatively-with-oxfmt.md +45 -0
  21. package/docs/adr/0018-use-a-high-signal-oxlint-policy.md +53 -0
  22. package/docs/adr/0019-gate-deterministic-size-and-observe-timing.md +44 -0
  23. package/docs/adr/0020-support-linux-and-macos-with-targeted-ci.md +41 -0
  24. package/docs/adr/0021-randomize-tests-without-retries.md +35 -0
  25. package/docs/adr/0022-use-one-root-bun-workspace.md +41 -0
  26. package/docs/adr/0024-make-gate-a-minimal-plan-approval.md +74 -0
  27. package/docs/adr/0025-end-the-lifecycle-after-assure.md +55 -0
  28. package/docs/adr/0026-keep-intake-product-stable-and-interview-shape-by-dependency.md +151 -0
  29. package/docs/adr/0027-add-agentic-project-init-and-versioned-engineering-profiles.md +147 -0
  30. package/docs/adr/0028-make-public-documentation-user-first-and-current.md +65 -0
  31. package/docs/adr/0029-make-build-a-native-execution-boundary.md +51 -0
  32. package/docs/adr/0030-unify-product-domain-and-technical-design-interviews.md +240 -0
  33. package/docs/adr/0031-make-assure-the-success-boundary.md +205 -0
  34. package/docs/artifacts.md +47 -0
  35. package/docs/baselines/2026-07-18-p0-lifecycle.json +142 -0
  36. package/docs/design.md +101 -0
  37. package/docs/getting-started.md +204 -0
  38. package/docs/glossary/dev-flow.md +527 -0
  39. package/docs/lifecycle-contract.md +189 -0
  40. package/docs/lifecycle-contract.projection.json +931 -0
  41. package/docs/metrics-protocol.md +113 -0
  42. package/docs/project-profile-contract.md +157 -0
  43. package/docs/runbooks/maintainer-release.md +291 -0
  44. package/docs/target-intake-shape-contract.md +416 -0
  45. package/package.json +68 -4
  46. package/schemas/config.schema.json +104 -0
  47. package/schemas/policy.schema.json +17 -0
  48. package/schemas/project-init-state.schema.json +159 -0
  49. package/schemas/project-profile-local.schema.json +53 -0
  50. package/schemas/project-profile.schema.json +285 -0
  51. package/schemas/state.schema.json +826 -0
  52. package/skills/debug-root-cause/SKILL.md +16 -0
  53. package/skills/design-decisions/SKILL.md +24 -0
  54. package/skills/dev-flow/SKILL.md +306 -0
  55. package/skills/dev-flow/agents/openai.yaml +6 -0
  56. package/skills/discover-change/SKILL.md +31 -0
  57. package/skills/plan-change/SKILL.md +29 -0
  58. package/skills/review-change/SKILL.md +21 -0
@@ -0,0 +1,241 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module"; const require = createRequire(import.meta.url);
3
+ var PS=Object.create;var Gf=Object.defineProperty;var RS=Object.getOwnPropertyDescriptor;var AS=Object.getOwnPropertyNames;var CS=Object.getPrototypeOf,TS=Object.prototype.hasOwnProperty;var Gi=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var v=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var DS=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of AS(t))!TS.call(e,i)&&i!==r&&Gf(e,i,{get:()=>t[i],enumerable:!(n=RS(t,i))||n.enumerable});return e};var Ve=(e,t,r)=>(r=e!=null?PS(CS(e)):{},DS(t||!e||!e.__esModule?Gf(r,"default",{value:e,enumerable:!0}):r,e));var L=v(ce=>{"use strict";var $a=Symbol.for("yaml.alias"),Hf=Symbol.for("yaml.document"),Hi=Symbol.for("yaml.map"),zf=Symbol.for("yaml.pair"),Ea=Symbol.for("yaml.scalar"),zi=Symbol.for("yaml.seq"),dt=Symbol.for("yaml.node.type"),OS=e=>!!e&&typeof e=="object"&&e[dt]===$a,xS=e=>!!e&&typeof e=="object"&&e[dt]===Hf,jS=e=>!!e&&typeof e=="object"&&e[dt]===Hi,NS=e=>!!e&&typeof e=="object"&&e[dt]===zf,Wf=e=>!!e&&typeof e=="object"&&e[dt]===Ea,qS=e=>!!e&&typeof e=="object"&&e[dt]===zi;function Qf(e){if(e&&typeof e=="object")switch(e[dt]){case Hi:case zi:return!0}return!1}function MS(e){if(e&&typeof e=="object")switch(e[dt]){case $a:case Hi:case Ea:case zi:return!0}return!1}var LS=e=>(Wf(e)||Qf(e))&&!!e.anchor;ce.ALIAS=$a;ce.DOC=Hf;ce.MAP=Hi;ce.NODE_TYPE=dt;ce.PAIR=zf;ce.SCALAR=Ea;ce.SEQ=zi;ce.hasAnchor=LS;ce.isAlias=OS;ce.isCollection=Qf;ce.isDocument=xS;ce.isMap=jS;ce.isNode=MS;ce.isPair=NS;ce.isScalar=Wf;ce.isSeq=qS});var pn=v(Ia=>{"use strict";var oe=L(),Se=Symbol("break visit"),Jf=Symbol("skip children"),rt=Symbol("remove node");function Wi(e,t){let r=Yf(t);oe.isDocument(e)?Pr(null,e.contents,r,Object.freeze([e]))===rt&&(e.contents=null):Pr(null,e,r,Object.freeze([]))}Wi.BREAK=Se;Wi.SKIP=Jf;Wi.REMOVE=rt;function Pr(e,t,r,n){let i=Xf(e,t,r,n);if(oe.isNode(i)||oe.isPair(i))return Zf(e,n,i),Pr(e,i,r,n);if(typeof i!="symbol"){if(oe.isCollection(t)){n=Object.freeze(n.concat(t));for(let s=0;s<t.items.length;++s){let o=Pr(s,t.items[s],r,n);if(typeof o=="number")s=o-1;else{if(o===Se)return Se;o===rt&&(t.items.splice(s,1),s-=1)}}}else if(oe.isPair(t)){n=Object.freeze(n.concat(t));let s=Pr("key",t.key,r,n);if(s===Se)return Se;s===rt&&(t.key=null);let o=Pr("value",t.value,r,n);if(o===Se)return Se;o===rt&&(t.value=null)}}return i}async function Qi(e,t){let r=Yf(t);oe.isDocument(e)?await Rr(null,e.contents,r,Object.freeze([e]))===rt&&(e.contents=null):await Rr(null,e,r,Object.freeze([]))}Qi.BREAK=Se;Qi.SKIP=Jf;Qi.REMOVE=rt;async function Rr(e,t,r,n){let i=await Xf(e,t,r,n);if(oe.isNode(i)||oe.isPair(i))return Zf(e,n,i),Rr(e,i,r,n);if(typeof i!="symbol"){if(oe.isCollection(t)){n=Object.freeze(n.concat(t));for(let s=0;s<t.items.length;++s){let o=await Rr(s,t.items[s],r,n);if(typeof o=="number")s=o-1;else{if(o===Se)return Se;o===rt&&(t.items.splice(s,1),s-=1)}}}else if(oe.isPair(t)){n=Object.freeze(n.concat(t));let s=await Rr("key",t.key,r,n);if(s===Se)return Se;s===rt&&(t.key=null);let o=await Rr("value",t.value,r,n);if(o===Se)return Se;o===rt&&(t.value=null)}}return i}function Yf(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Xf(e,t,r,n){if(typeof r=="function")return r(e,t,n);if(oe.isMap(t))return r.Map?.(e,t,n);if(oe.isSeq(t))return r.Seq?.(e,t,n);if(oe.isPair(t))return r.Pair?.(e,t,n);if(oe.isScalar(t))return r.Scalar?.(e,t,n);if(oe.isAlias(t))return r.Alias?.(e,t,n)}function Zf(e,t,r){let n=t[t.length-1];if(oe.isCollection(n))n.items[e]=r;else if(oe.isPair(n))e==="key"?n.key=r:n.value=r;else if(oe.isDocument(n))n.contents=r;else{let i=oe.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}Ia.visit=Wi;Ia.visitAsync=Qi});var Pa=v(tp=>{"use strict";var ep=L(),FS=pn(),VS={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},BS=e=>e.replace(/[!,[\]{}]/g,t=>VS[t]),hn=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let n=t.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[s,o]=n;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[s]=n;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return r(6,`Unsupported YAML version ${s}`,o),!1}}default:return r(0,`Unknown directive ${i}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,n,i]=t.match(/^(.*!)([^!]*)$/s);i||r(`The ${t} tag has no suffix`);let s=this.tags[n];if(s)try{return s+decodeURIComponent(i)}catch(o){return r(String(o)),null}return n==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,n]of Object.entries(this.tags))if(t.startsWith(n))return r+BS(t.substring(n.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),i;if(t&&n.length>0&&ep.isNode(t.contents)){let s={};FS.visit(t.contents,(o,a)=>{ep.isNode(a)&&a.tag&&(s[a.tag]=!0)}),i=Object.keys(s)}else i=[];for(let[s,o]of n)s==="!!"&&o==="tag:yaml.org,2002:"||(!t||i.some(a=>a.startsWith(o)))&&r.push(`%TAG ${s} ${o}`);return r.join(`
4
+ `)}};hn.defaultYaml={explicit:!1,version:"1.2"};hn.defaultTags={"!!":"tag:yaml.org,2002:"};tp.Directives=hn});var Ji=v(mn=>{"use strict";var rp=L(),KS=pn();function US(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function np(e){let t=new Set;return KS.visit(e,{Value(r,n){n.anchor&&t.add(n.anchor)}}),t}function ip(e,t){for(let r=1;;++r){let n=`${e}${r}`;if(!t.has(n))return n}}function GS(e,t){let r=[],n=new Map,i=null;return{onAnchor:s=>{r.push(s),i??(i=np(e));let o=ip(t,i);return i.add(o),o},setAnchors:()=>{for(let s of r){let o=n.get(s);if(typeof o=="object"&&o.anchor&&(rp.isScalar(o.node)||rp.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:n}}mn.anchorIsValid=US;mn.anchorNames=np;mn.createNodeAnchors=GS;mn.findNewAnchor=ip});var Ra=v(sp=>{"use strict";function gn(e,t,r,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,s=n.length;i<s;++i){let o=n[i],a=gn(e,n,String(i),o);a===void 0?delete n[i]:a!==o&&(n[i]=a)}else if(n instanceof Map)for(let i of Array.from(n.keys())){let s=n.get(i),o=gn(e,n,i,s);o===void 0?n.delete(i):o!==s&&n.set(i,o)}else if(n instanceof Set)for(let i of Array.from(n)){let s=gn(e,n,i,i);s===void 0?n.delete(i):s!==i&&(n.delete(i),n.add(s))}else for(let[i,s]of Object.entries(n)){let o=gn(e,n,i,s);o===void 0?delete n[i]:o!==s&&(n[i]=o)}return e.call(t,r,n)}sp.applyReviver=gn});var kt=v(ap=>{"use strict";var HS=L();function op(e,t,r){if(Array.isArray(e))return e.map((n,i)=>op(n,String(i),r));if(e&&typeof e.toJSON=="function"){if(!r||!HS.hasAnchor(e))return e.toJSON(t,r);let n={aliasCount:0,count:1,res:void 0};r.anchors.set(e,n),r.onCreate=s=>{n.res=s,delete r.onCreate};let i=e.toJSON(t,r);return r.onCreate&&r.onCreate(i),i}return typeof e=="bigint"&&!r?.keep?Number(e):e}ap.toJS=op});var Yi=v(lp=>{"use strict";var zS=Ra(),cp=L(),WS=kt(),Aa=class{constructor(t){Object.defineProperty(this,cp.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:n,onAnchor:i,reviver:s}={}){if(!cp.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},a=WS.toJS(this,"",o);if(typeof i=="function")for(let{count:c,res:l}of o.anchors.values())i(l,c);return typeof s=="function"?zS.applyReviver(s,{"":a},"",a):a}};lp.NodeBase=Aa});var yn=v(up=>{"use strict";var QS=Ji(),JS=pn(),Ar=L(),YS=Yi(),XS=kt(),Ca=class extends YS.NodeBase{constructor(t){super(Ar.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let n;r?.aliasResolveCache?n=r.aliasResolveCache:(n=[],JS.visit(t,{Node:(s,o)=>{(Ar.isAlias(o)||Ar.hasAnchor(o))&&n.push(o)}}),r&&(r.aliasResolveCache=n));let i;for(let s of n){if(s===this)break;s.anchor===this.source&&(i=s)}return i}toJSON(t,r){if(!r)return{source:this.source};let{anchors:n,doc:i,maxAliasCount:s}=r,o=this.resolve(i,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=n.get(o);if(a||(XS.toJS(o,null,r),a=n.get(o)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Xi(i,o,n)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(t,r,n){let i=`*${this.source}`;if(t){if(QS.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(t.implicitKey)return`${i} `}return i}};function Xi(e,t,r){if(Ar.isAlias(t)){let n=t.resolve(e),i=r&&n&&r.get(n);return i?i.count*i.aliasCount:0}else if(Ar.isCollection(t)){let n=0;for(let i of t.items){let s=Xi(e,i,r);s>n&&(n=s)}return n}else if(Ar.isPair(t)){let n=Xi(e,t.key,r),i=Xi(e,t.value,r);return Math.max(n,i)}return 1}up.Alias=Ca});var se=v(Ta=>{"use strict";var ZS=L(),e_=Yi(),t_=kt(),r_=e=>!e||typeof e!="function"&&typeof e!="object",$t=class extends e_.NodeBase{constructor(t){super(ZS.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:t_.toJS(this.value,t,r)}toString(){return String(this.value)}};$t.BLOCK_FOLDED="BLOCK_FOLDED";$t.BLOCK_LITERAL="BLOCK_LITERAL";$t.PLAIN="PLAIN";$t.QUOTE_DOUBLE="QUOTE_DOUBLE";$t.QUOTE_SINGLE="QUOTE_SINGLE";Ta.Scalar=$t;Ta.isScalarValue=r_});var vn=v(fp=>{"use strict";var n_=yn(),Yt=L(),dp=se(),i_="tag:yaml.org,2002:";function s_(e,t,r){if(t){let n=r.filter(s=>s.tag===t),i=n.find(s=>!s.format)??n[0];if(!i)throw new Error(`Tag ${t} not found`);return i}return r.find(n=>n.identify?.(e)&&!n.format)}function o_(e,t,r){if(Yt.isDocument(e)&&(e=e.contents),Yt.isNode(e))return e;if(Yt.isPair(e)){let u=r.schema[Yt.MAP].createNode?.(r.schema,null,r);return u.items.push(e),u}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:n,onAnchor:i,onTagObj:s,schema:o,sourceObjects:a}=r,c;if(n&&e&&typeof e=="object"){if(c=a.get(e),c)return c.anchor??(c.anchor=i(e)),new n_.Alias(c.anchor);c={anchor:null,node:null},a.set(e,c)}t?.startsWith("!!")&&(t=i_+t.slice(2));let l=s_(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let u=new dp.Scalar(e);return c&&(c.node=u),u}l=e instanceof Map?o[Yt.MAP]:Symbol.iterator in Object(e)?o[Yt.SEQ]:o[Yt.MAP]}s&&(s(l),delete r.onTagObj);let d=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new dp.Scalar(e);return t?d.tag=t:l.default||(d.tag=l.tag),c&&(c.node=d),d}fp.createNode=o_});var es=v(Zi=>{"use strict";var a_=vn(),nt=L(),c_=Yi();function Da(e,t,r){let n=r;for(let i=t.length-1;i>=0;--i){let s=t[i];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=n,n=o}else n=new Map([[s,n]])}return a_.createNode(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var pp=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Oa=class extends c_.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(n=>nt.isNode(n)||nt.isPair(n)?n.clone(t):n),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(pp(t))this.add(r);else{let[n,...i]=t,s=this.get(n,!0);if(nt.isCollection(s))s.addIn(i,r);else if(s===void 0&&this.schema)this.set(n,Da(this.schema,i,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(t){let[r,...n]=t;if(n.length===0)return this.delete(r);let i=this.get(r,!0);if(nt.isCollection(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}getIn(t,r){let[n,...i]=t,s=this.get(n,!0);return i.length===0?!r&&nt.isScalar(s)?s.value:s:nt.isCollection(s)?s.getIn(i,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!nt.isPair(r))return!1;let n=r.value;return n==null||t&&nt.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(t){let[r,...n]=t;if(n.length===0)return this.has(r);let i=this.get(r,!0);return nt.isCollection(i)?i.hasIn(n):!1}setIn(t,r){let[n,...i]=t;if(i.length===0)this.set(n,r);else{let s=this.get(n,!0);if(nt.isCollection(s))s.setIn(i,r);else if(s===void 0&&this.schema)this.set(n,Da(this.schema,i,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};Zi.Collection=Oa;Zi.collectionFromPath=Da;Zi.isEmptyPath=pp});var wn=v(ts=>{"use strict";var l_=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function xa(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var u_=(e,t,r)=>e.endsWith(`
5
+ `)?xa(r,t):r.includes(`
6
+ `)?`
7
+ `+xa(r,t):(e.endsWith(" ")?"":" ")+r;ts.indentComment=xa;ts.lineComment=u_;ts.stringifyComment=l_});var mp=v(bn=>{"use strict";var d_="flow",ja="block",rs="quoted";function f_(e,t,r="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return e;i<s&&(s=0);let c=Math.max(1+s,1+i-t.length);if(e.length<=c)return e;let l=[],d={},u=i-t.length;typeof n=="number"&&(n>i-Math.max(2,s)?l.push(0):u=i-n);let h,m,p=!1,f=-1,g=-1,y=-1;r===ja&&(f=hp(e,f,t.length),f!==-1&&(u=f+c));for(let b;b=e[f+=1];){if(r===rs&&b==="\\"){switch(g=f,e[f+1]){case"x":f+=3;break;case"u":f+=5;break;case"U":f+=9;break;default:f+=1}y=f}if(b===`
8
+ `)r===ja&&(f=hp(e,f,t.length)),u=f+t.length+c,h=void 0;else{if(b===" "&&m&&m!==" "&&m!==`
9
+ `&&m!==" "){let $=e[f+1];$&&$!==" "&&$!==`
10
+ `&&$!==" "&&(h=f)}if(f>=u)if(h)l.push(h),u=h+c,h=void 0;else if(r===rs){for(;m===" "||m===" ";)m=b,b=e[f+=1],p=!0;let $=f>y+1?f-2:g-1;if(d[$])return e;l.push($),d[$]=!0,u=$+c,h=void 0}else p=!0}m=b}if(p&&a&&a(),l.length===0)return e;o&&o();let w=e.slice(0,l[0]);for(let b=0;b<l.length;++b){let $=l[b],S=l[b+1]||e.length;$===0?w=`
11
+ ${t}${e.slice(0,S)}`:(r===rs&&d[$]&&(w+=`${e[$]}\\`),w+=`
12
+ ${t}${e.slice($+1,S)}`)}return w}function hp(e,t,r){let n=t,i=t+1,s=e[i];for(;s===" "||s===" ";)if(t<i+r)s=e[++t];else{do s=e[++t];while(s&&s!==`
13
+ `);n=t,i=t+1,s=e[i]}return n}bn.FOLD_BLOCK=ja;bn.FOLD_FLOW=d_;bn.FOLD_QUOTED=rs;bn.foldFlowLines=f_});var _n=v(gp=>{"use strict";var Be=se(),Et=mp(),is=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),ss=e=>/^(%|---|\.\.\.)/m.test(e);function p_(e,t,r){if(!t||t<0)return!1;let n=t-r,i=e.length;if(i<=n)return!1;for(let s=0,o=0;s<i;++s)if(e[s]===`
14
+ `){if(s-o>n)return!0;if(o=s+1,i-o<=n)return!1}return!0}function Sn(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:n}=t,i=t.options.doubleQuotedMinMultiLineLength,s=t.indent||(ss(e)?" ":""),o="",a=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(a,c);let d=r.substr(c+2,4);switch(d){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:d.substr(0,2)==="00"?o+="\\x"+d.substr(2):o+=r.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||r[c+2]==='"'||r.length<i)c+=1;else{for(o+=r.slice(a,c)+`
15
+
16
+ `;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`
17
+ `,c+=2;o+=s,r[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+r.slice(a):r,n?o:Et.foldFlowLines(o,s,Et.FOLD_QUOTED,is(t,!1))}function Na(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
18
+ `)||/[ \t]\n|\n[ \t]/.test(e))return Sn(e,t);let r=t.indent||(ss(e)?" ":""),n="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
19
+ ${r}`)+"'";return t.implicitKey?n:Et.foldFlowLines(n,r,Et.FOLD_FLOW,is(t,!1))}function Cr(e,t){let{singleQuote:r}=t.options,n;if(r===!1)n=Sn;else{let i=e.includes('"'),s=e.includes("'");i&&!s?n=Na:s&&!i?n=Sn:n=r?Na:Sn}return n(e,t)}var qa;try{qa=new RegExp(`(^|(?<!
20
+ ))
21
+ +(?!
22
+ |$)`,"g")}catch{qa=/\n+(?!\n|$)/g}function ns({comment:e,type:t,value:r},n,i,s){let{blockQuote:o,commentString:a,lineWidth:c}=n.options;if(!o||/\n[\t ]+$/.test(r))return Cr(r,n);let l=n.indent||(n.forceBlockIndent||ss(r)?" ":""),d=o==="literal"?!0:o==="folded"||t===Be.Scalar.BLOCK_FOLDED?!1:t===Be.Scalar.BLOCK_LITERAL?!0:!p_(r,c,l.length);if(!r)return d?`|
23
+ `:`>
24
+ `;let u,h;for(h=r.length;h>0;--h){let S=r[h-1];if(S!==`
25
+ `&&S!==" "&&S!==" ")break}let m=r.substring(h),p=m.indexOf(`
26
+ `);p===-1?u="-":r===m||p!==m.length-1?(u="+",s&&s()):u="",m&&(r=r.slice(0,-m.length),m[m.length-1]===`
27
+ `&&(m=m.slice(0,-1)),m=m.replace(qa,`$&${l}`));let f=!1,g,y=-1;for(g=0;g<r.length;++g){let S=r[g];if(S===" ")f=!0;else if(S===`
28
+ `)y=g;else break}let w=r.substring(0,y<g?y+1:g);w&&(r=r.substring(w.length),w=w.replace(/\n+/g,`$&${l}`));let $=(f?l?"2":"1":"")+u;if(e&&($+=" "+a(e.replace(/ ?[\r\n]+/g," ")),i&&i()),!d){let S=r.replace(/\n+/g,`
29
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),I=!1,k=is(n,!0);o!=="folded"&&t!==Be.Scalar.BLOCK_FOLDED&&(k.onOverflow=()=>{I=!0});let _=Et.foldFlowLines(`${w}${S}${m}`,l,Et.FOLD_BLOCK,k);if(!I)return`>${$}
30
+ ${l}${_}`}return r=r.replace(/\n+/g,`$&${l}`),`|${$}
31
+ ${l}${w}${r}${m}`}function h_(e,t,r,n){let{type:i,value:s}=e,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:d}=t;if(a&&s.includes(`
32
+ `)||d&&/[[\]{},]/.test(s))return Cr(s,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||d||!s.includes(`
33
+ `)?Cr(s,t):ns(e,t,r,n);if(!a&&!d&&i!==Be.Scalar.PLAIN&&s.includes(`
34
+ `))return ns(e,t,r,n);if(ss(s)){if(c==="")return t.forceBlockIndent=!0,ns(e,t,r,n);if(a&&c===l)return Cr(s,t)}let u=s.replace(/\n+/g,`$&
35
+ ${c}`);if(o){let h=f=>f.default&&f.tag!=="tag:yaml.org,2002:str"&&f.test?.test(u),{compat:m,tags:p}=t.doc.schema;if(p.some(h)||m?.some(h))return Cr(s,t)}return a?u:Et.foldFlowLines(u,c,Et.FOLD_FLOW,is(t,!1))}function m_(e,t,r,n){let{implicitKey:i,inFlow:s}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:a}=e;a!==Be.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=Be.Scalar.QUOTE_DOUBLE);let c=d=>{switch(d){case Be.Scalar.BLOCK_FOLDED:case Be.Scalar.BLOCK_LITERAL:return i||s?Cr(o.value,t):ns(o,t,r,n);case Be.Scalar.QUOTE_DOUBLE:return Sn(o.value,t);case Be.Scalar.QUOTE_SINGLE:return Na(o.value,t);case Be.Scalar.PLAIN:return h_(o,t,r,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:d,defaultStringType:u}=t.options,h=i&&d||u;if(l=c(h),l===null)throw new Error(`Unsupported default string type ${h}`)}return l}gp.stringifyString=m_});var kn=v(Ma=>{"use strict";var g_=Ji(),It=L(),y_=wn(),v_=_n();function w_(e,t){let r=Object.assign({blockQuote:!0,commentString:y_.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),n;switch(r.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:n,options:r}}function b_(e,t){if(t.tag){let i=e.filter(s=>s.tag===t.tag);if(i.length>0)return i.find(s=>s.format===t.format)??i[0]}let r,n;if(It.isScalar(t)){n=t.value;let i=e.filter(s=>s.identify?.(n));if(i.length>1){let s=i.filter(o=>o.test);s.length>0&&(i=s)}r=i.find(s=>s.format===t.format)??i.find(s=>!s.format)}else n=t,r=e.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!r){let i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return r}function S_(e,t,{anchors:r,doc:n}){if(!n.directives)return"";let i=[],s=(It.isScalar(e)||It.isCollection(e))&&e.anchor;s&&g_.anchorIsValid(s)&&(r.add(s),i.push(`&${s}`));let o=e.tag??(t.default?null:t.tag);return o&&i.push(n.directives.tagString(o)),i.join(" ")}function __(e,t,r,n){if(It.isPair(e))return e.toString(t,r,n);if(It.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i,s=It.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>i=c});i??(i=b_(t.doc.schema.tags,s));let o=S_(s,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let a=typeof i.stringify=="function"?i.stringify(s,t,r,n):It.isScalar(s)?v_.stringifyString(s,t,r,n):s.toString(t,r,n);return o?It.isScalar(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
36
+ ${t.indent}${a}`:a}Ma.createStringifyContext=w_;Ma.stringify=__});var bp=v(wp=>{"use strict";var ft=L(),yp=se(),vp=kn(),$n=wn();function k_({key:e,value:t},r,n,i){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:d,simpleKeys:u}}=r,h=ft.isNode(e)&&e.comment||null;if(u){if(h)throw new Error("With simple keys, key nodes cannot have comments");if(ft.isCollection(e)||!ft.isNode(e)&&typeof e=="object"){let k="With simple keys, collection cannot be used as a key value";throw new Error(k)}}let m=!u&&(!e||h&&t==null&&!r.inFlow||ft.isCollection(e)||(ft.isScalar(e)?e.type===yp.Scalar.BLOCK_FOLDED||e.type===yp.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!m&&(u||!s),indent:a+c});let p=!1,f=!1,g=vp.stringify(e,r,()=>p=!0,()=>f=!0);if(!m&&!r.inFlow&&g.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(r.inFlow){if(s||t==null)return p&&n&&n(),g===""?"?":m?`? ${g}`:g}else if(s&&!u||t==null&&m)return g=`? ${g}`,h&&!p?g+=$n.lineComment(g,r.indent,l(h)):f&&i&&i(),g;p&&(h=null),m?(h&&(g+=$n.lineComment(g,r.indent,l(h))),g=`? ${g}
37
+ ${a}:`):(g=`${g}:`,h&&(g+=$n.lineComment(g,r.indent,l(h))));let y,w,b;ft.isNode(t)?(y=!!t.spaceBefore,w=t.commentBefore,b=t.comment):(y=!1,w=null,b=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!m&&!h&&ft.isScalar(t)&&(r.indentAtStart=g.length+1),f=!1,!d&&c.length>=2&&!r.inFlow&&!m&&ft.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let $=!1,S=vp.stringify(t,r,()=>$=!0,()=>f=!0),I=" ";if(h||y||w){if(I=y?`
38
+ `:"",w){let k=l(w);I+=`
39
+ ${$n.indentComment(k,r.indent)}`}S===""&&!r.inFlow?I===`
40
+ `&&b&&(I=`
41
+
42
+ `):I+=`
43
+ ${r.indent}`}else if(!m&&ft.isCollection(t)){let k=S[0],_=S.indexOf(`
44
+ `),q=_!==-1,Q=r.inFlow??t.flow??t.items.length===0;if(q||!Q){let re=!1;if(q&&(k==="&"||k==="!")){let te=S.indexOf(" ");k==="&"&&te!==-1&&te<_&&S[te+1]==="!"&&(te=S.indexOf(" ",te+1)),(te===-1||_<te)&&(re=!0)}re||(I=`
45
+ ${r.indent}`)}}else(S===""||S[0]===`
46
+ `)&&(I="");return g+=I+S,r.inFlow?$&&n&&n():b&&!$?g+=$n.lineComment(g,r.indent,l(b)):f&&i&&i(),g}wp.stringifyPair=k_});var Fa=v(La=>{"use strict";var Sp=Gi("process");function $_(e,...t){e==="debug"&&console.log(...t)}function E_(e,t){(e==="debug"||e==="warn")&&(typeof Sp.emitWarning=="function"?Sp.emitWarning(t):console.warn(t))}La.debug=$_;La.warn=E_});var us=v(ls=>{"use strict";var cs=L(),_p=se(),os="<<",as={identify:e=>e===os||typeof e=="symbol"&&e.description===os,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new _p.Scalar(Symbol(os)),{addToJSMap:kp}),stringify:()=>os},I_=(e,t)=>(as.identify(t)||cs.isScalar(t)&&(!t.type||t.type===_p.Scalar.PLAIN)&&as.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===as.tag&&r.default);function kp(e,t,r){let n=$p(e,r);if(cs.isSeq(n))for(let i of n.items)Va(e,t,i);else if(Array.isArray(n))for(let i of n)Va(e,t,i);else Va(e,t,n)}function Va(e,t,r){let n=$p(e,r);if(!cs.isMap(n))throw new Error("Merge sources must be maps or map aliases");let i=n.toJSON(null,e,Map);for(let[s,o]of i)t instanceof Map?t.has(s)||t.set(s,o):t instanceof Set?t.add(s):Object.prototype.hasOwnProperty.call(t,s)||Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function $p(e,t){return e&&cs.isAlias(t)?t.resolve(e.doc,e):t}ls.addMergeToJSMap=kp;ls.isMergeKey=I_;ls.merge=as});var Ka=v(Pp=>{"use strict";var P_=Fa(),Ep=us(),R_=kn(),Ip=L(),Ba=kt();function A_(e,t,{key:r,value:n}){if(Ip.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,n);else if(Ep.isMergeKey(e,r))Ep.addMergeToJSMap(e,t,n);else{let i=Ba.toJS(r,"",e);if(t instanceof Map)t.set(i,Ba.toJS(n,i,e));else if(t instanceof Set)t.add(i);else{let s=C_(r,i,e),o=Ba.toJS(n,s,e);s in t?Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[s]=o}}return t}function C_(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(Ip.isNode(e)&&r?.doc){let n=R_.createStringifyContext(r.doc,{});n.anchors=new Set;for(let s of r.anchors.keys())n.anchors.add(s.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=e.toString(n);if(!r.mapKeyWarned){let s=JSON.stringify(i);s.length>40&&(s=s.substring(0,36)+'..."'),P_.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return i}return JSON.stringify(t)}Pp.addPairToJSMap=A_});var Pt=v(Ua=>{"use strict";var Rp=vn(),T_=bp(),D_=Ka(),ds=L();function O_(e,t,r){let n=Rp.createNode(e,void 0,r),i=Rp.createNode(t,void 0,r);return new fs(n,i)}var fs=class e{constructor(t,r=null){Object.defineProperty(this,ds.NODE_TYPE,{value:ds.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:n}=this;return ds.isNode(r)&&(r=r.clone(t)),ds.isNode(n)&&(n=n.clone(t)),new e(r,n)}toJSON(t,r){let n=r?.mapAsMap?new Map:{};return D_.addPairToJSMap(r,n,this)}toString(t,r,n){return t?.doc?T_.stringifyPair(this,t,r,n):JSON.stringify(this)}};Ua.Pair=fs;Ua.createPair=O_});var Ga=v(Cp=>{"use strict";var Xt=L(),Ap=kn(),ps=wn();function x_(e,t,r){return(t.inFlow??e.flow?N_:j_)(e,t,r)}function j_({comment:e,items:t},r,{blockItemPrefix:n,flowChars:i,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=r,d=Object.assign({},r,{indent:s,type:null}),u=!1,h=[];for(let p=0;p<t.length;++p){let f=t[p],g=null;if(Xt.isNode(f))!u&&f.spaceBefore&&h.push(""),hs(r,h,f.commentBefore,u),f.comment&&(g=f.comment);else if(Xt.isPair(f)){let w=Xt.isNode(f.key)?f.key:null;w&&(!u&&w.spaceBefore&&h.push(""),hs(r,h,w.commentBefore,u))}u=!1;let y=Ap.stringify(f,d,()=>g=null,()=>u=!0);g&&(y+=ps.lineComment(y,s,l(g))),u&&g&&(u=!1),h.push(n+y)}let m;if(h.length===0)m=i.start+i.end;else{m=h[0];for(let p=1;p<h.length;++p){let f=h[p];m+=f?`
47
+ ${c}${f}`:`
48
+ `}}return e?(m+=`
49
+ `+ps.indentComment(l(e),c),a&&a()):u&&o&&o(),m}function N_({items:e},t,{flowChars:r,itemIndent:n}){let{indent:i,indentStep:s,flowCollectionPadding:o,options:{commentString:a}}=t;n+=s;let c=Object.assign({},t,{indent:n,inFlow:!0,type:null}),l=!1,d=0,u=[];for(let p=0;p<e.length;++p){let f=e[p],g=null;if(Xt.isNode(f))f.spaceBefore&&u.push(""),hs(t,u,f.commentBefore,!1),f.comment&&(g=f.comment);else if(Xt.isPair(f)){let w=Xt.isNode(f.key)?f.key:null;w&&(w.spaceBefore&&u.push(""),hs(t,u,w.commentBefore,!1),w.comment&&(l=!0));let b=Xt.isNode(f.value)?f.value:null;b?(b.comment&&(g=b.comment),b.commentBefore&&(l=!0)):f.value==null&&w?.comment&&(g=w.comment)}g&&(l=!0);let y=Ap.stringify(f,c,()=>g=null);l||(l=u.length>d||y.includes(`
50
+ `)),p<e.length-1?y+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=u.reduce((w,b)=>w+b.length+2,2)+(y.length+2)>t.options.lineWidth)),l&&(y+=",")),g&&(y+=ps.lineComment(y,n,a(g))),u.push(y),d=u.length}let{start:h,end:m}=r;if(u.length===0)return h+m;if(!l){let p=u.reduce((f,g)=>f+g.length+2,2);l=t.options.lineWidth>0&&p>t.options.lineWidth}if(l){let p=h;for(let f of u)p+=f?`
51
+ ${s}${i}${f}`:`
52
+ `;return`${p}
53
+ ${i}${m}`}else return`${h}${o}${u.join(" ")}${o}${m}`}function hs({indent:e,options:{commentString:t}},r,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let s=ps.indentComment(t(n),e);r.push(s.trimStart())}}Cp.stringifyCollection=x_});var At=v(za=>{"use strict";var q_=Ga(),M_=Ka(),L_=es(),Rt=L(),ms=Pt(),F_=se();function En(e,t){let r=Rt.isScalar(t)?t.value:t;for(let n of e)if(Rt.isPair(n)&&(n.key===t||n.key===r||Rt.isScalar(n.key)&&n.key.value===r))return n}var Ha=class extends L_.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Rt.MAP,t),this.items=[]}static from(t,r,n){let{keepUndefined:i,replacer:s}=n,o=new this(t),a=(c,l)=>{if(typeof s=="function")l=s.call(r,c,l);else if(Array.isArray(s)&&!s.includes(c))return;(l!==void 0||i)&&o.items.push(ms.createPair(c,l,n))};if(r instanceof Map)for(let[c,l]of r)a(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))a(c,r[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let n;Rt.isPair(t)?n=t:!t||typeof t!="object"||!("key"in t)?n=new ms.Pair(t,t?.value):n=new ms.Pair(t.key,t.value);let i=En(this.items,n.key),s=this.schema?.sortMapEntries;if(i){if(!r)throw new Error(`Key ${n.key} already set`);Rt.isScalar(i.value)&&F_.isScalarValue(n.value)?i.value.value=n.value:i.value=n.value}else if(s){let o=this.items.findIndex(a=>s(n,a)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(t){let r=En(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let i=En(this.items,t)?.value;return(!r&&Rt.isScalar(i)?i.value:i)??void 0}has(t){return!!En(this.items,t)}set(t,r){this.add(new ms.Pair(t,r),!0)}toJSON(t,r,n){let i=n?new n:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(i);for(let s of this.items)M_.addPairToJSMap(r,i,s);return i}toString(t,r,n){if(!t)return JSON.stringify(this);for(let i of this.items)if(!Rt.isPair(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),q_.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:n,onComment:r})}};za.YAMLMap=Ha;za.findPair=En});var Tr=v(Dp=>{"use strict";var V_=L(),Tp=At(),B_={collection:"map",default:!0,nodeClass:Tp.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return V_.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>Tp.YAMLMap.from(e,t,r)};Dp.map=B_});var Ct=v(Op=>{"use strict";var K_=vn(),U_=Ga(),G_=es(),ys=L(),H_=se(),z_=kt(),Wa=class extends G_.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(ys.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=gs(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let n=gs(t);if(typeof n!="number")return;let i=this.items[n];return!r&&ys.isScalar(i)?i.value:i}has(t){let r=gs(t);return typeof r=="number"&&r<this.items.length}set(t,r){let n=gs(t);if(typeof n!="number")throw new Error(`Expected a valid index, not ${t}.`);let i=this.items[n];ys.isScalar(i)&&H_.isScalarValue(r)?i.value=r:this.items[n]=r}toJSON(t,r){let n=[];r?.onCreate&&r.onCreate(n);let i=0;for(let s of this.items)n.push(z_.toJS(s,String(i++),r));return n}toString(t,r,n){return t?U_.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:n,onComment:r}):JSON.stringify(this)}static from(t,r,n){let{replacer:i}=n,s=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let a of r){if(typeof i=="function"){let c=r instanceof Set?a:String(o++);a=i.call(r,c,a)}s.items.push(K_.createNode(a,void 0,n))}}return s}};function gs(e){let t=ys.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Op.YAMLSeq=Wa});var Dr=v(jp=>{"use strict";var W_=L(),xp=Ct(),Q_={collection:"seq",default:!0,nodeClass:xp.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return W_.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>xp.YAMLSeq.from(e,t,r)};jp.seq=Q_});var In=v(Np=>{"use strict";var J_=_n(),Y_={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,n){return t=Object.assign({actualString:!0},t),J_.stringifyString(e,t,r,n)}};Np.string=Y_});var vs=v(Lp=>{"use strict";var qp=se(),Mp={identify:e=>e==null,createNode:()=>new qp.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new qp.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Mp.test.test(e)?e:t.options.nullStr};Lp.nullTag=Mp});var Qa=v(Vp=>{"use strict";var X_=se(),Fp={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new X_.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&Fp.test.test(e)){let n=e[0]==="t"||e[0]==="T";if(t===n)return e}return t?r.options.trueStr:r.options.falseStr}};Vp.boolTag=Fp});var Or=v(Bp=>{"use strict";function Z_({format:e,minFractionDigits:t,tag:r,value:n}){if(typeof n=="bigint")return String(n);let i=typeof n=="number"?n:Number(n);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let s=Object.is(n,-0)?"-0":JSON.stringify(n);if(!e&&t&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let a=t-(s.length-o-1);for(;a-- >0;)s+="0"}return s}Bp.stringifyNumber=Z_});var Ya=v(ws=>{"use strict";var e0=se(),Ja=Or(),t0={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ja.stringifyNumber},r0={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(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Ja.stringifyNumber(e)}},n0={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new e0.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:Ja.stringifyNumber};ws.float=n0;ws.floatExp=r0;ws.floatNaN=t0});var Za=v(Ss=>{"use strict";var Kp=Or(),bs=e=>typeof e=="bigint"||Number.isInteger(e),Xa=(e,t,r,{intAsBigInt:n})=>n?BigInt(e):parseInt(e.substring(t),r);function Up(e,t,r){let{value:n}=e;return bs(n)&&n>=0?r+n.toString(t):Kp.stringifyNumber(e)}var i0={identify:e=>bs(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>Xa(e,2,8,r),stringify:e=>Up(e,8,"0o")},s0={identify:bs,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>Xa(e,0,10,r),stringify:Kp.stringifyNumber},o0={identify:e=>bs(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>Xa(e,2,16,r),stringify:e=>Up(e,16,"0x")};Ss.int=s0;Ss.intHex=o0;Ss.intOct=i0});var Hp=v(Gp=>{"use strict";var a0=Tr(),c0=vs(),l0=Dr(),u0=In(),d0=Qa(),ec=Ya(),tc=Za(),f0=[a0.map,l0.seq,u0.string,c0.nullTag,d0.boolTag,tc.intOct,tc.int,tc.intHex,ec.floatNaN,ec.floatExp,ec.float];Gp.schema=f0});var Qp=v(Wp=>{"use strict";var p0=se(),h0=Tr(),m0=Dr();function zp(e){return typeof e=="bigint"||Number.isInteger(e)}var _s=({value:e})=>JSON.stringify(e),g0=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:_s},{identify:e=>e==null,createNode:()=>new p0.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:_s},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:_s},{identify:zp,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>zp(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:_s}],y0={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},v0=[h0.map,m0.seq].concat(g0,y0);Wp.schema=v0});var nc=v(Jp=>{"use strict";var Pn=Gi("buffer"),rc=se(),w0=_n(),b0={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Pn.Buffer=="function")return Pn.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),n=new Uint8Array(r.length);for(let i=0;i<r.length;++i)n[i]=r.charCodeAt(i);return n}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},n,i,s){if(!r)return"";let o=r,a;if(typeof Pn.Buffer=="function")a=o instanceof Pn.Buffer?o.toString("base64"):Pn.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=rc.Scalar.BLOCK_LITERAL),t!==rc.Scalar.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),l=Math.ceil(a.length/c),d=new Array(l);for(let u=0,h=0;u<l;++u,h+=c)d[u]=a.substr(h,c);a=d.join(t===rc.Scalar.BLOCK_LITERAL?`
54
+ `:" ")}return w0.stringifyString({comment:e,type:t,value:a},n,i,s)}};Jp.binary=b0});var Es=v($s=>{"use strict";var ks=L(),ic=Pt(),S0=se(),_0=Ct();function Yp(e,t){if(ks.isSeq(e))for(let r=0;r<e.items.length;++r){let n=e.items[r];if(!ks.isPair(n)){if(ks.isMap(n)){n.items.length>1&&t("Each pair must have its own sequence indicator");let i=n.items[0]||new ic.Pair(new S0.Scalar(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore}
55
+ ${i.key.commentBefore}`:n.commentBefore),n.comment){let s=i.value??i.key;s.comment=s.comment?`${n.comment}
56
+ ${s.comment}`:n.comment}n=i}e.items[r]=ks.isPair(n)?n:new ic.Pair(n)}}else t("Expected a sequence for this tag");return e}function Xp(e,t,r){let{replacer:n}=r,i=new _0.YAMLSeq(e);i.tag="tag:yaml.org,2002:pairs";let s=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof n=="function"&&(o=n.call(t,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;i.items.push(ic.createPair(a,c,r))}return i}var k0={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Yp,createNode:Xp};$s.createPairs=Xp;$s.pairs=k0;$s.resolvePairs=Yp});var ac=v(oc=>{"use strict";var Zp=L(),sc=kt(),Rn=At(),$0=Ct(),eh=Es(),Zt=class e extends $0.YAMLSeq{constructor(){super(),this.add=Rn.YAMLMap.prototype.add.bind(this),this.delete=Rn.YAMLMap.prototype.delete.bind(this),this.get=Rn.YAMLMap.prototype.get.bind(this),this.has=Rn.YAMLMap.prototype.has.bind(this),this.set=Rn.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let n=new Map;r?.onCreate&&r.onCreate(n);for(let i of this.items){let s,o;if(Zp.isPair(i)?(s=sc.toJS(i.key,"",r),o=sc.toJS(i.value,s,r)):s=sc.toJS(i,"",r),n.has(s))throw new Error("Ordered maps must not include duplicate keys");n.set(s,o)}return n}static from(t,r,n){let i=eh.createPairs(t,r,n),s=new this;return s.items=i.items,s}};Zt.tag="tag:yaml.org,2002:omap";var E0={collection:"seq",identify:e=>e instanceof Map,nodeClass:Zt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=eh.resolvePairs(e,t),n=[];for(let{key:i}of r.items)Zp.isScalar(i)&&(n.includes(i.value)?t(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new Zt,r)},createNode:(e,t,r)=>Zt.from(e,t,r)};oc.YAMLOMap=Zt;oc.omap=E0});var sh=v(cc=>{"use strict";var th=se();function rh({value:e,source:t},r){return t&&(e?nh:ih).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var nh={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new th.Scalar(!0),stringify:rh},ih={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new th.Scalar(!1),stringify:rh};cc.falseTag=ih;cc.trueTag=nh});var oh=v(Is=>{"use strict";var I0=se(),lc=Or(),P0={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:lc.stringifyNumber},R0={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(e){let t=Number(e.value);return isFinite(t)?t.toExponential():lc.stringifyNumber(e)}},A0={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new I0.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let n=e.substring(r+1).replace(/_/g,"");n[n.length-1]==="0"&&(t.minFractionDigits=n.length)}return t},stringify:lc.stringifyNumber};Is.float=A0;Is.floatExp=R0;Is.floatNaN=P0});var ch=v(Cn=>{"use strict";var ah=Or(),An=e=>typeof e=="bigint"||Number.isInteger(e);function Ps(e,t,r,{intAsBigInt:n}){let i=e[0];if((i==="-"||i==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),n){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return i==="-"?BigInt(-1)*o:o}let s=parseInt(e,r);return i==="-"?-1*s:s}function uc(e,t,r){let{value:n}=e;if(An(n)){let i=n.toString(t);return n<0?"-"+r+i.substr(1):r+i}return ah.stringifyNumber(e)}var C0={identify:An,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Ps(e,2,2,r),stringify:e=>uc(e,2,"0b")},T0={identify:An,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Ps(e,1,8,r),stringify:e=>uc(e,8,"0")},D0={identify:An,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Ps(e,0,10,r),stringify:ah.stringifyNumber},O0={identify:An,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Ps(e,2,16,r),stringify:e=>uc(e,16,"0x")};Cn.int=D0;Cn.intBin=C0;Cn.intHex=O0;Cn.intOct=T0});var fc=v(dc=>{"use strict";var Cs=L(),Rs=Pt(),As=At(),er=class e extends As.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Cs.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Rs.Pair(t.key,null):r=new Rs.Pair(t,null),As.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let n=As.findPair(this.items,t);return!r&&Cs.isPair(n)?Cs.isScalar(n.key)?n.key.value:n.key:n}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let n=As.findPair(this.items,t);n&&!r?this.items.splice(this.items.indexOf(n),1):!n&&r&&this.items.push(new Rs.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,n){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,n);throw new Error("Set items must all have null values")}static from(t,r,n){let{replacer:i}=n,s=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof i=="function"&&(o=i.call(r,o,o)),s.items.push(Rs.createPair(o,null,n));return s}};er.tag="tag:yaml.org,2002:set";var x0={collection:"map",identify:e=>e instanceof Set,nodeClass:er,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>er.from(e,t,r),resolve(e,t){if(Cs.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new er,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};dc.YAMLSet=er;dc.set=x0});var hc=v(Ts=>{"use strict";var j0=Or();function pc(e,t){let r=e[0],n=r==="-"||r==="+"?e.substring(1):e,i=o=>t?BigInt(o):Number(o),s=n.replace(/_/g,"").split(":").reduce((o,a)=>o*i(60)+i(a),i(0));return r==="-"?i(-1)*s:s}function lh(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return j0.stringifyNumber(e);let n="";t<0&&(n="-",t*=r(-1));let i=r(60),s=[t%i];return t<60?s.unshift(0):(t=(t-s[0])/i,s.unshift(t%i),t>=60&&(t=(t-s[0])/i,s.unshift(t))),n+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var N0={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>pc(e,r),stringify:lh},q0={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=>pc(e,!1),stringify:lh},uh={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){let t=e.match(uh.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,n,i,s,o,a]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,n-1,i,s||0,o||0,a||0,c),d=t[8];if(d&&d!=="Z"){let u=pc(d,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Ts.floatTime=q0;Ts.intTime=N0;Ts.timestamp=uh});var ph=v(fh=>{"use strict";var M0=Tr(),L0=vs(),F0=Dr(),V0=In(),B0=nc(),dh=sh(),mc=oh(),Ds=ch(),K0=us(),U0=ac(),G0=Es(),H0=fc(),gc=hc(),z0=[M0.map,F0.seq,V0.string,L0.nullTag,dh.trueTag,dh.falseTag,Ds.intBin,Ds.intOct,Ds.int,Ds.intHex,mc.floatNaN,mc.floatExp,mc.float,B0.binary,K0.merge,U0.omap,G0.pairs,H0.set,gc.intTime,gc.floatTime,gc.timestamp];fh.schema=z0});var kh=v(wc=>{"use strict";var yh=Tr(),W0=vs(),vh=Dr(),Q0=In(),J0=Qa(),yc=Ya(),vc=Za(),Y0=Hp(),X0=Qp(),wh=nc(),Tn=us(),bh=ac(),Sh=Es(),hh=ph(),_h=fc(),Os=hc(),mh=new Map([["core",Y0.schema],["failsafe",[yh.map,vh.seq,Q0.string]],["json",X0.schema],["yaml11",hh.schema],["yaml-1.1",hh.schema]]),gh={binary:wh.binary,bool:J0.boolTag,float:yc.float,floatExp:yc.floatExp,floatNaN:yc.floatNaN,floatTime:Os.floatTime,int:vc.int,intHex:vc.intHex,intOct:vc.intOct,intTime:Os.intTime,map:yh.map,merge:Tn.merge,null:W0.nullTag,omap:bh.omap,pairs:Sh.pairs,seq:vh.seq,set:_h.set,timestamp:Os.timestamp},Z0={"tag:yaml.org,2002:binary":wh.binary,"tag:yaml.org,2002:merge":Tn.merge,"tag:yaml.org,2002:omap":bh.omap,"tag:yaml.org,2002:pairs":Sh.pairs,"tag:yaml.org,2002:set":_h.set,"tag:yaml.org,2002:timestamp":Os.timestamp};function ek(e,t,r){let n=mh.get(t);if(n&&!e)return r&&!n.includes(Tn.merge)?n.concat(Tn.merge):n.slice();let i=n;if(!i)if(Array.isArray(e))i=[];else{let s=Array.from(mh.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${s} or define customTags array`)}if(Array.isArray(e))for(let s of e)i=i.concat(s);else typeof e=="function"&&(i=e(i.slice()));return r&&(i=i.concat(Tn.merge)),i.reduce((s,o)=>{let a=typeof o=="string"?gh[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(gh).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}wc.coreKnownTags=Z0;wc.getTags=ek});var _c=v($h=>{"use strict";var bc=L(),tk=Tr(),rk=Dr(),nk=In(),xs=kh(),ik=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Sc=class e{constructor({compat:t,customTags:r,merge:n,resolveKnownTags:i,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(t)?xs.getTags(t,"compat"):t?xs.getTags(null,t):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?xs.coreKnownTags:{},this.tags=xs.getTags(r,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,bc.MAP,{value:tk.map}),Object.defineProperty(this,bc.SCALAR,{value:nk.string}),Object.defineProperty(this,bc.SEQ,{value:rk.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?ik:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};$h.Schema=Sc});var Ih=v(Eh=>{"use strict";var sk=L(),kc=kn(),Dn=wn();function ok(e,t){let r=[],n=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),n=!0):e.directives.docStart&&(n=!0)}n&&r.push("---");let i=kc.createStringifyContext(e,t),{commentString:s}=i.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=s(e.commentBefore);r.unshift(Dn.indentComment(c,""))}let o=!1,a=null;if(e.contents){if(sk.isNode(e.contents)){if(e.contents.spaceBefore&&n&&r.push(""),e.contents.commentBefore){let d=s(e.contents.commentBefore);r.push(Dn.indentComment(d,""))}i.forceBlockIndent=!!e.comment,a=e.contents.comment}let c=a?void 0:()=>o=!0,l=kc.stringify(e.contents,i,()=>a=null,c);a&&(l+=Dn.lineComment(l,"",s(a))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(kc.stringify(e.contents,i));if(e.directives?.docEnd)if(e.comment){let c=s(e.comment);c.includes(`
57
+ `)?(r.push("..."),r.push(Dn.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&r[r.length-1]!==""&&r.push(""),r.push(Dn.indentComment(s(c),"")))}return r.join(`
58
+ `)+`
59
+ `}Eh.stringifyDocument=ok});var On=v(Ph=>{"use strict";var ak=yn(),xr=es(),Te=L(),ck=Pt(),lk=kt(),uk=_c(),dk=Ih(),$c=Ji(),fk=Ra(),pk=vn(),Ec=Pa(),Ic=class e{constructor(t,r,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Te.NODE_TYPE,{value:Te.DOC});let i=null;typeof r=="function"||Array.isArray(r)?i=r:n===void 0&&r&&(n=r,r=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=s;let{version:o}=s;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Ec.Directives({version:o}),this.setSchema(o,n),this.contents=t===void 0?null:this.createNode(t,i,n)}clone(){let t=Object.create(e.prototype,{[Te.NODE_TYPE]:{value:Te.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=Te.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){jr(this.contents)&&this.contents.add(t)}addIn(t,r){jr(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let n=$c.anchorNames(this);t.anchor=!r||n.has(r)?$c.findNewAnchor(r||"a",n):r}return new ak.Alias(t.anchor)}createNode(t,r,n){let i;if(typeof r=="function")t=r.call({"":t},"",t),i=r;else if(Array.isArray(r)){let g=w=>typeof w=="number"||w instanceof String||w instanceof Number,y=r.filter(g).map(String);y.length>0&&(r=r.concat(y)),i=r}else n===void 0&&r&&(n=r,r=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:d}=n??{},{onAnchor:u,setAnchors:h,sourceObjects:m}=$c.createNodeAnchors(this,o||"a"),p={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:m},f=pk.createNode(t,d,p);return a&&Te.isCollection(f)&&(f.flow=!0),h(),f}createPair(t,r,n={}){let i=this.createNode(t,null,n),s=this.createNode(r,null,n);return new ck.Pair(i,s)}delete(t){return jr(this.contents)?this.contents.delete(t):!1}deleteIn(t){return xr.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):jr(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return Te.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return xr.isEmptyPath(t)?!r&&Te.isScalar(this.contents)?this.contents.value:this.contents:Te.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return Te.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return xr.isEmptyPath(t)?this.contents!==void 0:Te.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=xr.collectionFromPath(this.schema,[t],r):jr(this.contents)&&this.contents.set(t,r)}setIn(t,r){xr.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=xr.collectionFromPath(this.schema,Array.from(t),r):jr(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let n;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Ec.Directives({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Ec.Directives({version:t}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let i=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(n)this.schema=new uk.Schema(Object.assign(n,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:n,maxAliasCount:i,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!t,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},c=lk.toJS(this.contents,r??"",a);if(typeof s=="function")for(let{count:l,res:d}of a.anchors.values())s(d,l);return typeof o=="function"?fk.applyReviver(o,{"":c},"",c):c}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return dk.stringifyDocument(this,t)}};function jr(e){if(Te.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Ph.Document=Ic});var Nn=v(jn=>{"use strict";var xn=class extends Error{constructor(t,r,n,i){super(),this.name=t,this.code=n,this.message=i,this.pos=r}},Pc=class extends xn{constructor(t,r,n){super("YAMLParseError",t,r,n)}},Rc=class extends xn{constructor(t,r,n){super("YAMLWarning",t,r,n)}},hk=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(a=>t.linePos(a));let{line:n,col:i}=r.linePos[0];r.message+=` at line ${n}, column ${i}`;let s=i-1,o=e.substring(t.lineStarts[n-1],t.lineStarts[n]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="\u2026"+o.substring(a),s-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,s))){let a=e.substring(t.lineStarts[n-2],t.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
60
+ `),o=a+o}if(/[^ ]/.test(o)){let a=1,c=r.linePos[1];c?.line===n&&c.col>i&&(a=Math.max(1,Math.min(c.col-i,80-s)));let l=" ".repeat(s)+"^".repeat(a);r.message+=`:
61
+
62
+ ${o}
63
+ ${l}
64
+ `}};jn.YAMLError=xn;jn.YAMLParseError=Pc;jn.YAMLWarning=Rc;jn.prettifyError=hk});var qn=v(Rh=>{"use strict";function mk(e,{flow:t,indicator:r,next:n,offset:i,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,d=a,u="",h="",m=!1,p=!1,f=null,g=null,y=null,w=null,b=null,$=null,S=null;for(let _ of e)switch(p&&(_.type!=="space"&&_.type!=="newline"&&_.type!=="comma"&&s(_.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p=!1),f&&(l&&_.type!=="comment"&&_.type!=="newline"&&s(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),f=null),_.type){case"space":!t&&(r!=="doc-start"||n?.type!=="flow-collection")&&_.source.includes(" ")&&(f=_),d=!0;break;case"comment":{d||s(_,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let q=_.source.substring(1)||" ";u?u+=h+q:u=q,h="",l=!1;break}case"newline":l?u?u+=_.source:(!$||r!=="seq-item-ind")&&(c=!0):h+=_.source,l=!0,m=!0,(g||y)&&(w=_),d=!0;break;case"anchor":g&&s(_,"MULTIPLE_ANCHORS","A node can have at most one anchor"),_.source.endsWith(":")&&s(_.offset+_.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=_,S??(S=_.offset),l=!1,d=!1,p=!0;break;case"tag":{y&&s(_,"MULTIPLE_TAGS","A node can have at most one tag"),y=_,S??(S=_.offset),l=!1,d=!1,p=!0;break}case r:(g||y)&&s(_,"BAD_PROP_ORDER",`Anchors and tags must be after the ${_.source} indicator`),$&&s(_,"UNEXPECTED_TOKEN",`Unexpected ${_.source} in ${t??"collection"}`),$=_,l=r==="seq-item-ind"||r==="explicit-key-ind",d=!1;break;case"comma":if(t){b&&s(_,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),b=_,l=!1,d=!1;break}default:s(_,"UNEXPECTED_TOKEN",`Unexpected ${_.type} token`),l=!1,d=!1}let I=e[e.length-1],k=I?I.offset+I.source.length:i;return p&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&s(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),f&&(l&&f.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&s(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:b,found:$,spaceBefore:c,comment:u,hasNewline:m,anchor:g,tag:y,newlineAfterProp:w,end:k,start:S??k}}Rh.resolveProps=mk});var js=v(Ah=>{"use strict";function Ac(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
65
+ `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(Ac(t.key)||Ac(t.value))return!0}return!1;default:return!0}}Ah.containsNewline=Ac});var Cc=v(Ch=>{"use strict";var gk=js();function yk(e,t,r){if(t?.type==="flow-collection"){let n=t.end[0];n.indent===e&&(n.source==="]"||n.source==="}")&&gk.containsNewline(t)&&r(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Ch.flowIndentCheck=yk});var Tc=v(Dh=>{"use strict";var Th=L();function vk(e,t,r){let{uniqueKeys:n}=e.options;if(n===!1)return!1;let i=typeof n=="function"?n:(s,o)=>s===o||Th.isScalar(s)&&Th.isScalar(o)&&s.value===o.value;return t.some(s=>i(s.key,r))}Dh.mapIncludes=vk});var Mh=v(qh=>{"use strict";var Oh=Pt(),wk=At(),xh=qn(),bk=js(),jh=Cc(),Sk=Tc(),Nh="All mapping items must start at the same column";function _k({composeNode:e,composeEmptyNode:t},r,n,i,s){let o=s?.nodeClass??wk.YAMLMap,a=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=n.offset,l=null;for(let d of n.items){let{start:u,key:h,sep:m,value:p}=d,f=xh.resolveProps(u,{indicator:"explicit-key-ind",next:h??m?.[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),g=!f.found;if(g){if(h&&(h.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in h&&h.indent!==n.indent&&i(c,"BAD_INDENT",Nh)),!f.anchor&&!f.tag&&!m){l=f.end,f.comment&&(a.comment?a.comment+=`
66
+ `+f.comment:a.comment=f.comment);continue}(f.newlineAfterProp||bk.containsNewline(h))&&i(h??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else f.found?.indent!==n.indent&&i(c,"BAD_INDENT",Nh);r.atKey=!0;let y=f.end,w=h?e(r,h,f,i):t(r,y,u,null,f,i);r.schema.compat&&jh.flowIndentCheck(n.indent,h,i),r.atKey=!1,Sk.mapIncludes(r,a.items,w)&&i(y,"DUPLICATE_KEY","Map keys must be unique");let b=xh.resolveProps(m??[],{indicator:"map-value-ind",next:p,offset:w.range[2],onError:i,parentIndent:n.indent,startOnNewline:!h||h.type==="block-scalar"});if(c=b.end,b.found){g&&(p?.type==="block-map"&&!b.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&f.start<b.found.offset-1024&&i(w.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let $=p?e(r,p,b,i):t(r,c,m,null,b,i);r.schema.compat&&jh.flowIndentCheck(n.indent,p,i),c=$.range[2];let S=new Oh.Pair(w,$);r.options.keepSourceTokens&&(S.srcToken=d),a.items.push(S)}else{g&&i(w.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),b.comment&&(w.comment?w.comment+=`
67
+ `+b.comment:w.comment=b.comment);let $=new Oh.Pair(w);r.options.keepSourceTokens&&($.srcToken=d),a.items.push($)}}return l&&l<c&&i(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,c,l??c],a}qh.resolveBlockMap=_k});var Fh=v(Lh=>{"use strict";var kk=Ct(),$k=qn(),Ek=Cc();function Ik({composeNode:e,composeEmptyNode:t},r,n,i,s){let o=s?.nodeClass??kk.YAMLSeq,a=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=n.offset,l=null;for(let{start:d,value:u}of n.items){let h=$k.resolveProps(d,{indicator:"seq-item-ind",next:u,offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0});if(!h.found)if(h.anchor||h.tag||u)u?.type==="block-seq"?i(h.end,"BAD_INDENT","All sequence items must start at the same column"):i(c,"MISSING_CHAR","Sequence item without - indicator");else{l=h.end,h.comment&&(a.comment=h.comment);continue}let m=u?e(r,u,h,i):t(r,h.end,d,null,h,i);r.schema.compat&&Ek.flowIndentCheck(n.indent,u,i),c=m.range[2],a.items.push(m)}return a.range=[n.offset,c,l??c],a}Lh.resolveBlockSeq=Ik});var Nr=v(Vh=>{"use strict";function Pk(e,t,r,n){let i="";if(e){let s=!1,o="";for(let a of e){let{source:c,type:l}=a;switch(l){case"space":s=!0;break;case"comment":{r&&!s&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=c.substring(1)||" ";i?i+=o+d:i=d,o="";break}case"newline":i&&(o+=c),s=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:i,offset:t}}Vh.resolveEnd=Pk});var Gh=v(Uh=>{"use strict";var Rk=L(),Ak=Pt(),Bh=At(),Ck=Ct(),Tk=Nr(),Kh=qn(),Dk=js(),Ok=Tc(),Dc="Block collections are not allowed within flow collections",Oc=e=>e&&(e.type==="block-map"||e.type==="block-seq");function xk({composeNode:e,composeEmptyNode:t},r,n,i,s){let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?Bh.YAMLMap:Ck.YAMLSeq),l=new c(r.schema);l.flow=!0;let d=r.atRoot;d&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let u=n.offset+n.start.source.length;for(let g=0;g<n.items.length;++g){let y=n.items[g],{start:w,key:b,sep:$,value:S}=y,I=Kh.resolveProps(w,{flow:a,indicator:"explicit-key-ind",next:b??$?.[0],offset:u,onError:i,parentIndent:n.indent,startOnNewline:!1});if(!I.found){if(!I.anchor&&!I.tag&&!$&&!S){g===0&&I.comma?i(I.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):g<n.items.length-1&&i(I.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),I.comment&&(l.comment?l.comment+=`
68
+ `+I.comment:l.comment=I.comment),u=I.end;continue}!o&&r.options.strict&&Dk.containsNewline(b)&&i(b,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(g===0)I.comma&&i(I.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(I.comma||i(I.start,"MISSING_CHAR",`Missing , between ${a} items`),I.comment){let k="";e:for(let _ of w)switch(_.type){case"comma":case"space":break;case"comment":k=_.source.substring(1);break e;default:break e}if(k){let _=l.items[l.items.length-1];Rk.isPair(_)&&(_=_.value??_.key),_.comment?_.comment+=`
69
+ `+k:_.comment=k,I.comment=I.comment.substring(k.length+1)}}if(!o&&!$&&!I.found){let k=S?e(r,S,I,i):t(r,I.end,$,null,I,i);l.items.push(k),u=k.range[2],Oc(S)&&i(k.range,"BLOCK_IN_FLOW",Dc)}else{r.atKey=!0;let k=I.end,_=b?e(r,b,I,i):t(r,k,w,null,I,i);Oc(b)&&i(_.range,"BLOCK_IN_FLOW",Dc),r.atKey=!1;let q=Kh.resolveProps($??[],{flow:a,indicator:"map-value-ind",next:S,offset:_.range[2],onError:i,parentIndent:n.indent,startOnNewline:!1});if(q.found){if(!o&&!I.found&&r.options.strict){if($)for(let te of $){if(te===q.found)break;if(te.type==="newline"){i(te,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}I.start<q.found.offset-1024&&i(q.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else S&&("source"in S&&S.source?.[0]===":"?i(S,"MISSING_CHAR",`Missing space after : in ${a}`):i(q.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let Q=S?e(r,S,q,i):q.found?t(r,q.end,$,null,q,i):null;Q?Oc(S)&&i(Q.range,"BLOCK_IN_FLOW",Dc):q.comment&&(_.comment?_.comment+=`
70
+ `+q.comment:_.comment=q.comment);let re=new Ak.Pair(_,Q);if(r.options.keepSourceTokens&&(re.srcToken=y),o){let te=l;Ok.mapIncludes(r,te.items,_)&&i(k,"DUPLICATE_KEY","Map keys must be unique"),te.items.push(re)}else{let te=new Bh.YAMLMap(r.schema);te.flow=!0,te.items.push(re);let Jt=(Q??_).range;te.range=[_.range[0],Jt[1],Jt[2]],l.items.push(te)}u=Q?Q.range[2]:q.end}}let h=o?"}":"]",[m,...p]=n.end,f=u;if(m?.source===h)f=m.offset+m.source.length;else{let g=a[0].toUpperCase()+a.substring(1),y=d?`${g} must end with a ${h}`:`${g} in block collection must be sufficiently indented and end with a ${h}`;i(u,d?"MISSING_CHAR":"BAD_INDENT",y),m&&m.source.length!==1&&p.unshift(m)}if(p.length>0){let g=Tk.resolveEnd(p,f,r.options.strict,i);g.comment&&(l.comment?l.comment+=`
71
+ `+g.comment:l.comment=g.comment),l.range=[n.offset,f,g.offset]}else l.range=[n.offset,f,f];return l}Uh.resolveFlowCollection=xk});var zh=v(Hh=>{"use strict";var jk=L(),Nk=se(),qk=At(),Mk=Ct(),Lk=Mh(),Fk=Fh(),Vk=Gh();function xc(e,t,r,n,i,s){let o=r.type==="block-map"?Lk.resolveBlockMap(e,t,r,n,s):r.type==="block-seq"?Fk.resolveBlockSeq(e,t,r,n,s):Vk.resolveFlowCollection(e,t,r,n,s),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function Bk(e,t,r,n,i){let s=n.tag,o=s?t.directives.tagName(s.source,h=>i(s,"TAG_RESOLVE_FAILED",h)):null;if(r.type==="block-seq"){let{anchor:h,newlineAfterProp:m}=n,p=h&&s?h.offset>s.offset?h:s:h??s;p&&(!m||m.offset<p.offset)&&i(p,"MISSING_CHAR","Missing newline after block sequence props")}let a=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!s||!o||o==="!"||o===qk.YAMLMap.tagName&&a==="map"||o===Mk.YAMLSeq.tagName&&a==="seq")return xc(e,t,r,i,o);let c=t.schema.tags.find(h=>h.tag===o&&h.collection===a);if(!c){let h=t.schema.knownTags[o];if(h?.collection===a)t.schema.tags.push(Object.assign({},h,{default:!1})),c=h;else return h?i(s,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${h.collection??"scalar"}`,!0):i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),xc(e,t,r,i,o)}let l=xc(e,t,r,i,o,c),d=c.resolve?.(l,h=>i(s,"TAG_RESOLVE_FAILED",h),t.options)??l,u=jk.isNode(d)?d:new Nk.Scalar(d);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}Hh.composeCollection=Bk});var Nc=v(Wh=>{"use strict";var jc=se();function Kk(e,t,r){let n=t.offset,i=Uk(t,e.options.strict,r);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};let s=i.mode===">"?jc.Scalar.BLOCK_FOLDED:jc.Scalar.BLOCK_LITERAL,o=t.source?Gk(t.source):[],a=o.length;for(let f=o.length-1;f>=0;--f){let g=o[f][1];if(g===""||g==="\r")a=f;else break}if(a===0){let f=i.chomp==="+"&&o.length>0?`
72
+ `.repeat(Math.max(1,o.length-1)):"",g=n+i.length;return t.source&&(g+=t.source.length),{value:f,type:s,comment:i.comment,range:[n,g,g]}}let c=t.indent+i.indent,l=t.offset+i.length,d=0;for(let f=0;f<a;++f){let[g,y]=o[f];if(y===""||y==="\r")i.indent===0&&g.length>c&&(c=g.length);else{g.length<c&&r(l+g.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),i.indent===0&&(c=g.length),d=f,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=g.length+y.length+1}for(let f=o.length-1;f>=a;--f)o[f][0].length>c&&(a=f+1);let u="",h="",m=!1;for(let f=0;f<d;++f)u+=o[f][0].slice(c)+`
73
+ `;for(let f=d;f<a;++f){let[g,y]=o[f];l+=g.length+y.length+1;let w=y[y.length-1]==="\r";if(w&&(y=y.slice(0,-1)),y&&g.length<c){let $=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;r(l-y.length-(w?2:1),"BAD_INDENT",$),g=""}s===jc.Scalar.BLOCK_LITERAL?(u+=h+g.slice(c)+y,h=`
74
+ `):g.length>c||y[0]===" "?(h===" "?h=`
75
+ `:!m&&h===`
76
+ `&&(h=`
77
+
78
+ `),u+=h+g.slice(c)+y,h=`
79
+ `,m=!0):y===""?h===`
80
+ `?u+=`
81
+ `:h=`
82
+ `:(u+=h+y,h=" ",m=!1)}switch(i.chomp){case"-":break;case"+":for(let f=a;f<o.length;++f)u+=`
83
+ `+o[f][0].slice(c);u[u.length-1]!==`
84
+ `&&(u+=`
85
+ `);break;default:u+=`
86
+ `}let p=n+i.length+t.source.length;return{value:u,type:s,comment:i.comment,range:[n,p,p]}}function Uk({offset:e,props:t},r,n){if(t[0].type!=="block-scalar-header")return n(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:i}=t[0],s=i[0],o=0,a="",c=-1;for(let h=1;h<i.length;++h){let m=i[h];if(!a&&(m==="-"||m==="+"))a=m;else{let p=Number(m);!o&&p?o=p:c===-1&&(c=e+h)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let l=!1,d="",u=i.length;for(let h=1;h<t.length;++h){let m=t[h];switch(m.type){case"space":l=!0;case"newline":u+=m.source.length;break;case"comment":r&&!l&&n(m,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=m.source.length,d=m.source.substring(1);break;case"error":n(m,"UNEXPECTED_TOKEN",m.message),u+=m.source.length;break;default:{let p=`Unexpected token in block scalar header: ${m.type}`;n(m,"UNEXPECTED_TOKEN",p);let f=m.source;f&&typeof f=="string"&&(u+=f.length)}}}return{mode:s,indent:o,chomp:a,comment:d,length:u}}function Gk(e){let t=e.split(/\n( *)/),r=t[0],n=r.match(/^( *)/),s=[n?.[1]?[n[1],r.slice(n[1].length)]:["",r]];for(let o=1;o<t.length;o+=2)s.push([t[o],t[o+1]]);return s}Wh.resolveBlockScalar=Kk});var Mc=v(Jh=>{"use strict";var qc=se(),Hk=Nr();function zk(e,t,r){let{offset:n,type:i,source:s,end:o}=e,a,c,l=(h,m,p)=>r(n+h,m,p);switch(i){case"scalar":a=qc.Scalar.PLAIN,c=Wk(s,l);break;case"single-quoted-scalar":a=qc.Scalar.QUOTE_SINGLE,c=Qk(s,l);break;case"double-quoted-scalar":a=qc.Scalar.QUOTE_DOUBLE,c=Jk(s,l);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[n,n+s.length,n+s.length]}}let d=n+s.length,u=Hk.resolveEnd(o,d,t,r);return{value:c,type:a,comment:u.comment,range:[n,d,u.offset]}}function Wk(e,t){let r="";switch(e[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}return r&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),Qh(e)}function Qk(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Qh(e.slice(1,-1)).replace(/''/g,"'")}function Qh(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
87
+ `,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
88
+ `,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=t.exec(e);if(!n)return e;let i=n[1],s=" ",o=t.lastIndex;for(r.lastIndex=o;n=r.exec(e);)n[1]===""?s===`
89
+ `?i+=s:s=`
90
+ `:(i+=s+n[1],s=" "),o=r.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=o,n=a.exec(e),i+s+(n?.[1]??"")}function Jk(e,t){let r="";for(let n=1;n<e.length-1;++n){let i=e[n];if(!(i==="\r"&&e[n+1]===`
91
+ `))if(i===`
92
+ `){let{fold:s,offset:o}=Yk(e,n);r+=s,n=o}else if(i==="\\"){let s=e[++n],o=Xk[s];if(o)r+=o;else if(s===`
93
+ `)for(s=e[n+1];s===" "||s===" ";)s=e[++n+1];else if(s==="\r"&&e[n+1]===`
94
+ `)for(s=e[++n+1];s===" "||s===" ";)s=e[++n+1];else if(s==="x"||s==="u"||s==="U"){let a=s==="x"?2:s==="u"?4:8;r+=Zk(e,n+1,a,t),n+=a}else{let a=e.substr(n-1,2);t(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),r+=a}}else if(i===" "||i===" "){let s=n,o=e[n+1];for(;o===" "||o===" ";)o=e[++n+1];o!==`
95
+ `&&!(o==="\r"&&e[n+2]===`
96
+ `)&&(r+=n>s?e.slice(s,n+1):i)}else r+=i}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function Yk(e,t){let r="",n=e[t+1];for(;(n===" "||n===" "||n===`
97
+ `||n==="\r")&&!(n==="\r"&&e[t+2]!==`
98
+ `);)n===`
99
+ `&&(r+=`
100
+ `),t+=1,n=e[t+1];return r||(r=" "),{fold:r,offset:t}}var Xk={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
101
+ `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Zk(e,t,r,n){let i=e.substr(t,r),o=i.length===r&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(o)}catch{let a=e.substr(t-2,r+2);return n(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}Jh.resolveFlowScalar=zk});var Zh=v(Xh=>{"use strict";var tr=L(),Yh=se(),e$=Nc(),t$=Mc();function r$(e,t,r,n){let{value:i,type:s,comment:o,range:a}=t.type==="block-scalar"?e$.resolveBlockScalar(e,t,n):t$.resolveFlowScalar(t,e.options.strict,n),c=r?e.directives.tagName(r.source,u=>n(r,"TAG_RESOLVE_FAILED",u)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[tr.SCALAR]:c?l=n$(e.schema,i,c,r,n):t.type==="scalar"?l=i$(e,i,t,n):l=e.schema[tr.SCALAR];let d;try{let u=l.resolve(i,h=>n(r??t,"TAG_RESOLVE_FAILED",h),e.options);d=tr.isScalar(u)?u:new Yh.Scalar(u)}catch(u){let h=u instanceof Error?u.message:String(u);n(r??t,"TAG_RESOLVE_FAILED",h),d=new Yh.Scalar(i)}return d.range=a,d.source=i,s&&(d.type=s),c&&(d.tag=c),l.format&&(d.format=l.format),o&&(d.comment=o),d}function n$(e,t,r,n,i){if(r==="!")return e[tr.SCALAR];let s=[];for(let a of e.tags)if(!a.collection&&a.tag===r)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(t))return a;let o=e.knownTags[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[tr.SCALAR])}function i$({atKey:e,directives:t,schema:r},n,i,s){let o=r.tags.find(a=>(a.default===!0||e&&a.default==="key")&&a.test?.test(n))||r[tr.SCALAR];if(r.compat){let a=r.compat.find(c=>c.default&&c.test?.test(n))??r[tr.SCALAR];if(o.tag!==a.tag){let c=t.tagString(o.tag),l=t.tagString(a.tag),d=`Value may be parsed as either ${c} or ${l}`;s(i,"TAG_RESOLVE_FAILED",d,!0)}}return o}Xh.composeScalar=r$});var tm=v(em=>{"use strict";function s$(e,t,r){if(t){r??(r=t.length);for(let n=r-1;n>=0;--n){let i=t[n];switch(i.type){case"space":case"comment":case"newline":e-=i.source.length;continue}for(i=t[++n];i?.type==="space";)e+=i.source.length,i=t[++n];break}}return e}em.emptyScalarPosition=s$});var im=v(Fc=>{"use strict";var o$=yn(),a$=L(),c$=zh(),rm=Zh(),l$=Nr(),u$=tm(),d$={composeNode:nm,composeEmptyNode:Lc};function nm(e,t,r,n){let i=e.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=r,l,d=!0;switch(t.type){case"alias":l=f$(e,t,n),(a||c)&&n(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=rm.composeScalar(e,t,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=c$.composeCollection(d$,e,t,r,n),a&&(l.anchor=a.source.substring(1))}catch(u){let h=u instanceof Error?u.message:String(u);n(t,"RESOURCE_EXHAUSTION",h)}break;default:{let u=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;n(t,"UNEXPECTED_TOKEN",u),d=!1}}return l??(l=Lc(e,t.offset,void 0,null,r,n)),a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&e.options.stringKeys&&(!a$.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&d&&(l.srcToken=t),l}function Lc(e,t,r,n,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){let d={type:"scalar",offset:u$.emptyScalarPosition(t,r,n),indent:-1,source:""},u=rm.composeScalar(e,d,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function f$({options:e},{offset:t,source:r,end:n},i){let s=new o$.Alias(r.substring(1));s.source===""&&i(t,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&i(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+r.length,a=l$.resolveEnd(n,o,e.strict,i);return s.range=[t,o,a.offset],a.comment&&(s.comment=a.comment),s}Fc.composeEmptyNode=Lc;Fc.composeNode=nm});var am=v(om=>{"use strict";var p$=On(),sm=im(),h$=Nr(),m$=qn();function g$(e,t,{offset:r,start:n,value:i,end:s},o){let a=Object.assign({_directives:t},e),c=new p$.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=m$.resolveProps(n,{indicator:"doc-start",next:i??s?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?sm.composeNode(l,i,d,o):sm.composeEmptyNode(l,d.end,n,null,d,o);let u=c.contents.range[2],h=h$.resolveEnd(s,u,!1,o);return h.comment&&(c.comment=h.comment),c.range=[r,u,h.offset],c}om.composeDoc=g$});var Bc=v(um=>{"use strict";var y$=Gi("process"),v$=Pa(),w$=On(),Mn=Nn(),cm=L(),b$=am(),S$=Nr();function Ln(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:r}=e;return[t,t+(typeof r=="string"?r.length:1)]}function lm(e){let t="",r=!1,n=!1;for(let i=0;i<e.length;++i){let s=e[i];switch(s[0]){case"#":t+=(t===""?"":n?`
102
+
103
+ `:`
104
+ `)+(s.substring(1)||" "),r=!0,n=!1;break;case"%":e[i+1]?.[0]!=="#"&&(i+=1),r=!1;break;default:r||(n=!0),r=!1}}return{comment:t,afterEmptyLine:n}}var Vc=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,n,i,s)=>{let o=Ln(r);s?this.warnings.push(new Mn.YAMLWarning(o,n,i)):this.errors.push(new Mn.YAMLParseError(o,n,i))},this.directives=new v$.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:n,afterEmptyLine:i}=lm(this.prelude);if(n){let s=t.contents;if(r)t.comment=t.comment?`${t.comment}
105
+ ${n}`:n;else if(i||t.directives.docStart||!s)t.commentBefore=n;else if(cm.isCollection(s)&&!s.flow&&s.items.length>0){let o=s.items[0];cm.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${n}
106
+ ${a}`:n}else{let o=s.commentBefore;s.commentBefore=o?`${n}
107
+ ${o}`:n}}if(r){for(let s=0;s<this.errors.length;++s)t.errors.push(this.errors[s]);for(let s=0;s<this.warnings.length;++s)t.warnings.push(this.warnings[s])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:lm(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,n=-1){for(let i of t)yield*this.next(i);yield*this.end(r,n)}*next(t){switch(y$.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,n,i)=>{let s=Ln(t);s[0]+=r,this.onError(s,"BAD_DIRECTIVE",n,i)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=b$.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let r=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,n=new Mn.YAMLParseError(Ln(t),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){let n="Unexpected doc-end without preceding document";this.errors.push(new Mn.YAMLParseError(Ln(t),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let r=S$.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let n=this.doc.comment;this.doc.comment=n?`${n}
108
+ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new Mn.YAMLParseError(Ln(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let n=Object.assign({_directives:this.directives},this.options),i=new w$.Document(void 0,n);this.atDirectives&&this.onError(r,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,r,r],this.decorate(i,!1),yield i}}};um.Composer=Vc});var pm=v(Ns=>{"use strict";var _$=Nc(),k$=Mc(),$$=Nn(),dm=_n();function E$(e,t=!0,r){if(e){let n=(i,s,o)=>{let a=typeof i=="number"?i:Array.isArray(i)?i[0]:i.offset;if(r)r(a,s,o);else throw new $$.YAMLParseError([a,a+1],s,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return k$.resolveFlowScalar(e,t,n);case"block-scalar":return _$.resolveBlockScalar({options:{strict:t}},e,n)}}return null}function I$(e,t){let{implicitKey:r=!1,indent:n,inFlow:i=!1,offset:s=-1,type:o="PLAIN"}=t,a=dm.stringifyString({type:o,value:e},{implicitKey:r,indent:n>0?" ".repeat(n):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:n,source:`
109
+ `}];switch(a[0]){case"|":case">":{let l=a.indexOf(`
110
+ `),d=a.substring(0,l),u=a.substring(l+1)+`
111
+ `,h=[{type:"block-scalar-header",offset:s,indent:n,source:d}];return fm(h,c)||h.push({type:"newline",offset:-1,indent:n,source:`
112
+ `}),{type:"block-scalar",offset:s,indent:n,props:h,source:u}}case'"':return{type:"double-quoted-scalar",offset:s,indent:n,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:s,indent:n,source:a,end:c};default:return{type:"scalar",offset:s,indent:n,source:a,end:c}}}function P$(e,t,r={}){let{afterKey:n=!1,implicitKey:i=!1,inFlow:s=!1,type:o}=r,a="indent"in e?e.indent:null;if(n&&typeof a=="number"&&(a+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=dm.stringifyString({type:o,value:t},{implicitKey:i||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":R$(e,c);break;case'"':Kc(e,c,"double-quoted-scalar");break;case"'":Kc(e,c,"single-quoted-scalar");break;default:Kc(e,c,"scalar")}}function R$(e,t){let r=t.indexOf(`
113
+ `),n=t.substring(0,r),i=t.substring(r+1)+`
114
+ `;if(e.type==="block-scalar"){let s=e.props[0];if(s.type!=="block-scalar-header")throw new Error("Invalid block scalar header");s.source=n,e.source=i}else{let{offset:s}=e,o="indent"in e?e.indent:-1,a=[{type:"block-scalar-header",offset:s,indent:o,source:n}];fm(a,"end"in e?e.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
115
+ `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:a,source:i})}}function fm(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function Kc(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let n=e.props.slice(1),i=t.length;e.props[0].type==="block-scalar-header"&&(i-=e.props[0].source.length);for(let s of n)s.offset+=i;delete e.props,Object.assign(e,{type:r,source:t,end:n});break}case"block-map":case"block-seq":{let i={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
116
+ `};delete e.items,Object.assign(e,{type:r,source:t,end:[i]});break}default:{let n="indent"in e?e.indent:-1,i="end"in e&&Array.isArray(e.end)?e.end.filter(s=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(e))s!=="type"&&s!=="offset"&&delete e[s];Object.assign(e,{type:r,indent:n,source:t,end:i})}}}Ns.createScalarToken=I$;Ns.resolveAsScalar=E$;Ns.setScalarValue=P$});var mm=v(hm=>{"use strict";var A$=e=>"type"in e?Ms(e):qs(e);function Ms(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=Ms(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=qs(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=qs(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=qs(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function qs({start:e,key:t,sep:r,value:n}){let i="";for(let s of e)i+=s.source;if(t&&(i+=Ms(t)),r)for(let s of r)i+=s.source;return n&&(i+=Ms(n)),i}hm.stringify=A$});var wm=v(vm=>{"use strict";var Uc=Symbol("break visit"),C$=Symbol("skip children"),gm=Symbol("remove item");function rr(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),ym(Object.freeze([]),e,t)}rr.BREAK=Uc;rr.SKIP=C$;rr.REMOVE=gm;rr.itemAtPath=(e,t)=>{let r=e;for(let[n,i]of t){let s=r?.[n];if(s&&"items"in s)r=s.items[i];else return}return r};rr.parentCollection=(e,t)=>{let r=rr.itemAtPath(e,t.slice(0,-1)),n=t[t.length-1][0],i=r?.[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function ym(e,t,r){let n=r(t,e);if(typeof n=="symbol")return n;for(let i of["key","value"]){let s=t[i];if(s&&"items"in s){for(let o=0;o<s.items.length;++o){let a=ym(Object.freeze(e.concat([[i,o]])),s.items[o],r);if(typeof a=="number")o=a-1;else{if(a===Uc)return Uc;a===gm&&(s.items.splice(o,1),o-=1)}}typeof n=="function"&&i==="key"&&(n=n(t,e))}}return typeof n=="function"?n(t,e):n}vm.visit=rr});var Ls=v(_e=>{"use strict";var Gc=pm(),T$=mm(),D$=wm(),Hc="\uFEFF",zc="",Wc="",Qc="",O$=e=>!!e&&"items"in e,x$=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function j$(e){switch(e){case Hc:return"<BOM>";case zc:return"<DOC>";case Wc:return"<FLOW_END>";case Qc:return"<SCALAR>";default:return JSON.stringify(e)}}function N$(e){switch(e){case Hc:return"byte-order-mark";case zc:return"doc-mode";case Wc:return"flow-error-end";case Qc:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
117
+ `:case`\r
118
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}_e.createScalarToken=Gc.createScalarToken;_e.resolveAsScalar=Gc.resolveAsScalar;_e.setScalarValue=Gc.setScalarValue;_e.stringify=T$.stringify;_e.visit=D$.visit;_e.BOM=Hc;_e.DOCUMENT=zc;_e.FLOW_END=Wc;_e.SCALAR=Qc;_e.isCollection=O$;_e.isScalar=x$;_e.prettyToken=j$;_e.tokenType=N$});var Xc=v(Sm=>{"use strict";var Fn=Ls();function Ke(e){switch(e){case void 0:case" ":case`
119
+ `:case"\r":case" ":return!0;default:return!1}}var bm=new Set("0123456789ABCDEFabcdef"),q$=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Fs=new Set(",[]{}"),M$=new Set(` ,[]{}
120
+ \r `),Jc=e=>!e||M$.has(e),Yc=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let n=this.next??"stream";for(;n&&(r||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
121
+ `?!0:r==="\r"?this.buffer[t+1]===`
122
+ `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let n=0;for(;r===" ";)r=this.buffer[++n+t];if(r==="\r"){let i=this.buffer[n+t+1];if(i===`
123
+ `||!i&&!this.atEnd)return t+n+1}return r===`
124
+ `||n>=this.indentNext||!r&&!this.atEnd?t+n:-1}if(r==="-"||r==="."){let n=this.buffer.substr(t,3);if((n==="---"||n==="...")&&Ke(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
125
+ `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Fn.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,n=t.indexOf("#");for(;n!==-1;){let s=t[n-1];if(s===" "||s===" "){r=n-1;break}else n=t.indexOf("#",n+1)}for(;;){let s=t[r-1];if(s===" "||s===" ")r-=1;else break}let i=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-i),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield Fn.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&Ke(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Ke(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Ke(r)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Jc),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,n=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=n=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let i=this.getLine();if(i===null)return this.setNext("flow");if((n!==-1&&n<this.indentNext&&i[0]!=="#"||n===0&&(i.startsWith("---")||i.startsWith("..."))&&Ke(i[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield Fn.FLOW_END,yield*this.parseLineStart();let s=0;for(;i[s]===",";)s+=yield*this.pushCount(1),s+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(s+=yield*this.pushIndicators(),i[s]){case void 0:return"flow";case"#":return yield*this.pushCount(i.length-s),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Jc),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ke(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let s=0;for(;this.buffer[r-1-s]==="\\";)s+=1;if(s%2===0)break;r=this.buffer.indexOf('"',r+1)}let n=this.buffer.substring(0,r),i=n.indexOf(`
126
+ `,this.pos);if(i!==-1){for(;i!==-1;){let s=this.continueScalar(i+1);if(s===-1)break;i=n.indexOf(`
127
+ `,s)}i!==-1&&(r=i-(n[i-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>Ke(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,n;e:for(let s=this.pos;n=this.buffer[s];++s)switch(n){case" ":r+=1;break;case`
128
+ `:t=s,r=0;break;case"\r":{let o=this.buffer[s+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
129
+ `)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let s=this.continueScalar(t+1);if(s===-1)break;t=this.buffer.indexOf(`
130
+ `,s)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let i=t+1;for(n=this.buffer[i];n===" ";)n=this.buffer[++i];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===`
131
+ `;)n=this.buffer[++i];t=i-1}else if(!this.blockScalarKeep)do{let s=t-1,o=this.buffer[s];o==="\r"&&(o=this.buffer[--s]);let a=s;for(;o===" ";)o=this.buffer[--s];if(o===`
132
+ `&&s>=this.pos&&s+1+r>a)t=s;else break}while(!0);return yield Fn.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,n=this.pos-1,i;for(;i=this.buffer[++n];)if(i===":"){let s=this.buffer[n+1];if(Ke(s)||t&&Fs.has(s))break;r=n}else if(Ke(i)){let s=this.buffer[n+1];if(i==="\r"&&(s===`
133
+ `?(n+=1,i=`
134
+ `,s=this.buffer[n+1]):r=n),s==="#"||t&&Fs.has(s))break;if(i===`
135
+ `){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(t&&Fs.has(i))break;r=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield Fn.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let n=this.buffer.slice(this.pos,t);return n?(yield n,this.pos+=n.length,n.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Jc),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,n=this.charAt(1);if(Ke(n)||r&&Fs.has(n)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!Ke(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(q$.has(r))r=this.buffer[++t];else if(r==="%"&&bm.has(this.buffer[t+1])&&bm.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
136
+ `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
137
+ `?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,n;do n=this.buffer[++r];while(n===" "||t&&n===" ");let i=r-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=r),i}*pushUntil(t){let r=this.pos,n=this.buffer[r];for(;!t(n);)n=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};Sm.Lexer=Yc});var el=v(_m=>{"use strict";var Zc=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,n=this.lineStarts.length;for(;r<n;){let s=r+n>>1;this.lineStarts[s]<t?r=s+1:n=s}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let i=this.lineStarts[r-1];return{line:r,col:t-i+1}}}};_m.LineCounter=Zc});var rl=v(Pm=>{"use strict";var L$=Gi("process"),km=Ls(),F$=Xc();function Tt(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function $m(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function Im(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Vs(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function qr(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function Bs(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function Em(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Tt(t.start,"explicit-key-ind")&&!Tt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Im(t.value)?t.value.end?Bs(t.value.end,t.sep):t.value.end=t.sep:Bs(t.start,t.sep),delete t.sep)}var tl=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new F$.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(t,r))yield*this.next(n);r||(yield*this.end())}*next(t){if(this.source=t,L$.env.LOG_TOKENS&&console.log("|",km.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=km.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let n=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:n,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let n=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in n?n.indent:0:r.type==="flow-collection"&&n.type==="document"&&(r.indent=0),r.type==="flow-collection"&&Em(r),n.type){case"document":n.value=r;break;case"block-scalar":n.props.push(r);break;case"block-map":{let i=n.items[n.items.length-1];if(i.value){n.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=r;else{Object.assign(i,{key:r,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{let i=n.items[n.items.length-1];i.value?n.items.push({start:[],value:r}):i.value=r;break}case"flow-collection":{let i=n.items[n.items.length-1];!i||i.value?n.items.push({start:[],key:r,sep:[]}):i.sep?i.value=r:Object.assign(i,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let i=r.items[r.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&$m(i.start)===-1&&(r.indent===0||i.start.every(s=>s.type!=="comment"||s.indent<r.indent))&&(n.type==="document"?n.end=i.start:n.items.push({start:i.start}),r.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{$m(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let r=Vs(this.peek(2)),n=qr(r),i;t.end?(i=t.end,i.push(this.sourceToken),delete t.end):i=[this.sourceToken];let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:n,key:t,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
138
+ `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
139
+ `,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let i=t.items[t.items.length-2]?.value?.end;if(Array.isArray(i)){Bs(i,r.start),i.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let n=!this.onKeyLine&&this.indent===t.indent,i=n&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",s=[];if(i&&r.sep&&!r.value){let o=[];for(let a=0;a<r.sep.length;++a){let c=r.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(s=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||r.value?(s.push(this.sourceToken),t.items.push({start:s}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):i||r.value?(s.push(this.sourceToken),t.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Tt(r.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(Im(r.key)&&!Tt(r.sep,"newline")){let o=qr(r.start),a=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else s.length>0?r.sep=r.sep.concat(s,this.sourceToken):r.sep.push(this.sourceToken);else if(Tt(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=qr(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||i?t.items.push({start:s,key:null,sep:[this.sourceToken]}):Tt(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);i||r.value?(t.items.push({start:s,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!Tt(r.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&t.items.push({start:s});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let i=t.items[t.items.length-2]?.value?.end;if(Array.isArray(i)){Bs(i,r.start),i.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||Tt(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let n=this.startBlockValue(t);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:i,sep:[]}):r.sep?this.stack.push(i):Object.assign(r,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let n=this.startBlockValue(t);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===t.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let i=Vs(n),s=qr(i);Em(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:s,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
140
+ `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
141
+ `,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=Vs(t),n=qr(r);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=Vs(t),n=qr(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Pm.Parser=tl});var Dm=v(Bn=>{"use strict";var Rm=Bc(),V$=On(),Vn=Nn(),B$=Fa(),K$=L(),U$=el(),Am=rl();function Cm(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new U$.LineCounter||null,prettyErrors:t}}function G$(e,t={}){let{lineCounter:r,prettyErrors:n}=Cm(t),i=new Am.Parser(r?.addNewLine),s=new Rm.Composer(t),o=Array.from(s.compose(i.parse(e)));if(n&&r)for(let a of o)a.errors.forEach(Vn.prettifyError(e,r)),a.warnings.forEach(Vn.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function Tm(e,t={}){let{lineCounter:r,prettyErrors:n}=Cm(t),i=new Am.Parser(r?.addNewLine),s=new Rm.Composer(t),o=null;for(let a of s.compose(i.parse(e),!0,e.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Vn.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&r&&(o.errors.forEach(Vn.prettifyError(e,r)),o.warnings.forEach(Vn.prettifyError(e,r))),o}function H$(e,t,r){let n;typeof t=="function"?n=t:r===void 0&&t&&typeof t=="object"&&(r=t);let i=Tm(e,r);if(!i)return null;if(i.warnings.forEach(s=>B$.warn(i.options.logLevel,s)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:n},r))}function z$(e,t,r){let n=null;if(typeof t=="function"||Array.isArray(t)?n=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let i=Math.round(r);r=i<1?void 0:i>8?{indent:8}:{indent:i}}if(e===void 0){let{keepUndefined:i}=r??t??{};if(!i)return}return K$.isDocument(e)&&!n?e.toString(r):new V$.Document(e,n,r).toString(r)}Bn.parse=H$;Bn.parseAllDocuments=G$;Bn.parseDocument=Tm;Bn.stringify=z$});var Mr=v(G=>{"use strict";var W$=Bc(),Q$=On(),J$=_c(),nl=Nn(),Y$=yn(),Dt=L(),X$=Pt(),Z$=se(),e1=At(),t1=Ct(),r1=Ls(),n1=Xc(),i1=el(),s1=rl(),Ks=Dm(),Om=pn();G.Composer=W$.Composer;G.Document=Q$.Document;G.Schema=J$.Schema;G.YAMLError=nl.YAMLError;G.YAMLParseError=nl.YAMLParseError;G.YAMLWarning=nl.YAMLWarning;G.Alias=Y$.Alias;G.isAlias=Dt.isAlias;G.isCollection=Dt.isCollection;G.isDocument=Dt.isDocument;G.isMap=Dt.isMap;G.isNode=Dt.isNode;G.isPair=Dt.isPair;G.isScalar=Dt.isScalar;G.isSeq=Dt.isSeq;G.Pair=X$.Pair;G.Scalar=Z$.Scalar;G.YAMLMap=e1.YAMLMap;G.YAMLSeq=t1.YAMLSeq;G.CST=r1;G.Lexer=n1.Lexer;G.LineCounter=i1.LineCounter;G.Parser=s1.Parser;G.parse=Ks.parse;G.parseAllDocuments=Ks.parseAllDocuments;G.parseDocument=Ks.parseDocument;G.stringify=Ks.stringify;G.visit=Om.visit;G.visitAsync=Om.visitAsync});var Qn=v(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.regexpCode=V.getEsmExportName=V.getProperty=V.safeStringify=V.stringify=V.strConcat=V.addCodeArg=V.str=V._=V.nil=V._Code=V.Name=V.IDENTIFIER=V._CodeOrName=void 0;var zn=class{};V._CodeOrName=zn;V.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var or=class extends zn{constructor(t){if(super(),!V.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};V.Name=or;var De=class extends zn{constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof or&&(r[n.str]=(r[n.str]||0)+1),r),{})}};V._Code=De;V.nil=new De("");function rg(e,...t){let r=[e[0]],n=0;for(;n<t.length;)kl(r,t[n]),r.push(e[++n]);return new De(r)}V._=rg;var _l=new De("+");function ng(e,...t){let r=[Wn(e[0])],n=0;for(;n<t.length;)r.push(_l),kl(r,t[n]),r.push(_l,Wn(e[++n]));return G1(r),new De(r)}V.str=ng;function kl(e,t){t instanceof De?e.push(...t._items):t instanceof or?e.push(t):e.push(W1(t))}V.addCodeArg=kl;function G1(e){let t=1;for(;t<e.length-1;){if(e[t]===_l){let r=H1(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function H1(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof or||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof or))return`"${e}${t.slice(1)}`}function z1(e,t){return t.emptyStr()?e:e.emptyStr()?t:ng`${e}${t}`}V.strConcat=z1;function W1(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Wn(Array.isArray(e)?e.join(","):e)}function Q1(e){return new De(Wn(e))}V.stringify=Q1;function Wn(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}V.safeStringify=Wn;function J1(e){return typeof e=="string"&&V.IDENTIFIER.test(e)?new De(`.${e}`):rg`[${e}]`}V.getProperty=J1;function Y1(e){if(typeof e=="string"&&V.IDENTIFIER.test(e))return new De(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}V.getEsmExportName=Y1;function X1(e){return new De(e.toString())}V.regexpCode=X1});var Il=v($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.ValueScope=$e.ValueScopeName=$e.Scope=$e.varKinds=$e.UsedValueState=void 0;var ke=Qn(),$l=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},Js;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(Js||($e.UsedValueState=Js={}));$e.varKinds={const:new ke.Name("const"),let:new ke.Name("let"),var:new ke.Name("var")};var Ys=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof ke.Name?t:this.name(t)}name(t){return new ke.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};$e.Scope=Ys;var Xs=class extends ke.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,ke._)`.${new ke.Name(r)}[${n}]`}};$e.ValueScopeName=Xs;var Z1=(0,ke._)`\n`,El=class extends Ys{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?Z1:ke.nil}}get(){return this._scope}name(t){return new Xs(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(t),{prefix:s}=i,o=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let d=a.get(o);if(d)return d}else a=this._values[s]=new Map;a.set(o,i);let c=this._scope[s]||(this._scope[s]=[]),l=c.length;return c[l]=r.ref,i.setValue(r,{property:s,itemIndex:l}),i}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,ke._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},r,n)}_reduceValues(t,r,n={},i){let s=ke.nil;for(let o in t){let a=t[o];if(!a)continue;let c=n[o]=n[o]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,Js.Started);let d=r(l);if(d){let u=this.opts.es5?$e.varKinds.var:$e.varKinds.const;s=(0,ke._)`${s}${u} ${l} = ${d};${this.opts._n}`}else if(d=i?.(l))s=(0,ke._)`${s}${d}${this.opts._n}`;else throw new $l(l);c.set(l,Js.Completed)})}return s}};$e.ValueScope=El});var T=v(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0});O.or=O.and=O.not=O.CodeGen=O.operators=O.varKinds=O.ValueScopeName=O.ValueScope=O.Scope=O.Name=O.regexpCode=O.stringify=O.getProperty=O.nil=O.strConcat=O.str=O._=void 0;var M=Qn(),ze=Il(),Nt=Qn();Object.defineProperty(O,"_",{enumerable:!0,get:function(){return Nt._}});Object.defineProperty(O,"str",{enumerable:!0,get:function(){return Nt.str}});Object.defineProperty(O,"strConcat",{enumerable:!0,get:function(){return Nt.strConcat}});Object.defineProperty(O,"nil",{enumerable:!0,get:function(){return Nt.nil}});Object.defineProperty(O,"getProperty",{enumerable:!0,get:function(){return Nt.getProperty}});Object.defineProperty(O,"stringify",{enumerable:!0,get:function(){return Nt.stringify}});Object.defineProperty(O,"regexpCode",{enumerable:!0,get:function(){return Nt.regexpCode}});Object.defineProperty(O,"Name",{enumerable:!0,get:function(){return Nt.Name}});var ro=Il();Object.defineProperty(O,"Scope",{enumerable:!0,get:function(){return ro.Scope}});Object.defineProperty(O,"ValueScope",{enumerable:!0,get:function(){return ro.ValueScope}});Object.defineProperty(O,"ValueScopeName",{enumerable:!0,get:function(){return ro.ValueScopeName}});Object.defineProperty(O,"varKinds",{enumerable:!0,get:function(){return ro.varKinds}});O.operators={GT:new M._Code(">"),GTE:new M._Code(">="),LT:new M._Code("<"),LTE:new M._Code("<="),EQ:new M._Code("==="),NEQ:new M._Code("!=="),NOT:new M._Code("!"),OR:new M._Code("||"),AND:new M._Code("&&"),ADD:new M._Code("+")};var ht=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},Pl=class extends ht{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?ze.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${i};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=Vr(this.rhs,t,r)),this}get names(){return this.rhs instanceof M._CodeOrName?this.rhs.names:{}}},Zs=class extends ht{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof M.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=Vr(this.rhs,t,r),this}get names(){let t=this.lhs instanceof M.Name?{}:{...this.lhs.names};return to(t,this.rhs)}},Rl=class extends Zs{constructor(t,r,n,i){super(t,n,i),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},Al=class extends ht{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},Cl=class extends ht{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},Tl=class extends ht{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},Dl=class extends ht{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=Vr(this.code,t,r),this}get names(){return this.code instanceof M._CodeOrName?this.code.names:{}}},Jn=class extends ht{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,i=n.length;for(;i--;){let s=n[i];s.optimizeNames(t,r)||(eE(t,s.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>lr(t,r.names),{})}},mt=class extends Jn{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},Ol=class extends Jn{},Fr=class extends mt{};Fr.kind="else";var ar=class e extends mt{constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Fr(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(ig(t),r instanceof e?[r]:r.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=Vr(this.condition,t,r),this}get names(){let t=super.names;return to(t,this.condition),this.else&&lr(t,this.else.names),t}};ar.kind="if";var cr=class extends mt{};cr.kind="for";var xl=class extends cr{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=Vr(this.iteration,t,r),this}get names(){return lr(super.names,this.iteration.names)}},jl=class extends cr{constructor(t,r,n,i){super(),this.varKind=t,this.name=r,this.from=n,this.to=i}render(t){let r=t.es5?ze.varKinds.var:this.varKind,{name:n,from:i,to:s}=this;return`for(${r} ${n}=${i}; ${n}<${s}; ${n}++)`+super.render(t)}get names(){let t=to(super.names,this.from);return to(t,this.to)}},eo=class extends cr{constructor(t,r,n,i){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=i}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=Vr(this.iterable,t,r),this}get names(){return lr(super.names,this.iterable.names)}},Yn=class extends mt{constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};Yn.kind="func";var Xn=class extends Jn{render(t){return"return "+super.render(t)}};Xn.kind="return";var Nl=class extends mt{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,i;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(i=this.finally)===null||i===void 0||i.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&lr(t,this.catch.names),this.finally&&lr(t,this.finally.names),t}},Zn=class extends mt{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};Zn.kind="catch";var ei=class extends mt{render(t){return"finally"+super.render(t)}};ei.kind="finally";var ql=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
142
+ `:""},this._extScope=t,this._scope=new ze.Scope({parent:t}),this._nodes=[new Ol]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,i){let s=this._scope.toName(r);return n!==void 0&&i&&(this._constants[s.str]=n),this._leafNode(new Pl(t,s,n)),s}const(t,r,n){return this._def(ze.varKinds.const,t,r,n)}let(t,r,n){return this._def(ze.varKinds.let,t,r,n)}var(t,r,n){return this._def(ze.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new Zs(t,r,n))}add(t,r){return this._leafNode(new Rl(t,O.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==M.nil&&this._leafNode(new Dl(t)),this}object(...t){let r=["{"];for(let[n,i]of t)r.length>1&&r.push(","),r.push(n),(n!==i||this.opts.es5)&&(r.push(":"),(0,M.addCodeArg)(r,i));return r.push("}"),new M._Code(r)}if(t,r,n){if(this._blockNode(new ar(t)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new ar(t))}else(){return this._elseNode(new Fr)}endIf(){return this._endBlockNode(ar,Fr)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new xl(t),r)}forRange(t,r,n,i,s=this.opts.es5?ze.varKinds.var:ze.varKinds.let){let o=this._scope.toName(t);return this._for(new jl(s,o,r,n),()=>i(o))}forOf(t,r,n,i=ze.varKinds.const){let s=this._scope.toName(t);if(this.opts.es5){let o=r instanceof M.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,M._)`${o}.length`,a=>{this.var(s,(0,M._)`${o}[${a}]`),n(s)})}return this._for(new eo("of",i,s,r),()=>n(s))}forIn(t,r,n,i=this.opts.es5?ze.varKinds.var:ze.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,M._)`Object.keys(${r})`,n);let s=this._scope.toName(t);return this._for(new eo("in",i,s,r),()=>n(s))}endFor(){return this._endBlockNode(cr)}label(t){return this._leafNode(new Al(t))}break(t){return this._leafNode(new Cl(t))}return(t){let r=new Xn;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Xn)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new Nl;if(this._blockNode(i),this.code(t),r){let s=this.name("e");this._currNode=i.catch=new Zn(s),r(s)}return n&&(this._currNode=i.finally=new ei,this.code(n)),this._endBlockNode(Zn,ei)}throw(t){return this._leafNode(new Tl(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=M.nil,n,i){return this._blockNode(new Yn(t,r,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(Yn)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof ar))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};O.CodeGen=ql;function lr(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function to(e,t){return t instanceof M._CodeOrName?lr(e,t.names):e}function Vr(e,t,r){if(e instanceof M.Name)return n(e);if(!i(e))return e;return new M._Code(e._items.reduce((s,o)=>(o instanceof M.Name&&(o=n(o)),o instanceof M._Code?s.push(...o._items):s.push(o),s),[]));function n(s){let o=r[s.str];return o===void 0||t[s.str]!==1?s:(delete t[s.str],o)}function i(s){return s instanceof M._Code&&s._items.some(o=>o instanceof M.Name&&t[o.str]===1&&r[o.str]!==void 0)}}function eE(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function ig(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,M._)`!${Ml(e)}`}O.not=ig;var tE=sg(O.operators.AND);function rE(...e){return e.reduce(tE)}O.and=rE;var nE=sg(O.operators.OR);function iE(...e){return e.reduce(nE)}O.or=iE;function sg(e){return(t,r)=>t===M.nil?r:r===M.nil?t:(0,M._)`${Ml(t)} ${e} ${Ml(r)}`}function Ml(e){return e instanceof M.Name?e:(0,M._)`(${e})`}});var N=v(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.checkStrictMode=j.getErrorPath=j.Type=j.useFunc=j.setEvaluated=j.evaluatedPropsToName=j.mergeEvaluated=j.eachItem=j.unescapeJsonPointer=j.escapeJsonPointer=j.escapeFragment=j.unescapeFragment=j.schemaRefOrVal=j.schemaHasRulesButRef=j.schemaHasRules=j.checkUnknownRules=j.alwaysValidSchema=j.toHash=void 0;var J=T(),sE=Qn();function oE(e){let t={};for(let r of e)t[r]=!0;return t}j.toHash=oE;function aE(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(cg(e,t),!lg(t,e.self.RULES.all))}j.alwaysValidSchema=aE;function cg(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let i=n.RULES.keywords;for(let s in t)i[s]||fg(e,`unknown keyword: "${s}"`)}j.checkUnknownRules=cg;function lg(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}j.schemaHasRules=lg;function cE(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}j.schemaHasRulesButRef=cE;function lE({topSchemaRef:e,schemaPath:t},r,n,i){if(!i){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,J._)`${r}`}return(0,J._)`${e}${t}${(0,J.getProperty)(n)}`}j.schemaRefOrVal=lE;function uE(e){return ug(decodeURIComponent(e))}j.unescapeFragment=uE;function dE(e){return encodeURIComponent(Fl(e))}j.escapeFragment=dE;function Fl(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}j.escapeJsonPointer=Fl;function ug(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}j.unescapeJsonPointer=ug;function fE(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}j.eachItem=fE;function og({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(i,s,o,a)=>{let c=o===void 0?s:o instanceof J.Name?(s instanceof J.Name?e(i,s,o):t(i,s,o),o):s instanceof J.Name?(t(i,o,s),s):r(s,o);return a===J.Name&&!(c instanceof J.Name)?n(i,c):c}}j.mergeEvaluated={props:og({mergeNames:(e,t,r)=>e.if((0,J._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,J._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,J._)`${r} || {}`).code((0,J._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,J._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,J._)`${r} || {}`),Vl(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:dg}),items:og({mergeNames:(e,t,r)=>e.if((0,J._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,J._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,J._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,J._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function dg(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,J._)`{}`);return t!==void 0&&Vl(e,r,t),r}j.evaluatedPropsToName=dg;function Vl(e,t,r){Object.keys(r).forEach(n=>e.assign((0,J._)`${t}${(0,J.getProperty)(n)}`,!0))}j.setEvaluated=Vl;var ag={};function pE(e,t){return e.scopeValue("func",{ref:t,code:ag[t.code]||(ag[t.code]=new sE._Code(t.code))})}j.useFunc=pE;var Ll;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Ll||(j.Type=Ll={}));function hE(e,t,r){if(e instanceof J.Name){let n=t===Ll.Num;return r?n?(0,J._)`"[" + ${e} + "]"`:(0,J._)`"['" + ${e} + "']"`:n?(0,J._)`"/" + ${e}`:(0,J._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,J.getProperty)(e).toString():"/"+Fl(e)}j.getErrorPath=hE;function fg(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}j.checkStrictMode=fg});var Oe=v(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});var he=T(),mE={data:new he.Name("data"),valCxt:new he.Name("valCxt"),instancePath:new he.Name("instancePath"),parentData:new he.Name("parentData"),parentDataProperty:new he.Name("parentDataProperty"),rootData:new he.Name("rootData"),dynamicAnchors:new he.Name("dynamicAnchors"),vErrors:new he.Name("vErrors"),errors:new he.Name("errors"),this:new he.Name("this"),self:new he.Name("self"),scope:new he.Name("scope"),json:new he.Name("json"),jsonPos:new he.Name("jsonPos"),jsonLen:new he.Name("jsonLen"),jsonPart:new he.Name("jsonPart")};Bl.default=mE});var ti=v(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.extendErrors=me.resetErrorsCount=me.reportExtraError=me.reportError=me.keyword$DataError=me.keywordError=void 0;var F=T(),no=N(),ve=Oe();me.keywordError={message:({keyword:e})=>(0,F.str)`must pass "${e}" keyword validation`};me.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,F.str)`"${e}" keyword must be ${t} ($data)`:(0,F.str)`"${e}" keyword is invalid ($data)`};function gE(e,t=me.keywordError,r,n){let{it:i}=e,{gen:s,compositeRule:o,allErrors:a}=i,c=mg(e,t,r);n??(o||a)?pg(s,c):hg(i,(0,F._)`[${c}]`)}me.reportError=gE;function yE(e,t=me.keywordError,r){let{it:n}=e,{gen:i,compositeRule:s,allErrors:o}=n,a=mg(e,t,r);pg(i,a),s||o||hg(n,ve.default.vErrors)}me.reportExtraError=yE;function vE(e,t){e.assign(ve.default.errors,t),e.if((0,F._)`${ve.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,F._)`${ve.default.vErrors}.length`,t),()=>e.assign(ve.default.vErrors,null)))}me.resetErrorsCount=vE;function wE({gen:e,keyword:t,schemaValue:r,data:n,errsCount:i,it:s}){if(i===void 0)throw new Error("ajv implementation error");let o=e.name("err");e.forRange("i",i,ve.default.errors,a=>{e.const(o,(0,F._)`${ve.default.vErrors}[${a}]`),e.if((0,F._)`${o}.instancePath === undefined`,()=>e.assign((0,F._)`${o}.instancePath`,(0,F.strConcat)(ve.default.instancePath,s.errorPath))),e.assign((0,F._)`${o}.schemaPath`,(0,F.str)`${s.errSchemaPath}/${t}`),s.opts.verbose&&(e.assign((0,F._)`${o}.schema`,r),e.assign((0,F._)`${o}.data`,n))})}me.extendErrors=wE;function pg(e,t){let r=e.const("err",t);e.if((0,F._)`${ve.default.vErrors} === null`,()=>e.assign(ve.default.vErrors,(0,F._)`[${r}]`),(0,F._)`${ve.default.vErrors}.push(${r})`),e.code((0,F._)`${ve.default.errors}++`)}function hg(e,t){let{gen:r,validateName:n,schemaEnv:i}=e;i.$async?r.throw((0,F._)`new ${e.ValidationError}(${t})`):(r.assign((0,F._)`${n}.errors`,t),r.return(!1))}var ur={keyword:new F.Name("keyword"),schemaPath:new F.Name("schemaPath"),params:new F.Name("params"),propertyName:new F.Name("propertyName"),message:new F.Name("message"),schema:new F.Name("schema"),parentSchema:new F.Name("parentSchema")};function mg(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,F._)`{}`:bE(e,t,r)}function bE(e,t,r={}){let{gen:n,it:i}=e,s=[SE(i,r),_E(e,r)];return kE(e,t,s),n.object(...s)}function SE({errorPath:e},{instancePath:t}){let r=t?(0,F.str)`${e}${(0,no.getErrorPath)(t,no.Type.Str)}`:e;return[ve.default.instancePath,(0,F.strConcat)(ve.default.instancePath,r)]}function _E({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let i=n?t:(0,F.str)`${t}/${e}`;return r&&(i=(0,F.str)`${i}${(0,no.getErrorPath)(r,no.Type.Str)}`),[ur.schemaPath,i]}function kE(e,{params:t,message:r},n){let{keyword:i,data:s,schemaValue:o,it:a}=e,{opts:c,propertyName:l,topSchemaRef:d,schemaPath:u}=a;n.push([ur.keyword,i],[ur.params,typeof t=="function"?t(e):t||(0,F._)`{}`]),c.messages&&n.push([ur.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([ur.schema,o],[ur.parentSchema,(0,F._)`${d}${u}`],[ve.default.data,s]),l&&n.push([ur.propertyName,l])}});var yg=v(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.boolOrEmptySchema=Br.topBoolOrEmptySchema=void 0;var $E=ti(),EE=T(),IE=Oe(),PE={message:"boolean schema is false"};function RE(e){let{gen:t,schema:r,validateName:n}=e;r===!1?gg(e,!1):typeof r=="object"&&r.$async===!0?t.return(IE.default.data):(t.assign((0,EE._)`${n}.errors`,null),t.return(!0))}Br.topBoolOrEmptySchema=RE;function AE(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),gg(e)):r.var(t,!0)}Br.boolOrEmptySchema=AE;function gg(e,t){let{gen:r,data:n}=e,i={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,$E.reportError)(i,PE,void 0,t)}});var Kl=v(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.getRules=Kr.isJSONType=void 0;var CE=["string","number","integer","boolean","null","object","array"],TE=new Set(CE);function DE(e){return typeof e=="string"&&TE.has(e)}Kr.isJSONType=DE;function OE(){let 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:{}}}Kr.getRules=OE});var Ul=v(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.shouldUseRule=qt.shouldUseGroup=qt.schemaHasRulesForType=void 0;function xE({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&vg(e,n)}qt.schemaHasRulesForType=xE;function vg(e,t){return t.rules.some(r=>wg(e,r))}qt.shouldUseGroup=vg;function wg(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}qt.shouldUseRule=wg});var ri=v(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.reportTypeError=ge.checkDataTypes=ge.checkDataType=ge.coerceAndCheckDataType=ge.getJSONTypes=ge.getSchemaTypes=ge.DataType=void 0;var jE=Kl(),NE=Ul(),qE=ti(),D=T(),bg=N(),Ur;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Ur||(ge.DataType=Ur={}));function ME(e){let t=Sg(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}ge.getSchemaTypes=ME;function Sg(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(jE.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}ge.getJSONTypes=Sg;function LE(e,t){let{gen:r,data:n,opts:i}=e,s=FE(t,i.coerceTypes),o=t.length>0&&!(s.length===0&&t.length===1&&(0,NE.schemaHasRulesForType)(e,t[0]));if(o){let a=Hl(t,n,i.strictNumbers,Ur.Wrong);r.if(a,()=>{s.length?VE(e,t,s):zl(e)})}return o}ge.coerceAndCheckDataType=LE;var _g=new Set(["string","number","integer","boolean","null"]);function FE(e,t){return t?e.filter(r=>_g.has(r)||t==="array"&&r==="array"):[]}function VE(e,t,r){let{gen:n,data:i,opts:s}=e,o=n.let("dataType",(0,D._)`typeof ${i}`),a=n.let("coerced",(0,D._)`undefined`);s.coerceTypes==="array"&&n.if((0,D._)`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,D._)`${i}[0]`).assign(o,(0,D._)`typeof ${i}`).if(Hl(t,i,s.strictNumbers),()=>n.assign(a,i))),n.if((0,D._)`${a} !== undefined`);for(let l of r)(_g.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),zl(e),n.endIf(),n.if((0,D._)`${a} !== undefined`,()=>{n.assign(i,a),BE(e,a)});function c(l){switch(l){case"string":n.elseIf((0,D._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,D._)`"" + ${i}`).elseIf((0,D._)`${i} === null`).assign(a,(0,D._)`""`);return;case"number":n.elseIf((0,D._)`${o} == "boolean" || ${i} === null
143
+ || (${o} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,D._)`+${i}`);return;case"integer":n.elseIf((0,D._)`${o} === "boolean" || ${i} === null
144
+ || (${o} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(a,(0,D._)`+${i}`);return;case"boolean":n.elseIf((0,D._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(a,!1).elseIf((0,D._)`${i} === "true" || ${i} === 1`).assign(a,!0);return;case"null":n.elseIf((0,D._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(a,null);return;case"array":n.elseIf((0,D._)`${o} === "string" || ${o} === "number"
145
+ || ${o} === "boolean" || ${i} === null`).assign(a,(0,D._)`[${i}]`)}}}function BE({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,D._)`${t} !== undefined`,()=>e.assign((0,D._)`${t}[${r}]`,n))}function Gl(e,t,r,n=Ur.Correct){let i=n===Ur.Correct?D.operators.EQ:D.operators.NEQ,s;switch(e){case"null":return(0,D._)`${t} ${i} null`;case"array":s=(0,D._)`Array.isArray(${t})`;break;case"object":s=(0,D._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=o((0,D._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=o();break;default:return(0,D._)`typeof ${t} ${i} ${e}`}return n===Ur.Correct?s:(0,D.not)(s);function o(a=D.nil){return(0,D.and)((0,D._)`typeof ${t} == "number"`,a,r?(0,D._)`isFinite(${t})`:D.nil)}}ge.checkDataType=Gl;function Hl(e,t,r,n){if(e.length===1)return Gl(e[0],t,r,n);let i,s=(0,bg.toHash)(e);if(s.array&&s.object){let o=(0,D._)`typeof ${t} != "object"`;i=s.null?o:(0,D._)`!${t} || ${o}`,delete s.null,delete s.array,delete s.object}else i=D.nil;s.number&&delete s.integer;for(let o in s)i=(0,D.and)(i,Gl(o,t,r,n));return i}ge.checkDataTypes=Hl;var KE={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,D._)`{type: ${e}}`:(0,D._)`{type: ${t}}`};function zl(e){let t=UE(e);(0,qE.reportError)(t,KE)}ge.reportTypeError=zl;function UE(e){let{gen:t,data:r,schema:n}=e,i=(0,bg.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:e}}});var $g=v(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.assignDefaults=void 0;var Gr=T(),GE=N();function HE(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let i in r)kg(e,i,r[i].default);else t==="array"&&Array.isArray(n)&&n.forEach((i,s)=>kg(e,s,i.default))}io.assignDefaults=HE;function kg(e,t,r){let{gen:n,compositeRule:i,data:s,opts:o}=e;if(r===void 0)return;let a=(0,Gr._)`${s}${(0,Gr.getProperty)(t)}`;if(i){(0,GE.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,Gr._)`${a} === undefined`;o.useDefaults==="empty"&&(c=(0,Gr._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Gr._)`${a} = ${(0,Gr.stringify)(r)}`)}});var xe=v(z=>{"use strict";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;var Y=T(),Wl=N(),Mt=Oe(),zE=N();function WE(e,t){let{gen:r,data:n,it:i}=e;r.if(Jl(r,n,t,i.opts.ownProperties),()=>{e.setParams({missingProperty:(0,Y._)`${t}`},!0),e.error()})}z.checkReportMissingProp=WE;function QE({gen:e,data:t,it:{opts:r}},n,i){return(0,Y.or)(...n.map(s=>(0,Y.and)(Jl(e,t,s,r.ownProperties),(0,Y._)`${i} = ${s}`)))}z.checkMissingProp=QE;function JE(e,t){e.setParams({missingProperty:t},!0),e.error()}z.reportMissingProp=JE;function Eg(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Y._)`Object.prototype.hasOwnProperty`})}z.hasPropFunc=Eg;function Ql(e,t,r){return(0,Y._)`${Eg(e)}.call(${t}, ${r})`}z.isOwnProperty=Ql;function YE(e,t,r,n){let i=(0,Y._)`${t}${(0,Y.getProperty)(r)} !== undefined`;return n?(0,Y._)`${i} && ${Ql(e,t,r)}`:i}z.propertyInData=YE;function Jl(e,t,r,n){let i=(0,Y._)`${t}${(0,Y.getProperty)(r)} === undefined`;return n?(0,Y.or)(i,(0,Y.not)(Ql(e,t,r))):i}z.noPropertyInData=Jl;function Ig(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}z.allSchemaProperties=Ig;function XE(e,t){return Ig(t).filter(r=>!(0,Wl.alwaysValidSchema)(e,t[r]))}z.schemaProperties=XE;function ZE({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:i,errorPath:s},it:o},a,c,l){let d=l?(0,Y._)`${e}, ${t}, ${n}${i}`:t,u=[[Mt.default.instancePath,(0,Y.strConcat)(Mt.default.instancePath,s)],[Mt.default.parentData,o.parentData],[Mt.default.parentDataProperty,o.parentDataProperty],[Mt.default.rootData,Mt.default.rootData]];o.opts.dynamicRef&&u.push([Mt.default.dynamicAnchors,Mt.default.dynamicAnchors]);let h=(0,Y._)`${d}, ${r.object(...u)}`;return c!==Y.nil?(0,Y._)`${a}.call(${c}, ${h})`:(0,Y._)`${a}(${h})`}z.callValidateCode=ZE;var eI=(0,Y._)`new RegExp`;function tI({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:i}=t.code,s=i(r,n);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Y._)`${i.code==="new RegExp"?eI:(0,zE.useFunc)(e,i)}(${r}, ${n})`})}z.usePattern=tI;function rI(e){let{gen:t,data:r,keyword:n,it:i}=e,s=t.name("valid");if(i.allErrors){let a=t.let("valid",!0);return o(()=>t.assign(a,!1)),a}return t.var(s,!0),o(()=>t.break()),s;function o(a){let c=t.const("len",(0,Y._)`${r}.length`);t.forRange("i",0,c,l=>{e.subschema({keyword:n,dataProp:l,dataPropType:Wl.Type.Num},s),t.if((0,Y.not)(s),a)})}}z.validateArray=rI;function nI(e){let{gen:t,schema:r,keyword:n,it:i}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Wl.alwaysValidSchema)(i,c))&&!i.opts.unevaluated)return;let o=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((c,l)=>{let d=e.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);t.assign(o,(0,Y._)`${o} || ${a}`),e.mergeValidEvaluated(d,a)||t.if((0,Y.not)(o))})),e.result(o,()=>e.reset(),()=>e.error(!0))}z.validateUnion=nI});var Ag=v(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.validateKeywordUsage=it.validSchemaType=it.funcKeywordCode=it.macroKeywordCode=void 0;var we=T(),dr=Oe(),iI=xe(),sI=ti();function oI(e,t){let{gen:r,keyword:n,schema:i,parentSchema:s,it:o}=e,a=t.macro.call(o.self,i,s,o),c=Rg(r,n,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);let l=r.name("valid");e.subschema({schema:a,schemaPath:we.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}it.macroKeywordCode=oI;function aI(e,t){var r;let{gen:n,keyword:i,schema:s,parentSchema:o,$data:a,it:c}=e;lI(c,t);let l=!a&&t.compile?t.compile.call(c.self,s,o,c):t.validate,d=Rg(n,i,l),u=n.let("valid");e.block$data(u,h),e.ok((r=t.valid)!==null&&r!==void 0?r:u);function h(){if(t.errors===!1)f(),t.modifying&&Pg(e),g(()=>e.error());else{let y=t.async?m():p();t.modifying&&Pg(e),g(()=>cI(e,y))}}function m(){let y=n.let("ruleErrs",null);return n.try(()=>f((0,we._)`await `),w=>n.assign(u,!1).if((0,we._)`${w} instanceof ${c.ValidationError}`,()=>n.assign(y,(0,we._)`${w}.errors`),()=>n.throw(w))),y}function p(){let y=(0,we._)`${d}.errors`;return n.assign(y,null),f(we.nil),y}function f(y=t.async?(0,we._)`await `:we.nil){let w=c.opts.passContext?dr.default.this:dr.default.self,b=!("compile"in t&&!a||t.schema===!1);n.assign(u,(0,we._)`${y}${(0,iI.callValidateCode)(e,d,w,b)}`,t.modifying)}function g(y){var w;n.if((0,we.not)((w=t.valid)!==null&&w!==void 0?w:u),y)}}it.funcKeywordCode=aI;function Pg(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,we._)`${n.parentData}[${n.parentDataProperty}]`))}function cI(e,t){let{gen:r}=e;r.if((0,we._)`Array.isArray(${t})`,()=>{r.assign(dr.default.vErrors,(0,we._)`${dr.default.vErrors} === null ? ${t} : ${dr.default.vErrors}.concat(${t})`).assign(dr.default.errors,(0,we._)`${dr.default.vErrors}.length`),(0,sI.extendErrors)(e)},()=>e.error())}function lI({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function Rg(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,we.stringify)(r)})}function uI(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}it.validSchemaType=uI;function dI({schema:e,opts:t,self:r,errSchemaPath:n},i,s){if(Array.isArray(i.keyword)?!i.keyword.includes(s):i.keyword!==s)throw new Error("ajv implementation error");let o=i.dependencies;if(o?.some(a=>!Object.prototype.hasOwnProperty.call(e,a)))throw new Error(`parent schema must have dependencies of ${s}: ${o.join(",")}`);if(i.validateSchema&&!i.validateSchema(e[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(i.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}it.validateKeywordUsage=dI});var Tg=v(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.extendSubschemaMode=Lt.extendSubschemaData=Lt.getSubschema=void 0;var st=T(),Cg=N();function fI(e,{keyword:t,schemaProp:r,schema:n,schemaPath:i,errSchemaPath:s,topSchemaRef:o}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return r===void 0?{schema:a,schemaPath:(0,st._)`${e.schemaPath}${(0,st.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,st._)`${e.schemaPath}${(0,st.getProperty)(t)}${(0,st.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Cg.escapeFragment)(r)}`}}if(n!==void 0){if(i===void 0||s===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:o,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Lt.getSubschema=fI;function pI(e,t,{dataProp:r,dataPropType:n,data:i,dataTypes:s,propertyName:o}){if(i!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(r!==void 0){let{errorPath:l,dataPathArr:d,opts:u}=t,h=a.let("data",(0,st._)`${t.data}${(0,st.getProperty)(r)}`,!0);c(h),e.errorPath=(0,st.str)`${l}${(0,Cg.getErrorPath)(r,n,u.jsPropertySyntax)}`,e.parentDataProperty=(0,st._)`${r}`,e.dataPathArr=[...d,e.parentDataProperty]}if(i!==void 0){let l=i instanceof st.Name?i:a.let("data",i,!0);c(l),o!==void 0&&(e.propertyName=o)}s&&(e.dataTypes=s);function c(l){e.data=l,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,l]}}Lt.extendSubschemaData=pI;function hI(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:i,allErrors:s}){n!==void 0&&(e.compositeRule=n),i!==void 0&&(e.createErrors=i),s!==void 0&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=r}Lt.extendSubschemaMode=hI});var Yl=v((xN,Dg)=>{"use strict";Dg.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,i,s;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(i=n;i--!==0;)if(!e(t[i],r[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(s=Object.keys(t),n=s.length,n!==Object.keys(r).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[i]))return!1;for(i=n;i--!==0;){var o=s[i];if(!e(t[o],r[o]))return!1}return!0}return t!==t&&r!==r}});var xg=v((jN,Og)=>{"use strict";var Ft=Og.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},i=r.post||function(){};so(t,n,i,e,"",e)};Ft.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Ft.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Ft.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Ft.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 so(e,t,r,n,i,s,o,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,i,s,o,a,c,l);for(var d in n){var u=n[d];if(Array.isArray(u)){if(d in Ft.arrayKeywords)for(var h=0;h<u.length;h++)so(e,t,r,u[h],i+"/"+d+"/"+h,s,i,d,n,h)}else if(d in Ft.propsKeywords){if(u&&typeof u=="object")for(var m in u)so(e,t,r,u[m],i+"/"+d+"/"+mI(m),s,i,d,n,m)}else(d in Ft.keywords||e.allKeys&&!(d in Ft.skipKeywords))&&so(e,t,r,u,i+"/"+d,s,i,d,n)}r(n,i,s,o,a,c,l)}}function mI(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var ni=v(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.getSchemaRefs=Ee.resolveUrl=Ee.normalizeId=Ee._getFullPath=Ee.getFullPath=Ee.inlineRef=void 0;var gI=N(),yI=Yl(),vI=xg(),wI=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function bI(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Xl(e):t?jg(e)<=t:!1}Ee.inlineRef=bI;var SI=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Xl(e){for(let t in e){if(SI.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Xl)||typeof r=="object"&&Xl(r))return!0}return!1}function jg(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!wI.has(r)&&(typeof e[r]=="object"&&(0,gI.eachItem)(e[r],n=>t+=jg(n)),t===1/0))return 1/0}return t}function Ng(e,t="",r){r!==!1&&(t=Hr(t));let n=e.parse(t);return qg(e,n)}Ee.getFullPath=Ng;function qg(e,t){return e.serialize(t).split("#")[0]+"#"}Ee._getFullPath=qg;var _I=/#\/?$/;function Hr(e){return e?e.replace(_I,""):""}Ee.normalizeId=Hr;function kI(e,t,r){return r=Hr(r),e.resolve(t,r)}Ee.resolveUrl=kI;var $I=/^[a-z_][-a-z0-9._]*$/i;function EI(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,i=Hr(e[r]||t),s={"":i},o=Ng(n,i,!1),a={},c=new Set;return vI(e,{allKeys:!0},(u,h,m,p)=>{if(p===void 0)return;let f=o+h,g=s[p];typeof u[r]=="string"&&(g=y.call(this,u[r])),w.call(this,u.$anchor),w.call(this,u.$dynamicAnchor),s[h]=g;function y(b){let $=this.opts.uriResolver.resolve;if(b=Hr(g?$(g,b):b),c.has(b))throw d(b);c.add(b);let S=this.refs[b];return typeof S=="string"&&(S=this.refs[S]),typeof S=="object"?l(u,S.schema,b):b!==Hr(f)&&(b[0]==="#"?(l(u,a[b],b),a[b]=u):this.refs[b]=f),b}function w(b){if(typeof b=="string"){if(!$I.test(b))throw new Error(`invalid anchor "${b}"`);y.call(this,`#${b}`)}}}),a;function l(u,h,m){if(h!==void 0&&!yI(u,h))throw d(m)}function d(u){return new Error(`reference "${u}" resolves to more than one schema`)}}Ee.getSchemaRefs=EI});var oi=v(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.getData=Vt.KeywordCxt=Vt.validateFunctionCode=void 0;var Bg=yg(),Mg=ri(),eu=Ul(),oo=ri(),II=$g(),si=Ag(),Zl=Tg(),P=T(),A=Oe(),PI=ni(),gt=N(),ii=ti();function RI(e){if(Gg(e)&&(Hg(e),Ug(e))){TI(e);return}Kg(e,()=>(0,Bg.topBoolOrEmptySchema)(e))}Vt.validateFunctionCode=RI;function Kg({gen:e,validateName:t,schema:r,schemaEnv:n,opts:i},s){i.code.es5?e.func(t,(0,P._)`${A.default.data}, ${A.default.valCxt}`,n.$async,()=>{e.code((0,P._)`"use strict"; ${Lg(r,i)}`),CI(e,i),e.code(s)}):e.func(t,(0,P._)`${A.default.data}, ${AI(i)}`,n.$async,()=>e.code(Lg(r,i)).code(s))}function AI(e){return(0,P._)`{${A.default.instancePath}="", ${A.default.parentData}, ${A.default.parentDataProperty}, ${A.default.rootData}=${A.default.data}${e.dynamicRef?(0,P._)`, ${A.default.dynamicAnchors}={}`:P.nil}}={}`}function CI(e,t){e.if(A.default.valCxt,()=>{e.var(A.default.instancePath,(0,P._)`${A.default.valCxt}.${A.default.instancePath}`),e.var(A.default.parentData,(0,P._)`${A.default.valCxt}.${A.default.parentData}`),e.var(A.default.parentDataProperty,(0,P._)`${A.default.valCxt}.${A.default.parentDataProperty}`),e.var(A.default.rootData,(0,P._)`${A.default.valCxt}.${A.default.rootData}`),t.dynamicRef&&e.var(A.default.dynamicAnchors,(0,P._)`${A.default.valCxt}.${A.default.dynamicAnchors}`)},()=>{e.var(A.default.instancePath,(0,P._)`""`),e.var(A.default.parentData,(0,P._)`undefined`),e.var(A.default.parentDataProperty,(0,P._)`undefined`),e.var(A.default.rootData,A.default.data),t.dynamicRef&&e.var(A.default.dynamicAnchors,(0,P._)`{}`)})}function TI(e){let{schema:t,opts:r,gen:n}=e;Kg(e,()=>{r.$comment&&t.$comment&&Wg(e),NI(e),n.let(A.default.vErrors,null),n.let(A.default.errors,0),r.unevaluated&&DI(e),zg(e),LI(e)})}function DI(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,P._)`${r}.evaluated`),t.if((0,P._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,P._)`${e.evaluated}.props`,(0,P._)`undefined`)),t.if((0,P._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,P._)`${e.evaluated}.items`,(0,P._)`undefined`))}function Lg(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,P._)`/*# sourceURL=${r} */`:P.nil}function OI(e,t){if(Gg(e)&&(Hg(e),Ug(e))){xI(e,t);return}(0,Bg.boolOrEmptySchema)(e,t)}function Ug({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function Gg(e){return typeof e.schema!="boolean"}function xI(e,t){let{schema:r,gen:n,opts:i}=e;i.$comment&&r.$comment&&Wg(e),qI(e),MI(e);let s=n.const("_errs",A.default.errors);zg(e,s),n.var(t,(0,P._)`${s} === ${A.default.errors}`)}function Hg(e){(0,gt.checkUnknownRules)(e),jI(e)}function zg(e,t){if(e.opts.jtd)return Fg(e,[],!1,t);let r=(0,Mg.getSchemaTypes)(e.schema),n=(0,Mg.coerceAndCheckDataType)(e,r);Fg(e,r,!n,t)}function jI(e){let{schema:t,errSchemaPath:r,opts:n,self:i}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,gt.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function NI(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,gt.checkStrictMode)(e,"default is ignored in the schema root")}function qI(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,PI.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function MI(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function Wg({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:i}){let s=r.$comment;if(i.$comment===!0)e.code((0,P._)`${A.default.self}.logger.log(${s})`);else if(typeof i.$comment=="function"){let o=(0,P.str)`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,P._)`${A.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function LI(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:i,opts:s}=e;r.$async?t.if((0,P._)`${A.default.errors} === 0`,()=>t.return(A.default.data),()=>t.throw((0,P._)`new ${i}(${A.default.vErrors})`)):(t.assign((0,P._)`${n}.errors`,A.default.vErrors),s.unevaluated&&FI(e),t.return((0,P._)`${A.default.errors} === 0`))}function FI({gen:e,evaluated:t,props:r,items:n}){r instanceof P.Name&&e.assign((0,P._)`${t}.props`,r),n instanceof P.Name&&e.assign((0,P._)`${t}.items`,n)}function Fg(e,t,r,n){let{gen:i,schema:s,data:o,allErrors:a,opts:c,self:l}=e,{RULES:d}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,gt.schemaHasRulesButRef)(s,d))){i.block(()=>Jg(e,"$ref",d.all.$ref.definition));return}c.jtd||VI(e,t),i.block(()=>{for(let h of d.rules)u(h);u(d.post)});function u(h){(0,eu.shouldUseGroup)(s,h)&&(h.type?(i.if((0,oo.checkDataType)(h.type,o,c.strictNumbers)),Vg(e,h),t.length===1&&t[0]===h.type&&r&&(i.else(),(0,oo.reportTypeError)(e)),i.endIf()):Vg(e,h),a||i.if((0,P._)`${A.default.errors} === ${n||0}`))}}function Vg(e,t){let{gen:r,schema:n,opts:{useDefaults:i}}=e;i&&(0,II.assignDefaults)(e,t.type),r.block(()=>{for(let s of t.rules)(0,eu.shouldUseRule)(n,s)&&Jg(e,s.keyword,s.definition,t.type)})}function VI(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(BI(e,t),e.opts.allowUnionTypes||KI(e,t),UI(e,e.dataTypes))}function BI(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{Qg(e.dataTypes,r)||tu(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),HI(e,t)}}function KI(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&tu(e,"use allowUnionTypes to allow union type keyword")}function UI(e,t){let r=e.self.RULES.all;for(let n in r){let i=r[n];if(typeof i=="object"&&(0,eu.shouldUseRule)(e.schema,i)){let{type:s}=i.definition;s.length&&!s.some(o=>GI(t,o))&&tu(e,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function GI(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Qg(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function HI(e,t){let r=[];for(let n of e.dataTypes)Qg(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function tu(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,gt.checkStrictMode)(e,t,e.opts.strictTypes)}var ao=class{constructor(t,r,n){if((0,si.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,gt.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",Yg(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,si.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",A.default.errors))}result(t,r,n){this.failResult((0,P.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,P.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,P._)`${r} !== undefined && (${(0,P.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?ii.reportExtraError:ii.reportError)(this,this.def.error,r)}$dataError(){(0,ii.reportError)(this,this.def.$dataError||ii.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ii.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=P.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=P.nil,r=P.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:s,def:o}=this;n.if((0,P.or)((0,P._)`${i} === undefined`,r)),t!==P.nil&&n.assign(t,!0),(s.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==P.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:i,it:s}=this;return(0,P.or)(o(),a());function o(){if(n.length){if(!(r instanceof P.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,P._)`${(0,oo.checkDataTypes)(c,r,s.opts.strictNumbers,oo.DataType.Wrong)}`}return P.nil}function a(){if(i.validateSchema){let c=t.scopeValue("validate$data",{ref:i.validateSchema});return(0,P._)`!${c}(${r})`}return P.nil}}subschema(t,r){let n=(0,Zl.getSubschema)(this.it,t);(0,Zl.extendSubschemaData)(n,this.it,t),(0,Zl.extendSubschemaMode)(n,t);let i={...this.it,...n,items:void 0,props:void 0};return OI(i,r),i}mergeEvaluated(t,r){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=gt.mergeEvaluated.props(i,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=gt.mergeEvaluated.items(i,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(r,()=>this.mergeEvaluated(t,P.Name)),!0}};Vt.KeywordCxt=ao;function Jg(e,t,r,n){let i=new ao(e,r,t);"code"in r?r.code(i,n):i.$data&&r.validate?(0,si.funcKeywordCode)(i,r):"macro"in r?(0,si.macroKeywordCode)(i,r):(r.compile||r.validate)&&(0,si.funcKeywordCode)(i,r)}var zI=/^\/(?:[^~]|~0|~1)*$/,WI=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Yg(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let i,s;if(e==="")return A.default.rootData;if(e[0]==="/"){if(!zI.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);i=e,s=A.default.rootData}else{let l=WI.exec(e);if(!l)throw new Error(`Invalid JSON-pointer: ${e}`);let d=+l[1];if(i=l[2],i==="#"){if(d>=t)throw new Error(c("property/index",d));return n[t-d]}if(d>t)throw new Error(c("data",d));if(s=r[t-d],!i)return s}let o=s,a=i.split("/");for(let l of a)l&&(s=(0,P._)`${s}${(0,P.getProperty)((0,gt.unescapeJsonPointer)(l))}`,o=(0,P._)`${o} && ${s}`);return o;function c(l,d){return`Cannot access ${l} ${d} levels up, current level is ${t}`}}Vt.getData=Yg});var co=v(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});var ru=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};nu.default=ru});var ai=v(ou=>{"use strict";Object.defineProperty(ou,"__esModule",{value:!0});var iu=ni(),su=class extends Error{constructor(t,r,n,i){super(i||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,iu.resolveUrl)(t,r,n),this.missingSchema=(0,iu.normalizeId)((0,iu.getFullPath)(t,this.missingRef))}};ou.default=su});var ci=v(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.resolveSchema=je.getCompilingSchema=je.resolveRef=je.compileSchema=je.SchemaEnv=void 0;var We=T(),QI=co(),fr=Oe(),Qe=ni(),Xg=N(),JI=oi(),zr=class{constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0,Qe.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};je.SchemaEnv=zr;function cu(e){let t=Zg.call(this,e);if(t)return t;let r=(0,Qe.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:s}=this.opts,o=new We.CodeGen(this.scope,{es5:n,lines:i,ownProperties:s}),a;e.$async&&(a=o.scopeValue("Error",{ref:QI.default,code:(0,We._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");e.validateName=c;let l={gen:o,allErrors:this.opts.allErrors,data:fr.default.data,parentData:fr.default.parentData,parentDataProperty:fr.default.parentDataProperty,dataNames:[fr.default.data],dataPathArr:[We.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,We.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:We.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,We._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(e),(0,JI.validateFunctionCode)(l),o.optimize(this.opts.code.optimize);let u=o.toString();d=`${o.scopeRefs(fr.default.scope)}return ${u}`,this.opts.code.process&&(d=this.opts.code.process(d,e));let m=new Function(`${fr.default.self}`,`${fr.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:m}),m.errors=null,m.schema=e.schema,m.schemaEnv=e,e.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:c,validateCode:u,scopeValues:o._values}),this.opts.unevaluated){let{props:p,items:f}=l;m.evaluated={props:p instanceof We.Name?void 0:p,items:f instanceof We.Name?void 0:f,dynamicProps:p instanceof We.Name,dynamicItems:f instanceof We.Name},m.source&&(m.source.evaluated=(0,We.stringify)(m.evaluated))}return e.validate=m,e}catch(u){throw delete e.validate,delete e.validateName,d&&this.logger.error("Error compiling schema, function code:",d),u}finally{this._compilations.delete(e)}}je.compileSchema=cu;function YI(e,t,r){var n;r=(0,Qe.resolveUrl)(this.opts.uriResolver,t,r);let i=e.refs[r];if(i)return i;let s=eP.call(this,e,r);if(s===void 0){let o=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;o&&(s=new zr({schema:o,schemaId:a,root:e,baseId:t}))}if(s!==void 0)return e.refs[r]=XI.call(this,s)}je.resolveRef=YI;function XI(e){return(0,Qe.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:cu.call(this,e)}function Zg(e){for(let t of this._compilations)if(ZI(t,e))return t}je.getCompilingSchema=Zg;function ZI(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function eP(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||lo.call(this,e,t)}function lo(e,t){let r=this.opts.uriResolver.parse(t),n=(0,Qe._getFullPath)(this.opts.uriResolver,r),i=(0,Qe.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===i)return au.call(this,r,e);let s=(0,Qe.normalizeId)(n),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=lo.call(this,e,o);return typeof a?.schema!="object"?void 0:au.call(this,r,a)}if(typeof o?.schema=="object"){if(o.validate||cu.call(this,o),s===(0,Qe.normalizeId)(t)){let{schema:a}=o,{schemaId:c}=this.opts,l=a[c];return l&&(i=(0,Qe.resolveUrl)(this.opts.uriResolver,i,l)),new zr({schema:a,schemaId:c,root:e,baseId:i})}return au.call(this,r,o)}}je.resolveSchema=lo;var tP=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function au(e,{baseId:t,schema:r,root:n}){var i;if(((i=e.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Xg.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!tP.has(a)&&l&&(t=(0,Qe.resolveUrl)(this.opts.uriResolver,t,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Xg.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Qe.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=lo.call(this,n,a)}let{schemaId:o}=this.opts;if(s=s||new zr({schema:r,schemaId:o,root:n,baseId:t}),s.schema!==s.root.schema)return s}});var ey=v((VN,rP)=>{rP.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var du=v((BN,oy)=>{"use strict";var nP=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),ry=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),lu=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),ny=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),iP=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function uu(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}var sP=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function ty(e){return e.length=0,!0}function oP(e,t,r){if(e.length){let n=uu(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function aP(e){let t=0,r={error:!1,address:"",zone:""},n=[],i=[],s=!1,o=!1,a=oP;for(let c=0;c<e.length;c++){let l=e[c];if(!(l==="["||l==="]"))if(l===":"){if(s===!0&&(o=!0),!a(i,n,r))break;if(++t>7){r.error=!0;break}c>0&&e[c-1]===":"&&(s=!0),n.push(":");continue}else if(l==="%"){if(!a(i,n,r))break;a=ty}else{i.push(l);continue}}return i.length&&(a===ty?r.zone=i.join(""):o?n.push(i.join("")):n.push(uu(i))),r.address=n.join(""),r}function iy(e){if(cP(e,":")<2)return{host:e,isIPV6:!1};let t=aP(e);if(t.error)return{host:e,isIPV6:!1};{let r=t.address,n=t.address;return t.zone&&(r+="%"+t.zone,n+="%25"+t.zone),{host:r,isIPV6:!0,escapedHost:n}}}function cP(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function lP(e){let t=e,r=[],n=-1,i=0;for(;i=t.length;){if(i===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(i===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(i===3&&t==="/.."){r.length!==0&&r.pop(),r.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),r.length!==0&&r.pop();continue}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}var uP={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},dP=/[@/?#:]/g,fP=/[@/?#]/g;function sy(e,t){let r=t?fP:dP;return r.lastIndex=0,e.replace(r,n=>uP[n])}function pP(e,t=!1){if(e.indexOf("%")===-1)return e;let r="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let i=e.slice(n+1,n+3);if(lu(i)){let s=i.toUpperCase(),o=String.fromCharCode(parseInt(s,16));t&&ny(o)?r+=o:r+="%"+s,n+=2;continue}}r+=e[n]}return r}function hP(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(lu(n)){let i=n.toUpperCase(),s=String.fromCharCode(parseInt(i,16));s!=="."&&ny(s)?t+=s:t+="%"+i,r+=2;continue}}iP(e[r])?t+=e[r]:t+=escape(e[r])}return t}function mP(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(lu(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function gP(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!ry(r)){let n=iy(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=sy(r,!1)}t.push(r)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}oy.exports={nonSimpleDomain:sP,recomposeAuthority:gP,reescapeHostDelimiters:sy,normalizePercentEncoding:pP,normalizePathEncoding:hP,escapePreservingEscapes:mP,removeDotSegments:lP,isIPv4:ry,isUUID:nP,normalizeIPv6:iy,stringArrayToHexStripped:uu}});var dy=v((KN,uy)=>{"use strict";var{isUUID:yP}=du(),vP=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,wP=["http","https","ws","wss","urn","urn:uuid"];function bP(e){return wP.indexOf(e)!==-1}function fu(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 ay(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function cy(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function SP(e){return e.secure=fu(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function _P(e){if((e.port===(fu(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){let[t,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}function kP(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(vP);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let i=`${n}:${t.nid||e.nid}`,s=pu(i);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function $P(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),i=`${r}:${t.nid||n}`,s=pu(i);s&&(e=s.serialize(e,t));let o=e,a=e.nss;return o.path=`${n||t.nid}:${a}`,t.skipEscape=!0,o}function EP(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!yP(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function IP(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var ly={scheme:"http",domainHost:!0,parse:ay,serialize:cy},PP={scheme:"https",domainHost:ly.domainHost,parse:ay,serialize:cy},uo={scheme:"ws",domainHost:!0,parse:SP,serialize:_P},RP={scheme:"wss",domainHost:uo.domainHost,parse:uo.parse,serialize:uo.serialize},AP={scheme:"urn",parse:kP,serialize:$P,skipNormalize:!0},CP={scheme:"urn:uuid",parse:EP,serialize:IP,skipNormalize:!0},fo={http:ly,https:PP,ws:uo,wss:RP,urn:AP,"urn:uuid":CP};Object.setPrototypeOf(fo,null);function pu(e){return e&&(fo[e]||fo[e.toLowerCase()])||void 0}uy.exports={wsIsSecure:fu,SCHEMES:fo,isValidSchemeName:bP,getSchemeHandler:pu}});var yy=v((UN,po)=>{"use strict";var{normalizeIPv6:TP,removeDotSegments:li,recomposeAuthority:DP,normalizePercentEncoding:OP,normalizePathEncoding:xP,escapePreservingEscapes:jP,reescapeHostDelimiters:NP,isIPv4:qP,nonSimpleDomain:MP}=du(),{SCHEMES:LP,getSchemeHandler:py}=dy();function FP(e,t){return typeof e=="string"?e=GP(e,t):typeof e=="object"&&(e=Wr(pr(e,t),t)),e}function VP(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},i=hy(Wr(e,n),Wr(t,n),n,!0);return n.skipEscape=!0,pr(i,n)}function hy(e,t,r,n){let i={};return n||(e=Wr(pr(e,r),r),t=Wr(pr(t,r),r)),r=r||{},!r.tolerant&&t.scheme?(i.scheme=t.scheme,i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=li(t.path||""),i.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=li(t.path||""),i.query=t.query):(t.path?(t.path[0]==="/"?i.path=li(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?i.path="/"+t.path:e.path?i.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:i.path=t.path,i.path=li(i.path)),i.query=t.query):(i.path=e.path,t.query!==void 0?i.query=t.query:i.query=e.query),i.userinfo=e.userinfo,i.host=e.host,i.port=e.port),i.scheme=e.scheme),i.fragment=t.fragment,i}function BP(e,t,r){let n=fy(e,r),i=fy(t,r);return n!==void 0&&i!==void 0&&n.toLowerCase()===i.toLowerCase()}function pr(e,t){let r={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:""},n=Object.assign({},t),i=[],s=py(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=OP(r.path):(r.path=jP(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&i.push(r.scheme,":");let o=DP(r);if(o!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(o),r.path&&r.path[0]!=="/"&&i.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=li(a)),o===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),i.push(a)}return r.query!==void 0&&i.push("?",r.query),r.fragment!==void 0&&i.push("#",r.fragment),i.join("")}var KP=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function UP(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 my(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=!1,s=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let o=e.match(KP);if(o){n.scheme=o[1],n.userinfo=o[3],n.host=o[4],n.port=parseInt(o[5],10),n.path=o[6]||"",n.query=o[7],n.fragment=o[8],isNaN(n.port)&&(n.port=o[5]);let a=UP(n,o);if(a!==void 0&&(n.error=n.error||a,i=!0),n.host)if(qP(n.host)===!1){let d=TP(n.host);n.host=d.host.toLowerCase(),s=d.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let c=py(r.scheme||n.scheme);if(!r.unicodeSupport&&(!c||!c.unicodeSupport)&&n.host&&(r.domainHost||c&&c.domainHost)&&s===!1&&MP(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(l){n.error=n.error||"Host's domain name can not be converted to ASCII: "+l}if((!c||c&&!c.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=NP(unescape(n.host),s))),n.path&&(n.path=xP(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}c&&c.parse&&c.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:i}}function Wr(e,t){return my(e,t).parsed}function GP(e,t){return gy(e,t).normalized}function gy(e,t){let{parsed:r,malformedAuthorityOrPort:n}=my(e,t);return{normalized:n?e:pr(r,t),malformedAuthorityOrPort:n}}function fy(e,t){if(typeof e=="string"){let{normalized:r,malformedAuthorityOrPort:n}=gy(e,t);return n?void 0:r}if(typeof e=="object")return pr(e,t)}var hu={SCHEMES:LP,normalize:FP,resolve:VP,resolveComponent:hy,equal:BP,serialize:pr,parse:Wr};po.exports=hu;po.exports.default=hu;po.exports.fastUri=hu});var wy=v(mu=>{"use strict";Object.defineProperty(mu,"__esModule",{value:!0});var vy=yy();vy.code='require("ajv/dist/runtime/uri").default';mu.default=vy});var Py=v(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.CodeGen=le.Name=le.nil=le.stringify=le.str=le._=le.KeywordCxt=void 0;var HP=oi();Object.defineProperty(le,"KeywordCxt",{enumerable:!0,get:function(){return HP.KeywordCxt}});var Qr=T();Object.defineProperty(le,"_",{enumerable:!0,get:function(){return Qr._}});Object.defineProperty(le,"str",{enumerable:!0,get:function(){return Qr.str}});Object.defineProperty(le,"stringify",{enumerable:!0,get:function(){return Qr.stringify}});Object.defineProperty(le,"nil",{enumerable:!0,get:function(){return Qr.nil}});Object.defineProperty(le,"Name",{enumerable:!0,get:function(){return Qr.Name}});Object.defineProperty(le,"CodeGen",{enumerable:!0,get:function(){return Qr.CodeGen}});var zP=co(),$y=ai(),WP=Kl(),ui=ci(),QP=T(),di=ni(),ho=ri(),yu=N(),by=ey(),JP=wy(),Ey=(e,t)=>new RegExp(e,t);Ey.code="new RegExp";var YP=["removeAdditional","useDefaults","coerceTypes"],XP=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),ZP={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."},eR={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Sy=200;function tR(e){var t,r,n,i,s,o,a,c,l,d,u,h,m,p,f,g,y,w,b,$,S,I,k,_,q;let Q=e.strict,re=(t=e.code)===null||t===void 0?void 0:t.optimize,te=re===!0||re===void 0?1:re||0,Jt=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Ey,IS=(i=e.uriResolver)!==null&&i!==void 0?i:JP.default;return{strictSchema:(o=(s=e.strictSchema)!==null&&s!==void 0?s:Q)!==null&&o!==void 0?o:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:Q)!==null&&c!==void 0?c:!0,strictTypes:(d=(l=e.strictTypes)!==null&&l!==void 0?l:Q)!==null&&d!==void 0?d:"log",strictTuples:(h=(u=e.strictTuples)!==null&&u!==void 0?u:Q)!==null&&h!==void 0?h:"log",strictRequired:(p=(m=e.strictRequired)!==null&&m!==void 0?m:Q)!==null&&p!==void 0?p:!1,code:e.code?{...e.code,optimize:te,regExp:Jt}:{optimize:te,regExp:Jt},loopRequired:(f=e.loopRequired)!==null&&f!==void 0?f:Sy,loopEnum:(g=e.loopEnum)!==null&&g!==void 0?g:Sy,meta:(y=e.meta)!==null&&y!==void 0?y:!0,messages:(w=e.messages)!==null&&w!==void 0?w:!0,inlineRefs:(b=e.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:($=e.schemaId)!==null&&$!==void 0?$:"$id",addUsedSchema:(S=e.addUsedSchema)!==null&&S!==void 0?S:!0,validateSchema:(I=e.validateSchema)!==null&&I!==void 0?I:!0,validateFormats:(k=e.validateFormats)!==null&&k!==void 0?k:!0,unicodeRegExp:(_=e.unicodeRegExp)!==null&&_!==void 0?_:!0,int32range:(q=e.int32range)!==null&&q!==void 0?q:!0,uriResolver:IS}}var fi=class{constructor(t={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...tR(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new QP.ValueScope({scope:{},prefixes:XP,es5:r,lines:n}),this.logger=aR(t.logger);let i=t.validateFormats;t.validateFormats=!1,this.RULES=(0,WP.getRules)(),_y.call(this,ZP,t,"NOT SUPPORTED"),_y.call(this,eR,t,"DEPRECATED","warn"),this._metaOpts=sR.call(this),t.formats&&nR.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&iR.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),rR.call(this),t.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,i=by;n==="id"&&(i={...by},i.id=i.$id,delete i.$id),r&&t&&this.addMetaSchema(i,i[n],!1)}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[r]||t:void 0}validate(t,r){let n;if(typeof t=="string"){if(n=this.getSchema(t),!n)throw new Error(`no schema with key or ref "${t}"`)}else n=this.compile(t);let i=n(r);return"$async"in n||(this.errors=n.errors),i}compile(t,r){let n=this._addSchema(t,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(t,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return i.call(this,t,r);async function i(d,u){await s.call(this,d.$schema);let h=this._addSchema(d,u);return h.validate||o.call(this,h)}async function s(d){d&&!this.getSchema(d)&&await i.call(this,{$ref:d},!0)}async function o(d){try{return this._compileSchemaEnv(d)}catch(u){if(!(u instanceof $y.default))throw u;return a.call(this,u),await c.call(this,u.missingSchema),o.call(this,d)}}function a({missingSchema:d,missingRef:u}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${u} cannot be resolved`)}async function c(d){let u=await l.call(this,d);this.refs[d]||await s.call(this,u.$schema),this.refs[d]||this.addSchema(u,d,r)}async function l(d){let u=this._loading[d];if(u)return u;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(t,r,n,i=this.opts.validateSchema){if(Array.isArray(t)){for(let o of t)this.addSchema(o,void 0,n,i);return this}let s;if(typeof t=="object"){let{schemaId:o}=this.opts;if(s=t[o],s!==void 0&&typeof s!="string")throw new Error(`schema ${o} must be string`)}return r=(0,di.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,i,!0),this}addMetaSchema(t,r,n=this.opts.validateSchema){return this.addSchema(t,r,!0,n),this}validateSchema(t,r){if(typeof t=="boolean")return!0;let n;if(n=t.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let i=this.validate(n,t);if(!i&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return i}getSchema(t){let r;for(;typeof(r=ky.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,i=new ui.SchemaEnv({schema:{},schemaId:n});if(r=ui.resolveSchema.call(this,i,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=ky.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0,di.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(lR.call(this,n,r),!r)return(0,yu.eachItem)(n,s=>gu.call(this,s)),this;dR.call(this,r);let i={...r,type:(0,ho.getJSONTypes)(r.type),schemaType:(0,ho.getJSONTypes)(r.schemaType)};return(0,yu.eachItem)(n,i.type.length===0?s=>gu.call(this,s,i):s=>i.type.forEach(o=>gu.call(this,s,i,o))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let i=n.rules.findIndex(s=>s.keyword===t);i>=0&&n.rules.splice(i,1)}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!t||t.length===0?"No errors":t.map(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,s)=>i+r+s)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let i of r){let s=i.split("/").slice(1),o=t;for(let a of s)o=o[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,d=o[a];l&&d&&(o[a]=Iy(d))}}return t}_removeAllSchemas(t,r){for(let n in t){let i=t[n];(!r||r.test(n))&&(typeof i=="string"?delete t[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete t[n]))}}_addSchema(t,r,n,i=this.opts.validateSchema,s=this.opts.addUsedSchema){let o,{schemaId:a}=this.opts;if(typeof t=="object")o=t[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(t);if(c!==void 0)return c;n=(0,di.normalizeId)(o||n);let l=di.getSchemaRefs.call(this,t,n);return c=new ui.SchemaEnv({schema:t,schemaId:a,meta:r,baseId:n,localRefs:l}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),i&&this.validateSchema(t,!0),c}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):ui.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{ui.compileSchema.call(this,t)}finally{this.opts=r}}};fi.ValidationError=zP.default;fi.MissingRefError=$y.default;le.default=fi;function _y(e,t,r,n="error"){for(let i in e){let s=i;s in t&&this.logger[n](`${r}: option ${i}. ${e[s]}`)}}function ky(e){return e=(0,di.normalizeId)(e),this.schemas[e]||this.refs[e]}function rR(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function nR(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function iR(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}function sR(){let e={...this.opts};for(let t of YP)delete e[t];return e}var oR={log(){},warn(){},error(){}};function aR(e){if(e===!1)return oR;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}var cR=/^[a-z_$][a-z0-9_$:-]*$/i;function lR(e,t){let{RULES:r}=this;if((0,yu.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!cR.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function gu(e,t,r){var n;let i=t?.post;if(r&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,o=i?s.post:s.rules.find(({type:c})=>c===r);if(o||(o={type:r,rules:[]},s.rules.push(o)),s.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,ho.getJSONTypes)(t.type),schemaType:(0,ho.getJSONTypes)(t.schemaType)}};t.before?uR.call(this,o,a,t.before):o.rules.push(a),s.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function uR(e,t,r){let n=e.rules.findIndex(i=>i.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function dR(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Iy(t)),e.validateSchema=this.compile(t,!0))}var fR={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Iy(e){return{anyOf:[e,fR]}}});var Ry=v(vu=>{"use strict";Object.defineProperty(vu,"__esModule",{value:!0});var pR={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};vu.default=pR});var yo=v(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.callRef=hr.getValidate=void 0;var hR=ai(),Ay=xe(),Ie=T(),Jr=Oe(),Cy=ci(),mo=N(),mR={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:i,schemaEnv:s,validateName:o,opts:a,self:c}=n,{root:l}=s;if((r==="#"||r==="#/")&&i===l.baseId)return u();let d=Cy.resolveRef.call(c,l,i,r);if(d===void 0)throw new hR.default(n.opts.uriResolver,i,r);if(d instanceof Cy.SchemaEnv)return h(d);return m(d);function u(){if(s===l)return go(e,o,s,s.$async);let p=t.scopeValue("root",{ref:l});return go(e,(0,Ie._)`${p}.validate`,l,l.$async)}function h(p){let f=Ty(e,p);go(e,f,p,p.$async)}function m(p){let f=t.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,Ie.stringify)(p)}:{ref:p}),g=t.name("valid"),y=e.subschema({schema:p,dataTypes:[],schemaPath:Ie.nil,topSchemaRef:f,errSchemaPath:r},g);e.mergeEvaluated(y),e.ok(g)}}};function Ty(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Ie._)`${r.scopeValue("wrapper",{ref:t})}.validate`}hr.getValidate=Ty;function go(e,t,r,n){let{gen:i,it:s}=e,{allErrors:o,schemaEnv:a,opts:c}=s,l=c.passContext?Jr.default.this:Ie.nil;n?d():u();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let p=i.let("valid");i.try(()=>{i.code((0,Ie._)`await ${(0,Ay.callValidateCode)(e,t,l)}`),m(t),o||i.assign(p,!0)},f=>{i.if((0,Ie._)`!(${f} instanceof ${s.ValidationError})`,()=>i.throw(f)),h(f),o||i.assign(p,!1)}),e.ok(p)}function u(){e.result((0,Ay.callValidateCode)(e,t,l),()=>m(t),()=>h(t))}function h(p){let f=(0,Ie._)`${p}.errors`;i.assign(Jr.default.vErrors,(0,Ie._)`${Jr.default.vErrors} === null ? ${f} : ${Jr.default.vErrors}.concat(${f})`),i.assign(Jr.default.errors,(0,Ie._)`${Jr.default.vErrors}.length`)}function m(p){var f;if(!s.opts.unevaluated)return;let g=(f=r?.validate)===null||f===void 0?void 0:f.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=mo.mergeEvaluated.props(i,g.props,s.props));else{let y=i.var("props",(0,Ie._)`${p}.evaluated.props`);s.props=mo.mergeEvaluated.props(i,y,s.props,Ie.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=mo.mergeEvaluated.items(i,g.items,s.items));else{let y=i.var("items",(0,Ie._)`${p}.evaluated.items`);s.items=mo.mergeEvaluated.items(i,y,s.items,Ie.Name)}}}hr.callRef=go;hr.default=mR});var Dy=v(wu=>{"use strict";Object.defineProperty(wu,"__esModule",{value:!0});var gR=Ry(),yR=yo(),vR=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",gR.default,yR.default];wu.default=vR});var Oy=v(bu=>{"use strict";Object.defineProperty(bu,"__esModule",{value:!0});var vo=T(),Bt=vo.operators,wo={maximum:{okStr:"<=",ok:Bt.LTE,fail:Bt.GT},minimum:{okStr:">=",ok:Bt.GTE,fail:Bt.LT},exclusiveMaximum:{okStr:"<",ok:Bt.LT,fail:Bt.GTE},exclusiveMinimum:{okStr:">",ok:Bt.GT,fail:Bt.LTE}},wR={message:({keyword:e,schemaCode:t})=>(0,vo.str)`must be ${wo[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,vo._)`{comparison: ${wo[e].okStr}, limit: ${t}}`},bR={keyword:Object.keys(wo),type:"number",schemaType:"number",$data:!0,error:wR,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,vo._)`${r} ${wo[t].fail} ${n} || isNaN(${r})`)}};bu.default=bR});var xy=v(Su=>{"use strict";Object.defineProperty(Su,"__esModule",{value:!0});var pi=T(),SR={message:({schemaCode:e})=>(0,pi.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,pi._)`{multipleOf: ${e}}`},_R={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:SR,code(e){let{gen:t,data:r,schemaCode:n,it:i}=e,s=i.opts.multipleOfPrecision,o=t.let("res"),a=s?(0,pi._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,pi._)`${o} !== parseInt(${o})`;e.fail$data((0,pi._)`(${n} === 0 || (${o} = ${r}/${n}, ${a}))`)}};Su.default=_R});var Ny=v(_u=>{"use strict";Object.defineProperty(_u,"__esModule",{value:!0});function jy(e){let t=e.length,r=0,n=0,i;for(;n<t;)r++,i=e.charCodeAt(n++),i>=55296&&i<=56319&&n<t&&(i=e.charCodeAt(n),(i&64512)===56320&&n++);return r}_u.default=jy;jy.code='require("ajv/dist/runtime/ucs2length").default'});var qy=v(ku=>{"use strict";Object.defineProperty(ku,"__esModule",{value:!0});var mr=T(),kR=N(),$R=Ny(),ER={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,mr.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,mr._)`{limit: ${e}}`},IR={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:ER,code(e){let{keyword:t,data:r,schemaCode:n,it:i}=e,s=t==="maxLength"?mr.operators.GT:mr.operators.LT,o=i.opts.unicode===!1?(0,mr._)`${r}.length`:(0,mr._)`${(0,kR.useFunc)(e.gen,$R.default)}(${r})`;e.fail$data((0,mr._)`${o} ${s} ${n}`)}};ku.default=IR});var My=v($u=>{"use strict";Object.defineProperty($u,"__esModule",{value:!0});var PR=xe(),RR=N(),Yr=T(),AR={message:({schemaCode:e})=>(0,Yr.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,Yr._)`{pattern: ${e}}`},CR={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:AR,code(e){let{gen:t,data:r,$data:n,schema:i,schemaCode:s,it:o}=e,a=o.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=o.opts.code,l=c.code==="new RegExp"?(0,Yr._)`new RegExp`:(0,RR.useFunc)(t,c),d=t.let("valid");t.try(()=>t.assign(d,(0,Yr._)`${l}(${s}, ${a}).test(${r})`),()=>t.assign(d,!1)),e.fail$data((0,Yr._)`!${d}`)}else{let c=(0,PR.usePattern)(e,i);e.fail$data((0,Yr._)`!${c}.test(${r})`)}}};$u.default=CR});var Ly=v(Eu=>{"use strict";Object.defineProperty(Eu,"__esModule",{value:!0});var hi=T(),TR={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,hi.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,hi._)`{limit: ${e}}`},DR={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:TR,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxProperties"?hi.operators.GT:hi.operators.LT;e.fail$data((0,hi._)`Object.keys(${r}).length ${i} ${n}`)}};Eu.default=DR});var Fy=v(Iu=>{"use strict";Object.defineProperty(Iu,"__esModule",{value:!0});var mi=xe(),gi=T(),OR=N(),xR={message:({params:{missingProperty:e}})=>(0,gi.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,gi._)`{missingProperty: ${e}}`},jR={keyword:"required",type:"object",schemaType:"array",$data:!0,error:xR,code(e){let{gen:t,schema:r,schemaCode:n,data:i,$data:s,it:o}=e,{opts:a}=o;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(o.allErrors?l():d(),a.strictRequired){let m=e.parentSchema.properties,{definedProperties:p}=e.it;for(let f of r)if(m?.[f]===void 0&&!p.has(f)){let g=o.schemaEnv.baseId+o.errSchemaPath,y=`required property "${f}" is not defined at "${g}" (strictRequired)`;(0,OR.checkStrictMode)(o,y,o.opts.strictRequired)}}function l(){if(c||s)e.block$data(gi.nil,u);else for(let m of r)(0,mi.checkReportMissingProp)(e,m)}function d(){let m=t.let("missing");if(c||s){let p=t.let("valid",!0);e.block$data(p,()=>h(m,p)),e.ok(p)}else t.if((0,mi.checkMissingProp)(e,r,m)),(0,mi.reportMissingProp)(e,m),t.else()}function u(){t.forOf("prop",n,m=>{e.setParams({missingProperty:m}),t.if((0,mi.noPropertyInData)(t,i,m,a.ownProperties),()=>e.error())})}function h(m,p){e.setParams({missingProperty:m}),t.forOf(m,n,()=>{t.assign(p,(0,mi.propertyInData)(t,i,m,a.ownProperties)),t.if((0,gi.not)(p),()=>{e.error(),t.break()})},gi.nil)}}};Iu.default=jR});var Vy=v(Pu=>{"use strict";Object.defineProperty(Pu,"__esModule",{value:!0});var yi=T(),NR={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,yi.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,yi._)`{limit: ${e}}`},qR={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:NR,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxItems"?yi.operators.GT:yi.operators.LT;e.fail$data((0,yi._)`${r}.length ${i} ${n}`)}};Pu.default=qR});var bo=v(Ru=>{"use strict";Object.defineProperty(Ru,"__esModule",{value:!0});var By=Yl();By.code='require("ajv/dist/runtime/equal").default';Ru.default=By});var Ky=v(Cu=>{"use strict";Object.defineProperty(Cu,"__esModule",{value:!0});var Au=ri(),ue=T(),MR=N(),LR=bo(),FR={message:({params:{i:e,j:t}})=>(0,ue.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,ue._)`{i: ${e}, j: ${t}}`},VR={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:FR,code(e){let{gen:t,data:r,$data:n,schema:i,parentSchema:s,schemaCode:o,it:a}=e;if(!n&&!i)return;let c=t.let("valid"),l=s.items?(0,Au.getSchemaTypes)(s.items):[];e.block$data(c,d,(0,ue._)`${o} === false`),e.ok(c);function d(){let p=t.let("i",(0,ue._)`${r}.length`),f=t.let("j");e.setParams({i:p,j:f}),t.assign(c,!0),t.if((0,ue._)`${p} > 1`,()=>(u()?h:m)(p,f))}function u(){return l.length>0&&!l.some(p=>p==="object"||p==="array")}function h(p,f){let g=t.name("item"),y=(0,Au.checkDataTypes)(l,g,a.opts.strictNumbers,Au.DataType.Wrong),w=t.const("indices",(0,ue._)`{}`);t.for((0,ue._)`;${p}--;`,()=>{t.let(g,(0,ue._)`${r}[${p}]`),t.if(y,(0,ue._)`continue`),l.length>1&&t.if((0,ue._)`typeof ${g} == "string"`,(0,ue._)`${g} += "_"`),t.if((0,ue._)`typeof ${w}[${g}] == "number"`,()=>{t.assign(f,(0,ue._)`${w}[${g}]`),e.error(),t.assign(c,!1).break()}).code((0,ue._)`${w}[${g}] = ${p}`)})}function m(p,f){let g=(0,MR.useFunc)(t,LR.default),y=t.name("outer");t.label(y).for((0,ue._)`;${p}--;`,()=>t.for((0,ue._)`${f} = ${p}; ${f}--;`,()=>t.if((0,ue._)`${g}(${r}[${p}], ${r}[${f}])`,()=>{e.error(),t.assign(c,!1).break(y)})))}}};Cu.default=VR});var Uy=v(Du=>{"use strict";Object.defineProperty(Du,"__esModule",{value:!0});var Tu=T(),BR=N(),KR=bo(),UR={message:"must be equal to constant",params:({schemaCode:e})=>(0,Tu._)`{allowedValue: ${e}}`},GR={keyword:"const",$data:!0,error:UR,code(e){let{gen:t,data:r,$data:n,schemaCode:i,schema:s}=e;n||s&&typeof s=="object"?e.fail$data((0,Tu._)`!${(0,BR.useFunc)(t,KR.default)}(${r}, ${i})`):e.fail((0,Tu._)`${s} !== ${r}`)}};Du.default=GR});var Gy=v(Ou=>{"use strict";Object.defineProperty(Ou,"__esModule",{value:!0});var vi=T(),HR=N(),zR=bo(),WR={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,vi._)`{allowedValues: ${e}}`},QR={keyword:"enum",schemaType:"array",$data:!0,error:WR,code(e){let{gen:t,data:r,$data:n,schema:i,schemaCode:s,it:o}=e;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let a=i.length>=o.opts.loopEnum,c,l=()=>c??(c=(0,HR.useFunc)(t,zR.default)),d;if(a||n)d=t.let("valid"),e.block$data(d,u);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let m=t.const("vSchema",s);d=(0,vi.or)(...i.map((p,f)=>h(m,f)))}e.pass(d);function u(){t.assign(d,!1),t.forOf("v",s,m=>t.if((0,vi._)`${l()}(${r}, ${m})`,()=>t.assign(d,!0).break()))}function h(m,p){let f=i[p];return typeof f=="object"&&f!==null?(0,vi._)`${l()}(${r}, ${m}[${p}])`:(0,vi._)`${r} === ${f}`}}};Ou.default=QR});var Hy=v(xu=>{"use strict";Object.defineProperty(xu,"__esModule",{value:!0});var JR=Oy(),YR=xy(),XR=qy(),ZR=My(),eA=Ly(),tA=Fy(),rA=Vy(),nA=Ky(),iA=Uy(),sA=Gy(),oA=[JR.default,YR.default,XR.default,ZR.default,eA.default,tA.default,rA.default,nA.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},iA.default,sA.default];xu.default=oA});var Nu=v(wi=>{"use strict";Object.defineProperty(wi,"__esModule",{value:!0});wi.validateAdditionalItems=void 0;var gr=T(),ju=N(),aA={message:({params:{len:e}})=>(0,gr.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,gr._)`{limit: ${e}}`},cA={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:aA,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,ju.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}zy(e,n)}};function zy(e,t){let{gen:r,schema:n,data:i,keyword:s,it:o}=e;o.items=!0;let a=r.const("len",(0,gr._)`${i}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,gr._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,ju.alwaysValidSchema)(o,n)){let l=r.var("valid",(0,gr._)`${a} <= ${t.length}`);r.if((0,gr.not)(l),()=>c(l)),e.ok(l)}function c(l){r.forRange("i",t.length,a,d=>{e.subschema({keyword:s,dataProp:d,dataPropType:ju.Type.Num},l),o.allErrors||r.if((0,gr.not)(l),()=>r.break())})}}wi.validateAdditionalItems=zy;wi.default=cA});var qu=v(bi=>{"use strict";Object.defineProperty(bi,"__esModule",{value:!0});bi.validateTuple=void 0;var Wy=T(),So=N(),lA=xe(),uA={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return Qy(e,"additionalItems",t);r.items=!0,!(0,So.alwaysValidSchema)(r,t)&&e.ok((0,lA.validateArray)(e))}};function Qy(e,t,r=e.schema){let{gen:n,parentSchema:i,data:s,keyword:o,it:a}=e;d(i),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=So.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,Wy._)`${s}.length`);r.forEach((u,h)=>{(0,So.alwaysValidSchema)(a,u)||(n.if((0,Wy._)`${l} > ${h}`,()=>e.subschema({keyword:o,schemaProp:h,dataProp:h},c)),e.ok(c))});function d(u){let{opts:h,errSchemaPath:m}=a,p=r.length,f=p===u.minItems&&(p===u.maxItems||u[t]===!1);if(h.strictTuples&&!f){let g=`"${o}" is ${p}-tuple, but minItems or maxItems/${t} are not specified or different at path "${m}"`;(0,So.checkStrictMode)(a,g,h.strictTuples)}}}bi.validateTuple=Qy;bi.default=uA});var Jy=v(Mu=>{"use strict";Object.defineProperty(Mu,"__esModule",{value:!0});var dA=qu(),fA={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,dA.validateTuple)(e,"items")};Mu.default=fA});var Xy=v(Lu=>{"use strict";Object.defineProperty(Lu,"__esModule",{value:!0});var Yy=T(),pA=N(),hA=xe(),mA=Nu(),gA={message:({params:{len:e}})=>(0,Yy.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Yy._)`{limit: ${e}}`},yA={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:gA,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:i}=r;n.items=!0,!(0,pA.alwaysValidSchema)(n,t)&&(i?(0,mA.validateAdditionalItems)(e,i):e.ok((0,hA.validateArray)(e)))}};Lu.default=yA});var Zy=v(Fu=>{"use strict";Object.defineProperty(Fu,"__esModule",{value:!0});var Ne=T(),_o=N(),vA={message:({params:{min:e,max:t}})=>t===void 0?(0,Ne.str)`must contain at least ${e} valid item(s)`:(0,Ne.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,Ne._)`{minContains: ${e}}`:(0,Ne._)`{minContains: ${e}, maxContains: ${t}}`},wA={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:vA,code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:s}=e,o,a,{minContains:c,maxContains:l}=n;s.opts.next?(o=c===void 0?1:c,a=l):o=1;let d=t.const("len",(0,Ne._)`${i}.length`);if(e.setParams({min:o,max:a}),a===void 0&&o===0){(0,_o.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,_o.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,_o.alwaysValidSchema)(s,r)){let f=(0,Ne._)`${d} >= ${o}`;a!==void 0&&(f=(0,Ne._)`${f} && ${d} <= ${a}`),e.pass(f);return}s.items=!0;let u=t.name("valid");a===void 0&&o===1?m(u,()=>t.if(u,()=>t.break())):o===0?(t.let(u,!0),a!==void 0&&t.if((0,Ne._)`${i}.length > 0`,h)):(t.let(u,!1),h()),e.result(u,()=>e.reset());function h(){let f=t.name("_valid"),g=t.let("count",0);m(f,()=>t.if(f,()=>p(g)))}function m(f,g){t.forRange("i",0,d,y=>{e.subschema({keyword:"contains",dataProp:y,dataPropType:_o.Type.Num,compositeRule:!0},f),g()})}function p(f){t.code((0,Ne._)`${f}++`),a===void 0?t.if((0,Ne._)`${f} >= ${o}`,()=>t.assign(u,!0).break()):(t.if((0,Ne._)`${f} > ${a}`,()=>t.assign(u,!1).break()),o===1?t.assign(u,!0):t.if((0,Ne._)`${f} >= ${o}`,()=>t.assign(u,!0)))}}};Fu.default=wA});var ko=v(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.validateSchemaDeps=ot.validatePropertyDeps=ot.error=void 0;var Vu=T(),bA=N(),Si=xe();ot.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Vu.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Vu._)`{property: ${e},
146
+ missingProperty: ${n},
147
+ depsCount: ${t},
148
+ deps: ${r}}`};var SA={keyword:"dependencies",type:"object",schemaType:"object",error:ot.error,code(e){let[t,r]=_A(e);ev(e,t),tv(e,r)}};function _A({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let i=Array.isArray(e[n])?t:r;i[n]=e[n]}return[t,r]}function ev(e,t=e.schema){let{gen:r,data:n,it:i}=e;if(Object.keys(t).length===0)return;let s=r.let("missing");for(let o in t){let a=t[o];if(a.length===0)continue;let c=(0,Si.propertyInData)(r,n,o,i.opts.ownProperties);e.setParams({property:o,depsCount:a.length,deps:a.join(", ")}),i.allErrors?r.if(c,()=>{for(let l of a)(0,Si.checkReportMissingProp)(e,l)}):(r.if((0,Vu._)`${c} && (${(0,Si.checkMissingProp)(e,a,s)})`),(0,Si.reportMissingProp)(e,s),r.else())}}ot.validatePropertyDeps=ev;function tv(e,t=e.schema){let{gen:r,data:n,keyword:i,it:s}=e,o=r.name("valid");for(let a in t)(0,bA.alwaysValidSchema)(s,t[a])||(r.if((0,Si.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=e.subschema({keyword:i,schemaProp:a},o);e.mergeValidEvaluated(c,o)},()=>r.var(o,!0)),e.ok(o))}ot.validateSchemaDeps=tv;ot.default=SA});var nv=v(Bu=>{"use strict";Object.defineProperty(Bu,"__esModule",{value:!0});var rv=T(),kA=N(),$A={message:"property name must be valid",params:({params:e})=>(0,rv._)`{propertyName: ${e.propertyName}}`},EA={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:$A,code(e){let{gen:t,schema:r,data:n,it:i}=e;if((0,kA.alwaysValidSchema)(i,r))return;let s=t.name("valid");t.forIn("key",n,o=>{e.setParams({propertyName:o}),e.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},s),t.if((0,rv.not)(s),()=>{e.error(!0),i.allErrors||t.break()})}),e.ok(s)}};Bu.default=EA});var Uu=v(Ku=>{"use strict";Object.defineProperty(Ku,"__esModule",{value:!0});var $o=xe(),Je=T(),IA=Oe(),Eo=N(),PA={message:"must NOT have additional properties",params:({params:e})=>(0,Je._)`{additionalProperty: ${e.additionalProperty}}`},RA={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:PA,code(e){let{gen:t,schema:r,parentSchema:n,data:i,errsCount:s,it:o}=e;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,Eo.alwaysValidSchema)(o,r))return;let l=(0,$o.allSchemaProperties)(n.properties),d=(0,$o.allSchemaProperties)(n.patternProperties);u(),e.ok((0,Je._)`${s} === ${IA.default.errors}`);function u(){t.forIn("key",i,g=>{!l.length&&!d.length?p(g):t.if(h(g),()=>p(g))})}function h(g){let y;if(l.length>8){let w=(0,Eo.schemaRefOrVal)(o,n.properties,"properties");y=(0,$o.isOwnProperty)(t,w,g)}else l.length?y=(0,Je.or)(...l.map(w=>(0,Je._)`${g} === ${w}`)):y=Je.nil;return d.length&&(y=(0,Je.or)(y,...d.map(w=>(0,Je._)`${(0,$o.usePattern)(e,w)}.test(${g})`))),(0,Je.not)(y)}function m(g){t.code((0,Je._)`delete ${i}[${g}]`)}function p(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){m(g);return}if(r===!1){e.setParams({additionalProperty:g}),e.error(),a||t.break();return}if(typeof r=="object"&&!(0,Eo.alwaysValidSchema)(o,r)){let y=t.name("valid");c.removeAdditional==="failing"?(f(g,y,!1),t.if((0,Je.not)(y),()=>{e.reset(),m(g)})):(f(g,y),a||t.if((0,Je.not)(y),()=>t.break()))}}function f(g,y,w){let b={keyword:"additionalProperties",dataProp:g,dataPropType:Eo.Type.Str};w===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(b,y)}}};Ku.default=RA});var ov=v(Hu=>{"use strict";Object.defineProperty(Hu,"__esModule",{value:!0});var AA=oi(),iv=xe(),Gu=N(),sv=Uu(),CA={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:s}=e;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&sv.default.code(new AA.KeywordCxt(s,sv.default,"additionalProperties"));let o=(0,iv.allSchemaProperties)(r);for(let u of o)s.definedProperties.add(u);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=Gu.mergeEvaluated.props(t,(0,Gu.toHash)(o),s.props));let a=o.filter(u=>!(0,Gu.alwaysValidSchema)(s,r[u]));if(a.length===0)return;let c=t.name("valid");for(let u of a)l(u)?d(u):(t.if((0,iv.propertyInData)(t,i,u,s.opts.ownProperties)),d(u),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(u),e.ok(c);function l(u){return s.opts.useDefaults&&!s.compositeRule&&r[u].default!==void 0}function d(u){e.subschema({keyword:"properties",schemaProp:u,dataProp:u},c)}}};Hu.default=CA});var uv=v(zu=>{"use strict";Object.defineProperty(zu,"__esModule",{value:!0});var av=xe(),Io=T(),cv=N(),lv=N(),TA={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:i,it:s}=e,{opts:o}=s,a=(0,av.allSchemaProperties)(r),c=a.filter(f=>(0,cv.alwaysValidSchema)(s,r[f]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=o.strictSchema&&!o.allowMatchingProperties&&i.properties,d=t.name("valid");s.props!==!0&&!(s.props instanceof Io.Name)&&(s.props=(0,lv.evaluatedPropsToName)(t,s.props));let{props:u}=s;h();function h(){for(let f of a)l&&m(f),s.allErrors?p(f):(t.var(d,!0),p(f),t.if(d))}function m(f){for(let g in l)new RegExp(f).test(g)&&(0,cv.checkStrictMode)(s,`property ${g} matches pattern ${f} (use allowMatchingProperties)`)}function p(f){t.forIn("key",n,g=>{t.if((0,Io._)`${(0,av.usePattern)(e,f)}.test(${g})`,()=>{let y=c.includes(f);y||e.subschema({keyword:"patternProperties",schemaProp:f,dataProp:g,dataPropType:lv.Type.Str},d),s.opts.unevaluated&&u!==!0?t.assign((0,Io._)`${u}[${g}]`,!0):!y&&!s.allErrors&&t.if((0,Io.not)(d),()=>t.break())})})}}};zu.default=TA});var dv=v(Wu=>{"use strict";Object.defineProperty(Wu,"__esModule",{value:!0});var DA=N(),OA={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,DA.alwaysValidSchema)(n,r)){e.fail();return}let i=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),e.failResult(i,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Wu.default=OA});var fv=v(Qu=>{"use strict";Object.defineProperty(Qu,"__esModule",{value:!0});var xA=xe(),jA={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:xA.validateUnion,error:{message:"must match a schema in anyOf"}};Qu.default=jA});var pv=v(Ju=>{"use strict";Object.defineProperty(Ju,"__esModule",{value:!0});var Po=T(),NA=N(),qA={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Po._)`{passingSchemas: ${e.passing}}`},MA={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:qA,code(e){let{gen:t,schema:r,parentSchema:n,it:i}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let s=r,o=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(l),e.result(o,()=>e.reset(),()=>e.error(!0));function l(){s.forEach((d,u)=>{let h;(0,NA.alwaysValidSchema)(i,d)?t.var(c,!0):h=e.subschema({keyword:"oneOf",schemaProp:u,compositeRule:!0},c),u>0&&t.if((0,Po._)`${c} && ${o}`).assign(o,!1).assign(a,(0,Po._)`[${a}, ${u}]`).else(),t.if(c,()=>{t.assign(o,!0),t.assign(a,u),h&&e.mergeEvaluated(h,Po.Name)})})}}};Ju.default=MA});var hv=v(Yu=>{"use strict";Object.defineProperty(Yu,"__esModule",{value:!0});var LA=N(),FA={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");let i=t.name("valid");r.forEach((s,o)=>{if((0,LA.alwaysValidSchema)(n,s))return;let a=e.subschema({keyword:"allOf",schemaProp:o},i);e.ok(i),e.mergeEvaluated(a)})}};Yu.default=FA});var yv=v(Xu=>{"use strict";Object.defineProperty(Xu,"__esModule",{value:!0});var Ro=T(),gv=N(),VA={message:({params:e})=>(0,Ro.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Ro._)`{failingKeyword: ${e.ifClause}}`},BA={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:VA,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,gv.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=mv(n,"then"),s=mv(n,"else");if(!i&&!s)return;let o=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),i&&s){let d=t.let("ifClause");e.setParams({ifClause:d}),t.if(a,l("then",d),l("else",d))}else i?t.if(a,l("then")):t.if((0,Ro.not)(a),l("else"));e.pass(o,()=>e.error(!0));function c(){let d=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(d)}function l(d,u){return()=>{let h=e.subschema({keyword:d},a);t.assign(o,a),e.mergeValidEvaluated(h,o),u?t.assign(u,(0,Ro._)`${d}`):e.setParams({ifClause:d})}}}};function mv(e,t){let r=e.schema[t];return r!==void 0&&!(0,gv.alwaysValidSchema)(e,r)}Xu.default=BA});var vv=v(Zu=>{"use strict";Object.defineProperty(Zu,"__esModule",{value:!0});var KA=N(),UA={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,KA.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Zu.default=UA});var wv=v(ed=>{"use strict";Object.defineProperty(ed,"__esModule",{value:!0});var GA=Nu(),HA=Jy(),zA=qu(),WA=Xy(),QA=Zy(),JA=ko(),YA=nv(),XA=Uu(),ZA=ov(),eC=uv(),tC=dv(),rC=fv(),nC=pv(),iC=hv(),sC=yv(),oC=vv();function aC(e=!1){let t=[tC.default,rC.default,nC.default,iC.default,sC.default,oC.default,YA.default,XA.default,JA.default,ZA.default,eC.default];return e?t.push(HA.default,WA.default):t.push(GA.default,zA.default),t.push(QA.default),t}ed.default=aC});var rd=v(_i=>{"use strict";Object.defineProperty(_i,"__esModule",{value:!0});_i.dynamicAnchor=void 0;var td=T(),cC=Oe(),bv=ci(),lC=yo(),uC={keyword:"$dynamicAnchor",schemaType:"string",code:e=>Sv(e,e.schema)};function Sv(e,t){let{gen:r,it:n}=e;n.schemaEnv.root.dynamicAnchors[t]=!0;let i=(0,td._)`${cC.default.dynamicAnchors}${(0,td.getProperty)(t)}`,s=n.errSchemaPath==="#"?n.validateName:dC(e);r.if((0,td._)`!${i}`,()=>r.assign(i,s))}_i.dynamicAnchor=Sv;function dC(e){let{schemaEnv:t,schema:r,self:n}=e.it,{root:i,baseId:s,localRefs:o,meta:a}=t.root,{schemaId:c}=n.opts,l=new bv.SchemaEnv({schema:r,schemaId:c,root:i,baseId:s,localRefs:o,meta:a});return bv.compileSchema.call(n,l),(0,lC.getValidate)(e,l)}_i.default=uC});var nd=v(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});ki.dynamicRef=void 0;var _v=T(),fC=Oe(),kv=yo(),pC={keyword:"$dynamicRef",schemaType:"string",code:e=>$v(e,e.schema)};function $v(e,t){let{gen:r,keyword:n,it:i}=e;if(t[0]!=="#")throw new Error(`"${n}" only supports hash fragment reference`);let s=t.slice(1);if(i.allErrors)o();else{let c=r.let("valid",!1);o(c),e.ok(c)}function o(c){if(i.schemaEnv.root.dynamicAnchors[s]){let l=r.let("_v",(0,_v._)`${fC.default.dynamicAnchors}${(0,_v.getProperty)(s)}`);r.if(l,a(l,c),a(i.validateName,c))}else a(i.validateName,c)()}function a(c,l){return l?()=>r.block(()=>{(0,kv.callRef)(e,c),r.let(l,!0)}):()=>(0,kv.callRef)(e,c)}}ki.dynamicRef=$v;ki.default=pC});var Ev=v(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});var hC=rd(),mC=N(),gC={keyword:"$recursiveAnchor",schemaType:"boolean",code(e){e.schema?(0,hC.dynamicAnchor)(e,""):(0,mC.checkStrictMode)(e.it,"$recursiveAnchor: false is ignored")}};id.default=gC});var Iv=v(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});var yC=nd(),vC={keyword:"$recursiveRef",schemaType:"string",code:e=>(0,yC.dynamicRef)(e,e.schema)};sd.default=vC});var Pv=v(od=>{"use strict";Object.defineProperty(od,"__esModule",{value:!0});var wC=rd(),bC=nd(),SC=Ev(),_C=Iv(),kC=[wC.default,bC.default,SC.default,_C.default];od.default=kC});var Av=v(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});var Rv=ko(),$C={keyword:"dependentRequired",type:"object",schemaType:"object",error:Rv.error,code:e=>(0,Rv.validatePropertyDeps)(e)};ad.default=$C});var Cv=v(cd=>{"use strict";Object.defineProperty(cd,"__esModule",{value:!0});var EC=ko(),IC={keyword:"dependentSchemas",type:"object",schemaType:"object",code:e=>(0,EC.validateSchemaDeps)(e)};cd.default=IC});var Tv=v(ld=>{"use strict";Object.defineProperty(ld,"__esModule",{value:!0});var PC=N(),RC={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:e,parentSchema:t,it:r}){t.contains===void 0&&(0,PC.checkStrictMode)(r,`"${e}" without "contains" is ignored`)}};ld.default=RC});var Dv=v(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var AC=Av(),CC=Cv(),TC=Tv(),DC=[AC.default,CC.default,TC.default];ud.default=DC});var xv=v(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var Kt=T(),Ov=N(),OC=Oe(),xC={message:"must NOT have unevaluated properties",params:({params:e})=>(0,Kt._)`{unevaluatedProperty: ${e.unevaluatedProperty}}`},jC={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:xC,code(e){let{gen:t,schema:r,data:n,errsCount:i,it:s}=e;if(!i)throw new Error("ajv implementation error");let{allErrors:o,props:a}=s;a instanceof Kt.Name?t.if((0,Kt._)`${a} !== true`,()=>t.forIn("key",n,u=>t.if(l(a,u),()=>c(u)))):a!==!0&&t.forIn("key",n,u=>a===void 0?c(u):t.if(d(a,u),()=>c(u))),s.props=!0,e.ok((0,Kt._)`${i} === ${OC.default.errors}`);function c(u){if(r===!1){e.setParams({unevaluatedProperty:u}),e.error(),o||t.break();return}if(!(0,Ov.alwaysValidSchema)(s,r)){let h=t.name("valid");e.subschema({keyword:"unevaluatedProperties",dataProp:u,dataPropType:Ov.Type.Str},h),o||t.if((0,Kt.not)(h),()=>t.break())}}function l(u,h){return(0,Kt._)`!${u} || !${u}[${h}]`}function d(u,h){let m=[];for(let p in u)u[p]===!0&&m.push((0,Kt._)`${h} !== ${p}`);return(0,Kt.and)(...m)}}};dd.default=jC});var Nv=v(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var yr=T(),jv=N(),NC={message:({params:{len:e}})=>(0,yr.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,yr._)`{limit: ${e}}`},qC={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:NC,code(e){let{gen:t,schema:r,data:n,it:i}=e,s=i.items||0;if(s===!0)return;let o=t.const("len",(0,yr._)`${n}.length`);if(r===!1)e.setParams({len:s}),e.fail((0,yr._)`${o} > ${s}`);else if(typeof r=="object"&&!(0,jv.alwaysValidSchema)(i,r)){let c=t.var("valid",(0,yr._)`${o} <= ${s}`);t.if((0,yr.not)(c),()=>a(c,s)),e.ok(c)}i.items=!0;function a(c,l){t.forRange("i",l,o,d=>{e.subschema({keyword:"unevaluatedItems",dataProp:d,dataPropType:jv.Type.Num},c),i.allErrors||t.if((0,yr.not)(c),()=>t.break())})}}};fd.default=qC});var qv=v(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});var MC=xv(),LC=Nv(),FC=[MC.default,LC.default];pd.default=FC});var Mv=v(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var ne=T(),VC={message:({schemaCode:e})=>(0,ne.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,ne._)`{format: ${e}}`},BC={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:VC,code(e,t){let{gen:r,data:n,$data:i,schema:s,schemaCode:o,it:a}=e,{opts:c,errSchemaPath:l,schemaEnv:d,self:u}=a;if(!c.validateFormats)return;i?h():m();function h(){let p=r.scopeValue("formats",{ref:u.formats,code:c.code.formats}),f=r.const("fDef",(0,ne._)`${p}[${o}]`),g=r.let("fType"),y=r.let("format");r.if((0,ne._)`typeof ${f} == "object" && !(${f} instanceof RegExp)`,()=>r.assign(g,(0,ne._)`${f}.type || "string"`).assign(y,(0,ne._)`${f}.validate`),()=>r.assign(g,(0,ne._)`"string"`).assign(y,f)),e.fail$data((0,ne.or)(w(),b()));function w(){return c.strictSchema===!1?ne.nil:(0,ne._)`${o} && !${y}`}function b(){let $=d.$async?(0,ne._)`(${f}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,ne._)`${y}(${n})`,S=(0,ne._)`(typeof ${y} == "function" ? ${$} : ${y}.test(${n}))`;return(0,ne._)`${y} && ${y} !== true && ${g} === ${t} && !${S}`}}function m(){let p=u.formats[s];if(!p){w();return}if(p===!0)return;let[f,g,y]=b(p);f===t&&e.pass($());function w(){if(c.strictSchema===!1){u.logger.warn(S());return}throw new Error(S());function S(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function b(S){let I=S instanceof RegExp?(0,ne.regexpCode)(S):c.code.formats?(0,ne._)`${c.code.formats}${(0,ne.getProperty)(s)}`:void 0,k=r.scopeValue("formats",{key:s,ref:S,code:I});return typeof S=="object"&&!(S instanceof RegExp)?[S.type||"string",S.validate,(0,ne._)`${k}.validate`]:["string",S,k]}function $(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!d.$async)throw new Error("async format in sync schema");return(0,ne._)`await ${y}(${n})`}return typeof g=="function"?(0,ne._)`${y}(${n})`:(0,ne._)`${y}.test(${n})`}}}};hd.default=BC});var Lv=v(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});var KC=Mv(),UC=[KC.default];md.default=UC});var Fv=v(Xr=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});Xr.contentVocabulary=Xr.metadataVocabulary=void 0;Xr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Xr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Bv=v(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});var GC=Dy(),HC=Hy(),zC=wv(),WC=Pv(),QC=Dv(),JC=qv(),YC=Lv(),Vv=Fv(),XC=[WC.default,GC.default,HC.default,(0,zC.default)(!0),YC.default,Vv.metadataVocabulary,Vv.contentVocabulary,QC.default,JC.default];gd.default=XC});var Uv=v(Ao=>{"use strict";Object.defineProperty(Ao,"__esModule",{value:!0});Ao.DiscrError=void 0;var Kv;(function(e){e.Tag="tag",e.Mapping="mapping"})(Kv||(Ao.DiscrError=Kv={}))});var Hv=v(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var Zr=T(),yd=Uv(),Gv=ci(),ZC=ai(),eT=N(),tT={message:({params:{discrError:e,tagName:t}})=>e===yd.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,Zr._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},rT={keyword:"discriminator",type:"object",schemaType:"object",error:tT,code(e){let{gen:t,data:r,schema:n,parentSchema:i,it:s}=e,{oneOf:o}=i;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),l=t.const("tag",(0,Zr._)`${r}${(0,Zr.getProperty)(a)}`);t.if((0,Zr._)`typeof ${l} == "string"`,()=>d(),()=>e.error(!1,{discrError:yd.DiscrError.Tag,tag:l,tagName:a})),e.ok(c);function d(){let m=h();t.if(!1);for(let p in m)t.elseIf((0,Zr._)`${l} === ${p}`),t.assign(c,u(m[p]));t.else(),e.error(!1,{discrError:yd.DiscrError.Mapping,tag:l,tagName:a}),t.endIf()}function u(m){let p=t.name("valid"),f=e.subschema({keyword:"oneOf",schemaProp:m},p);return e.mergeEvaluated(f,Zr.Name),p}function h(){var m;let p={},f=y(i),g=!0;for(let $=0;$<o.length;$++){let S=o[$];if(S?.$ref&&!(0,eT.schemaHasRulesButRef)(S,s.self.RULES)){let k=S.$ref;if(S=Gv.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,k),S instanceof Gv.SchemaEnv&&(S=S.schema),S===void 0)throw new ZC.default(s.opts.uriResolver,s.baseId,k)}let I=(m=S?.properties)===null||m===void 0?void 0:m[a];if(typeof I!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(f||y(S)),w(I,$)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return p;function y({required:$}){return Array.isArray($)&&$.includes(a)}function w($,S){if($.const)b($.const,S);else if($.enum)for(let I of $.enum)b(I,S);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b($,S){if(typeof $!="string"||$ in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[$]=S}}}};vd.default=rT});var zv=v((Uq,nT)=>{nT.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var Wv=v((Gq,iT)=>{iT.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var Qv=v((Hq,sT)=>{sT.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var Jv=v((zq,oT)=>{oT.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var Yv=v((Wq,aT)=>{aT.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var Xv=v((Qq,cT)=>{cT.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var Zv=v((Jq,lT)=>{lT.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var ew=v((Yq,uT)=>{uT.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var tw=v(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var dT=zv(),fT=Wv(),pT=Qv(),hT=Jv(),mT=Yv(),gT=Xv(),yT=Zv(),vT=ew(),wT=["/properties"];function bT(e){return[dT,fT,pT,hT,mT,t(this,gT),yT,t(this,vT)].forEach(r=>this.addMetaSchema(r,void 0,!1)),this;function t(r,n){return e?r.$dataMetaSchema(n,wT):n}}wd.default=bT});var _d=v((X,Sd)=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.MissingRefError=X.ValidationError=X.CodeGen=X.Name=X.nil=X.stringify=X.str=X._=X.KeywordCxt=X.Ajv2020=void 0;var ST=Py(),_T=Bv(),kT=Hv(),$T=tw(),bd="https://json-schema.org/draft/2020-12/schema",en=class extends ST.default{constructor(t={}){super({...t,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),_T.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(kT.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:t,meta:r}=this.opts;r&&($T.default.call(this,t),this.refs["http://json-schema.org/schema"]=bd)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(bd)?bd:void 0)}};X.Ajv2020=en;Sd.exports=X=en;Sd.exports.Ajv2020=en;Object.defineProperty(X,"__esModule",{value:!0});X.default=en;var ET=oi();Object.defineProperty(X,"KeywordCxt",{enumerable:!0,get:function(){return ET.KeywordCxt}});var tn=T();Object.defineProperty(X,"_",{enumerable:!0,get:function(){return tn._}});Object.defineProperty(X,"str",{enumerable:!0,get:function(){return tn.str}});Object.defineProperty(X,"stringify",{enumerable:!0,get:function(){return tn.stringify}});Object.defineProperty(X,"nil",{enumerable:!0,get:function(){return tn.nil}});Object.defineProperty(X,"Name",{enumerable:!0,get:function(){return tn.Name}});Object.defineProperty(X,"CodeGen",{enumerable:!0,get:function(){return tn.CodeGen}});var IT=co();Object.defineProperty(X,"ValidationError",{enumerable:!0,get:function(){return IT.default}});var PT=ai();Object.defineProperty(X,"MissingRefError",{enumerable:!0,get:function(){return PT.default}})});var Cd=v((cM,Ad)=>{var Do=process||{},uw=Do.argv||[],To=Do.env||{},CT=!(To.NO_COLOR||uw.includes("--no-color"))&&(!!To.FORCE_COLOR||uw.includes("--color")||Do.platform==="win32"||(Do.stdout||{}).isTTY&&To.TERM!=="dumb"||!!To.CI),TT=(e,t,r=e)=>n=>{let i=""+n,s=i.indexOf(t,e.length);return~s?e+DT(i,t,r,s)+t:e+i+t},DT=(e,t,r,n)=>{let i="",s=0;do i+=e.substring(s,n)+r,s=n+t.length,n=e.indexOf(t,s);while(~n);return i+e.substring(s)},dw=(e=CT)=>{let t=e?TT:()=>String;return{isColorSupported:e,reset:t("\x1B[0m","\x1B[0m"),bold:t("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:t("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:t("\x1B[3m","\x1B[23m"),underline:t("\x1B[4m","\x1B[24m"),inverse:t("\x1B[7m","\x1B[27m"),hidden:t("\x1B[8m","\x1B[28m"),strikethrough:t("\x1B[9m","\x1B[29m"),black:t("\x1B[30m","\x1B[39m"),red:t("\x1B[31m","\x1B[39m"),green:t("\x1B[32m","\x1B[39m"),yellow:t("\x1B[33m","\x1B[39m"),blue:t("\x1B[34m","\x1B[39m"),magenta:t("\x1B[35m","\x1B[39m"),cyan:t("\x1B[36m","\x1B[39m"),white:t("\x1B[37m","\x1B[39m"),gray:t("\x1B[90m","\x1B[39m"),bgBlack:t("\x1B[40m","\x1B[49m"),bgRed:t("\x1B[41m","\x1B[49m"),bgGreen:t("\x1B[42m","\x1B[49m"),bgYellow:t("\x1B[43m","\x1B[49m"),bgBlue:t("\x1B[44m","\x1B[49m"),bgMagenta:t("\x1B[45m","\x1B[49m"),bgCyan:t("\x1B[46m","\x1B[49m"),bgWhite:t("\x1B[47m","\x1B[49m"),blackBright:t("\x1B[90m","\x1B[39m"),redBright:t("\x1B[91m","\x1B[39m"),greenBright:t("\x1B[92m","\x1B[39m"),yellowBright:t("\x1B[93m","\x1B[39m"),blueBright:t("\x1B[94m","\x1B[39m"),magentaBright:t("\x1B[95m","\x1B[39m"),cyanBright:t("\x1B[96m","\x1B[39m"),whiteBright:t("\x1B[97m","\x1B[39m"),bgBlackBright:t("\x1B[100m","\x1B[49m"),bgRedBright:t("\x1B[101m","\x1B[49m"),bgGreenBright:t("\x1B[102m","\x1B[49m"),bgYellowBright:t("\x1B[103m","\x1B[49m"),bgBlueBright:t("\x1B[104m","\x1B[49m"),bgMagentaBright:t("\x1B[105m","\x1B[49m"),bgCyanBright:t("\x1B[106m","\x1B[49m"),bgWhiteBright:t("\x1B[107m","\x1B[49m")}};Ad.exports=dw();Ad.exports.createColors=dw});var Dd=v((lM,fw)=>{"use strict";var Td={to(e,t){return t?`\x1B[${t+1};${e+1}H`:`\x1B[${e+1}G`},move(e,t){let r="";return e<0?r+=`\x1B[${-e}D`:e>0&&(r+=`\x1B[${e}C`),t<0?r+=`\x1B[${-t}A`:t>0&&(r+=`\x1B[${t}B`),r},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},OT={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},xT={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let t="";for(let r=0;r<e;r++)t+=this.line+(r<e-1?Td.up():"");return e&&(t+=Td.left),t}};fw.exports={cursor:Td,scroll:OT,erase:xT,beep:"\x07"}});var kS=Ve(Mr(),1);import{resolve as C2}from"node:path";import{spawn as m1}from"node:child_process";import{createInterface as g1}from"node:readline";var Kn=["gpt-5.6-luna","gpt-5.6-terra","gpt-5.6-sol"],nr=["low","medium","high","xhigh"];var o1=Kn,a1="v2",ir="2026-08-13.taskstate-v6.v1",Un={"gpt-5.6-luna":1,"gpt-5.6-terra":2.5,"gpt-5.6-sol":5},sl={"gpt-5.6-luna":{multiplier:1,rateVersion:"2026-07-09",inputCreditsPerMillion:25,cachedInputCreditsPerMillion:2.5,outputCreditsPerMillion:150},"gpt-5.6-terra":{multiplier:2.5,rateVersion:"2026-07-09",inputCreditsPerMillion:62.5,cachedInputCreditsPerMillion:6.25,outputCreditsPerMillion:375},"gpt-5.6-sol":{multiplier:5,rateVersion:"2026-07-09",inputCreditsPerMillion:125,cachedInputCreditsPerMillion:12.5,outputCreditsPerMillion:750}},il=[...nr],c1={plus:{design:{model:"gpt-5.6-terra",effort:"medium"},discover:{model:"gpt-5.6-terra",effort:"medium"},plan:{model:"gpt-5.6-sol",effort:"medium"},review:{model:"gpt-5.6-luna",effort:"medium"},debug:{model:"gpt-5.6-sol",effort:"high"}},pro_5x:{design:{model:"gpt-5.6-sol",effort:"high"},discover:{model:"gpt-5.6-terra",effort:"high"},plan:{model:"gpt-5.6-sol",effort:"high"},review:{model:"gpt-5.6-luna",effort:"medium"},debug:{model:"gpt-5.6-sol",effort:"xhigh"}},pro_20x:{design:{model:"gpt-5.6-sol",effort:"xhigh"},discover:{model:"gpt-5.6-sol",effort:"medium"},plan:{model:"gpt-5.6-sol",effort:"xhigh"},review:{model:"gpt-5.6-luna",effort:"medium"},debug:{model:"gpt-5.6-sol",effort:"xhigh"}}};function xm(e,t={}){if(e===void 0||!Number.isFinite(e))return"unknown";let r=t.warningPercent??50,n=t.criticalPercent??80;return e>=n?"critical":e>=r?"warning":"normal"}function jm(e){return al(e).find(t=>t.windowDurationMins===300)}function Nm(e){return al(e).filter(t=>t.windowDurationMins!==300).toSorted((t,r)=>t.windowDurationMins-r.windowDurationMins)[0]}function qm(e,t){return e==="plus"||e==="pro_5x"||e==="pro_20x"?e:t==="plus"?"plus":t==="pro_5x"||t==="pro_20x"?t:t==="pro"?"pro_5x":"unknown"}function Mm(e,t){return t!==void 0&&Number.isFinite(t)&&t>0?t:e==="pro_20x"?20:e==="pro_5x"?5:1}function Us(e,t=!0){let r=p1(e.account),n=typeof r.planType=="string"?r.planType:void 0,i=e.config?.planOverride??e.config?.plan,s=qm(i,n),o=jm(e.rateLimits),a=o?void 0:Nm(e.rateLimits),c=xm(o?.usedPercent,e.config?.quota),l=f1(e.models,e.config?.modelAllowlist),d=[];c==="unknown"&&d.push("quota_unknown"),t&&!o&&d.push("five_hour_window_unavailable"),l.length===0&&d.push("allowed_model_unavailable"),!t&&!d.includes("quota_unknown")&&d.push("quota_unknown");let u={schemaVersion:1,capturedAt:e.capturedAt??new Date().toISOString(),plan:s,account:r,quota:{...o?{windowDurationMins:o.windowDurationMins,usedPercent:o.usedPercent,...o.resetsAt!==void 0?{resetsAt:o.resetsAt}:{}}:{},pressure:c,source:t&&o?"app-server":"unknown",...a?{observedWindow:a}:{}},models:l,warnings:d,provenance:{plan:i&&i!=="auto"?"config":n?"account/read":"unknown",quota:t&&o?"account/rateLimits/read":"unknown",models:t&&l.length?"model/list":"unknown"},subscriptionMultiplier:Mm(s,e.config?.multiplierOverride)};return{available:t,snapshot:u}}function ol(e=new Date().toISOString()){return Us({capturedAt:e,config:{plan:"auto"}},!1)}function Gn(e,t){let r=[...e.warnings],n=e.quota.pressure,i=e.plan==="unknown";n==="unknown"&&!r.includes("quota_unknown")&&r.push("quota_unknown"),i&&!r.includes("plan_unknown")&&r.push("plan_unknown");let s=u1(e.plan,n),o=t.stage==="review"?l1(t.risk,t.ambiguity):c1[s][t.stage],c=(t.risk==="high"||t.risk==="critical"||t.ambiguity==="high"||t.ambiguity==="critical")&&t.stage!=="review"?1:0,l=d1(o.effort,c),u=e.models.find(m=>m.id===o.model)?.supportedReasoningEfforts.includes(l)===!0,h=t.stage==="review"?`least-cost qualified review route for ${Lm(t.risk,t.ambiguity)} risk`:`${t.stage} route for ${s} plan under ${n} quota`;return u?{stage:t.stage,model:o.model,effort:l,quotaPressure:n,reason:h,warnings:r}:(r.includes("required_route_unavailable")||r.push("required_route_unavailable"),{stage:t.stage,model:null,effort:null,quotaPressure:n,reason:`${h}; exact ${o.model}/${l} unavailable`,warnings:r})}function l1(e,t){let r=Lm(e,t);return r==="critical"?{model:"gpt-5.6-sol",effort:"high"}:r==="high"?{model:"gpt-5.6-terra",effort:"high"}:{model:"gpt-5.6-luna",effort:"medium"}}function Lm(e,t){let r=["low","medium","high","critical"];return r[Math.max(r.indexOf(e),r.indexOf(t))]??"critical"}function u1(e,t){let r=e==="unknown"?"plus":e;return t==="critical"||t==="unknown"?"plus":t!=="warning"?r:r==="pro_20x"?"pro_5x":"plus"}function d1(e,t){let r=il.indexOf(e);return il[Math.max(0,Math.min(il.length-1,r+t))]??e}function f1(e,t){let r=Array.isArray(e)?e:Ot(e)&&Array.isArray(e.models)?e.models:Ot(e)&&Array.isArray(e.data)?e.data:[],n=[];for(let i of r){if(!Ot(i)||typeof i.id!="string"||!h1(i.id)||t&&!t.includes(i.id))continue;let s=Array.isArray(i.supportedReasoningEfforts)?i.supportedReasoningEfforts.flatMap(o=>{let a=typeof o=="string"?o:Ot(o)&&typeof o.reasoningEffort=="string"?o.reasoningEffort:void 0;return a&&nr.includes(a)?[a]:[]}):[];n.push({id:i.id,supportedReasoningEfforts:s})}return n}function p1(e){if(!Ot(e))return{};let t=Ot(e.account)?e.account:e;return typeof t.planType=="string"?{planType:t.planType}:{}}function h1(e){return Kn.includes(e)}function Ot(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function al(e,t=[],r=new Set){if(!Ot(e)||r.has(e))return t;r.add(e),typeof e.windowDurationMins=="number"&&Number.isFinite(e.windowDurationMins)&&e.windowDurationMins>0&&typeof e.usedPercent=="number"&&Number.isFinite(e.usedPercent)&&t.push({windowDurationMins:e.windowDurationMins,usedPercent:e.usedPercent,...typeof e.resetsAt=="number"&&Number.isFinite(e.resetsAt)?{resetsAt:e.resetsAt}:{}});for(let n of Object.values(e))Ot(n)&&al(n,t,r);return t}var Ue=class extends Error{constructor(r,n="unknown",i=""){super(r);this.kind=n;this.stderr=i}kind;stderr},Gs=class{process;pending=new Map;nextId=1;closed=!1;stderr="";constructor(t={}){let r=t.args??["app-server"],n=t.cwd?{cwd:t.cwd,stdio:["pipe","pipe","pipe"]}:{stdio:["pipe","pipe","pipe"]};this.process=m1(t.command??"codex",r,n),g1({input:this.process.stdout}).on("line",s=>this.receive(s)),this.process.stderr.on("data",s=>{this.stderr.length>=Fm||(this.stderr=(this.stderr+String(s)).slice(0,Fm))}),this.process.on("error",s=>this.fail(new Ue(s.message,"spawn",this.stderr))),this.process.on("close",()=>{let s=Vm(this.stderr)?"permission":"closed";this.fail(new Ue("app-server closed before completing request",s,this.stderr))})}async readSnapshot(t){await this.request("initialize",{clientInfo:{name:"dev-flow",title:"Dev Flow",version:"0.1.0"}}),this.notify("initialized",{});let r=await this.request("account/read",{refreshToken:!1}),n=await this.request("account/rateLimits/read",{}),i=await this.request("model/list",{includeHidden:!1});return Us({account:r,rateLimits:n,models:i,...t?{config:t}:{}})}close(){this.closed||(this.closed=!0,this.process.kill())}notify(t,r){if(this.closed)throw new Ue("app-server is closed");this.process.stdin.write(JSON.stringify({method:t,params:r})+`
149
+ `)}request(t,r){if(this.closed)return Promise.reject(new Ue("app-server is closed"));let n=this.nextId++;return new Promise((i,s)=>{this.pending.set(n,{resolve:i,reject:s});try{this.process.stdin.write(JSON.stringify({id:n,method:t,params:r})+`
150
+ `)}catch(o){this.pending.delete(n),s(o instanceof Error?o:new Ue("failed to write to app-server"))}})}receive(t){let r;try{r=JSON.parse(t)}catch{return}if(typeof r.id!="number")return;let n=this.pending.get(r.id);if(n){if(this.pending.delete(r.id),r.error){n.reject(new Ue(r.error.message??"app-server request failed","rpc"));return}n.resolve(r.result)}}fail(t){if(!this.closed){for(let r of this.pending.values())r.reject(t);this.pending.clear()}}};async function cl(e={}){let t=new Gs(e),r=e.timeoutMs??1500;try{return await y1(t.readSnapshot(e.config),r)}catch(n){let i=v1(n);return{...ol(),error:i.code==="app_server_timeout"?"app-server timeout":"app-server unavailable",failure:i}}finally{t.close()}}function y1(e,t){return new Promise((r,n)=>{let i=setTimeout(()=>n(new Ue("app-server timeout","timeout")),t);e.then(s=>{clearTimeout(i),r(s)},s=>{clearTimeout(i),n(s)})})}var Fm=8192;function v1(e){if(e instanceof Ue){if(e.kind==="timeout")return{code:"app_server_timeout",retryableWithApproval:!1};if(e.kind==="spawn")return{code:"app_server_spawn_failed",retryableWithApproval:!1};if(e.kind==="rpc")return{code:"app_server_rpc_failed",retryableWithApproval:!1};if(e.kind==="permission"||Vm(e.stderr))return{code:"app_server_permission_denied",...w1(e.stderr)?{path:"~/.codex"}:{},retryableWithApproval:!0};if(e.kind==="closed")return{code:"app_server_closed",retryableWithApproval:!1}}return{code:"app_server_unavailable",retryableWithApproval:!1}}function Vm(e){return/operation not permitted|permission denied|\bEACCES\b|\bEPERM\b/i.test(e)}function w1(e){return/(?:^|[\\/])\.codex(?:[\\/]|\b)/i.test(e)}import{randomUUID as D1}from"node:crypto";import{constants as ml,lstatSync as O1,realpathSync as x1}from"node:fs";import*as pe from"node:fs/promises";import{basename as j1,join as Hn,resolve as Qm}from"node:path";import{createHash as b1}from"node:crypto";var S1=/^[A-Za-z0-9][A-Za-z0-9._:/#@+~=-]{0,255}$/,_1=/^[A-Za-z0-9][A-Za-z0-9._:/#@+~=-]{0,511}$/,k1=1024,$1=1024,Km=2048;function zs(){return{schemaVersion:1,evidenceIndex:[],issues:[]}}function ul(e){let t={...structuredClone(e),digest:xt(e)};return sr(t),t}function sr(e){if(!e||e.schemaVersion!==1)throw new Error("AssuranceContract schemaVersion must be 1.");if(Ge(e.sourceDigest,"AssuranceContract source digest"),Ge(e.policyDigest,"AssuranceContract policy digest"),!Array.isArray(e.subjects)||e.subjects.length>k1)throw new Error("AssuranceContract subjects are invalid.");if(!Array.isArray(e.operations)||e.operations.length>$1)throw new Error("AssuranceContract operations are invalid.");let t=R1(e.subjects),r=A1(e.operations,t),n=new Set(r.flatMap(c=>c.covers)),i=[...t].filter(c=>!n.has(c));if(i.length)throw new Error(`AssuranceContract subjects lack operations: ${i.join(", ")}.`);let s=new Set(r.map(c=>c.id));if(!Array.isArray(e.evidencePreference)||new Set(e.evidencePreference).size!==e.evidencePreference.length||e.evidencePreference.some(c=>!s.has(c)))throw new Error("AssuranceContract evidence preference is invalid.");if(e.evidencePreference.length!==s.size)throw new Error("AssuranceContract evidence preference must order every operation.");let o=e.reviewBudget;if(!o||!ll(o.maxInputTokens)||!ll(o.maxOutputTokens)||![0,1,2].includes(o.maxCalls)||!ll(o.maxConcurrency)||o.maxConcurrency>32)throw new Error("AssuranceContract review budget is invalid.");let a=r.filter(c=>c.kind==="model-inspection");if(!a.length&&o.maxCalls!==0)throw new Error("Review budget must allow zero calls when no review operation exists.");if(a.length&&o.maxCalls<1)throw new Error("Review operation requires at least one allowed model call.");if(e.digest!==xt({...e,digest:void 0}))throw new Error("AssuranceContract digest is stale.");return structuredClone(e)}function Um(e,t,r){sr(e);let n=t??zs();if(He(e,n),n.receipt)throw new Error("Completed ASSURE is immutable.");jt(r.evidenceId,"Evidence");let i=Lr(e,r.operationId);if(Ge(r.verifierDigest,"Evidence verifier digest"),Ge(r.observedFingerprint,"Evidence fingerprint"),Ge(r.detailRef,"Evidence detail reference"),r.result==="not_applicable"){if(!i.conditional)throw new Error("Only a conditional operation may be not_applicable.");let m=new Set(e.subjects.filter(p=>p.kind==="criterion").map(p=>p.id));if(i.covers.some(p=>m.has(p)))throw new Error("Acceptance criteria cannot become not_applicable in ASSURE.")}let s={schemaVersion:1,evidenceId:r.evidenceId,operationId:i.id,subjectIds:[...i.covers].toSorted(),verifierKind:i.kind,result:r.result,verifierDigest:r.verifierDigest,observedFingerprint:r.observedFingerprint,detailRef:r.detailRef,recordedAt:hl(r.recordedAt)},o={...s,digest:xt(s)},a=[...n.evidenceIndex.filter(m=>m.evidenceId!==o.evidenceId&&m.operationId!==o.operationId),o].toSorted((m,p)=>m.operationId.localeCompare(p.operationId));if(a.length>Km)throw new Error("Assurance evidence budget exceeded.");let{completionIndex:c,receipt:l,pendingHumanObservation:d,...u}=n,h=d?.operationIds.every(m=>a.some(p=>p.operationId===m));return{...u,schemaVersion:1,evidenceIndex:a,...d&&!h?{pendingHumanObservation:d}:{}}}function Gm(e,t,r){if(He(e,t),t.receipt)throw new Error("Completed ASSURE is immutable.");let n=new Set(r),i=new Map(e.operations.map(o=>[o.id,o]));return{schemaVersion:1,evidenceIndex:t.evidenceIndex.filter(o=>{let a=i.get(o.operationId);return a.fingerprintMode==="scoped"&&!a.scopeRefs.some(c=>n.has(c))}),...t.issues?.length?{issues:[...t.issues]}:{},...t.pendingHumanObservation?{pendingHumanObservation:structuredClone(t.pendingHumanObservation)}:{}}}function Hm(e,t,r){let n=t??zs();if(He(e,n),n.receipt)throw new Error("Completed ASSURE is immutable.");if(jt(r.requestId,"Human observation request"),Ge(r.promptRef,"Human observation prompt"),!r.operationIds.length||new Set(r.operationIds).size!==r.operationIds.length)throw new Error("Human observation request operations are invalid.");for(let i of r.operationIds)if(Lr(e,i).kind!=="user-observation")throw new Error("Human observation request may contain only user operations.");return{...n,schemaVersion:1,evidenceIndex:[...n.evidenceIndex],pendingHumanObservation:{...structuredClone(r),requestedAt:hl(r.requestedAt)}}}function zm(e,t,r){if(He(e,t),t.pendingHumanObservation)throw new Error("ASSURE has pending human observation.");if(t.issues?.some(u=>u.status==="active"))throw new Error("ASSURE has active issues.");Ge(r.contractDigest,"Completion contract digest"),Ge(r.verifiedSnapshotFingerprint,"Verified snapshot fingerprint");let n=new Map(t.evidenceIndex.filter(u=>u.result==="passed"||u.result==="not_applicable").map(u=>[u.operationId,u]));for(let[u,h]of n){let m=Lr(e,u);(r.currentFingerprints[u]!==h.observedFingerprint||m.fingerprintMode==="global"&&h.observedFingerprint!==r.verifiedSnapshotFingerprint)&&n.delete(u)}let i=new Set,s=[];for(let u of e.evidencePreference){let h=n.get(u);if(!(!h||h.subjectIds.every(m=>i.has(m)))){s.push(h.evidenceId);for(let m of h.subjectIds)i.add(m)}}let o=e.subjects.map(u=>u.id).filter(u=>!i.has(u));if(o.length)throw new Error(`ASSURE coverage incomplete: ${o.join(", ")}.`);let a=xt(s),c=hl(r.completedAt),l={schemaVersion:1,taskId:r.taskId,contractDigest:r.contractDigest,verifiedSnapshotFingerprint:r.verifiedSnapshotFingerprint,evidenceIndexDigest:a,completedAt:c},d={...l,receiptDigest:xt(l)};return{...t,schemaVersion:1,evidenceIndex:[...t.evidenceIndex],completionIndex:s,receipt:d}}function E1(e,t,r){sr(e);let n=t??zs();He(e,n);let i=new Map(n.evidenceIndex.map(m=>[m.operationId,m])),s=new Set,o=new Set,a=new Set;for(let m of e.operations){let p=i.get(m.id);p&&p.observedFingerprint===r.currentFingerprints[m.id]&&(p.result==="passed"||p.result==="not_applicable")?s.add(m.id):p?.result==="failed"&&p.observedFingerprint===r.currentFingerprints[m.id]&&o.add(m.id),m.conditional&&r.activationPredicates[m.activationPredicateRef]!==!0&&a.add(m.id)}let c=new Set([...s,...a]),l=new Map(e.operations.filter(m=>!c.has(m.id)).map(m=>[m.id,m])),d=new Set,u=[],h=Math.max(1,Math.min(r.maxConcurrency??e.reviewBudget.maxConcurrency,e.reviewBudget.maxConcurrency));for(;l.size;){let m=!1;for(let y of l.values())y.dependsOn.some(w=>o.has(w)||d.has(w))&&(d.add(y.id),l.delete(y.id),m=!0);let p=[...l.values()].filter(y=>y.dependsOn.every(w=>c.has(w))).toSorted((y,w)=>Bm(y.cost)-Bm(w.cost)||y.id.localeCompare(w.id));if(!p.length){if(!m)throw new Error("Assurance execution graph cannot make progress.");continue}let f=p[0],g=f.readOnly&&f.concurrencySafe?p.filter(y=>y.readOnly&&y.concurrencySafe&&y.cost===f.cost).slice(0,h):[f];u.push(g.map(y=>y.id));for(let y of g)l.delete(y.id),c.add(y.id)}return{reusedOperationIds:[...s].toSorted(),notApplicableOperationIds:[...a].toSorted(),skippedOperationIds:[...d].toSorted(),batches:u}}function I1(e,t){if(!e||e.schemaVersion!==1||!Array.isArray(e.subjectVerdicts)||!Array.isArray(e.findings))throw new Error("Consolidated review result is invalid.");if(e.findings.length>64||e.subjectVerdicts.length>1024)throw new Error("Consolidated review result exceeds budget.");let r=new Set(t);if(!Wm(e.subjectVerdicts.map(i=>i.subjectId),t))throw new Error("Consolidated review subject coverage is incomplete.");let n=new Set;for(let i of e.subjectVerdicts)if(!r.has(i.subjectId)||!["passed","finding"].includes(i.verdict))throw new Error("Consolidated review verdict is invalid.");for(let i of e.findings){if(jt(i.issueId,"Review issue"),n.has(i.issueId)||!r.has(i.subjectId))throw new Error("Consolidated review finding identity is invalid.");if(n.add(i.issueId),!["blocking","major","minor","style"].includes(i.severity))throw new Error(`Review finding ${i.issueId} severity is invalid.`);if(!["low","medium","high"].includes(i.confidence))throw new Error(`Review finding ${i.issueId} confidence is invalid.`);for(let s of[i.locationRef,i.evidence,i.requiredCorrection])if(!s||s.length>4096)throw new Error(`Review finding ${i.issueId} text is invalid.`)}for(let i of e.subjectVerdicts){let s=e.findings.some(o=>o.subjectId===i.subjectId);if(i.verdict==="finding"!==s)throw new Error(`Review verdict for ${i.subjectId} contradicts findings.`)}return structuredClone(e)}function P1(e){return e.findings.some(t=>t.confidence==="low")}function dl(e,t,r){if(He(e,t),t.receipt)throw new Error("Completed ASSURE is immutable.");jt(r.issueId,"Assurance issue"),Lr(e,r.operationId),Ge(r.evidenceRef,"Assurance issue evidence");let n=t.issues?.find(s=>s.issueId===r.issueId),i=n?{...n,status:"active",evidenceRef:r.evidenceRef}:{...r,status:"active",correctionAttempts:0,rootCauseRequired:!1};return{...t,issues:[...(t.issues??[]).filter(s=>s.issueId!==r.issueId),i].toSorted((s,o)=>s.issueId.localeCompare(o.issueId))}}function fl(e,t,r){He(e,t);let n=!1,i=(t.issues??[]).map(s=>{if(s.issueId!==r)return s;if(n=!0,s.status!=="active")throw new Error(`Assurance issue ${r} is not active.`);let o=s.correctionAttempts+1;return Object.assign({},s,{correctionAttempts:o,rootCauseRequired:o>=2})});if(!n)throw new Error(`Unknown assurance issue ${r}.`);return{...t,issues:i}}function pl(e,t,r){He(e,t);let n=!1,i=(t.issues??[]).map(s=>s.issueId!==r?s:(n=!0,Object.assign({},s,{status:"resolved",rootCauseRequired:!1})));if(!n)throw new Error(`Unknown assurance issue ${r}.`);return{...t,issues:i}}function He(e,t){if(sr(e),!t||t.schemaVersion!==1||!Array.isArray(t.evidenceIndex))throw new Error("AssuranceState is invalid.");if(t.evidenceIndex.length>Km)throw new Error("Assurance evidence budget exceeded.");let r=new Set;for(let s of t.issues??[]){if(jt(s.issueId,"Assurance issue"),Lr(e,s.operationId),Ge(s.evidenceRef,"Assurance issue evidence"),r.has(s.issueId)||!Number.isInteger(s.correctionAttempts)||s.correctionAttempts<0||s.rootCauseRequired!==(s.status==="active"&&s.correctionAttempts>=2))throw new Error(`Assurance issue ${s.issueId} is invalid.`);r.add(s.issueId)}let n=new Set,i=new Set;for(let s of t.evidenceIndex){jt(s.evidenceId,"Evidence");let o=Lr(e,s.operationId);if(n.has(s.evidenceId)||i.has(s.operationId))throw new Error("Assurance evidence identities are duplicated.");if(n.add(s.evidenceId),i.add(s.operationId),s.verifierKind!==o.kind||!Wm(s.subjectIds,o.covers)||s.digest!==xt({...s,digest:void 0}))throw new Error(`Assurance evidence ${s.evidenceId} is malformed.`)}if(t.receipt===void 0!=(t.completionIndex===void 0))throw new Error("Assurance completion index and receipt must be paired.");if(t.receipt){if(t.receipt.receiptDigest!==xt({...t.receipt,receiptDigest:void 0}))throw new Error("AssuranceReceipt digest is invalid.");if(t.pendingHumanObservation)throw new Error("Completed ASSURE cannot await observation.");if(t.issues?.some(s=>s.status==="active"))throw new Error("Completed ASSURE cannot retain active issues.");if(!t.completionIndex?.length||t.completionIndex.some(s=>!n.has(s)))throw new Error("Assurance completion index is invalid.");if(t.receipt.evidenceIndexDigest!==xt(t.completionIndex))throw new Error("Assurance completion index digest is stale.")}}function Bm(e){return e==="low"?0:e==="medium"?1:2}function pt(e){return!!(e?.receipt&&e.completionIndex?.length)}function R1(e){let t=new Set;for(let r of e){if(jt(r.id,"Assurance subject"),!["criterion","risk","mandatory_check"].includes(r.kind))throw new Error(`Assurance subject ${r.id} kind is invalid.`);if(t.has(r.id))throw new Error(`Duplicate assurance subject ${r.id}.`);t.add(r.id)}if(!t.size)throw new Error("AssuranceContract requires subjects.");return t}function A1(e,t){let r=new Set,n=new Set;for(let i of e){if(jt(i.id,"Assurance operation"),r.has(i.id))throw new Error(`Duplicate assurance operation ${i.id}.`);r.add(i.id)}for(let i of e){if(!["command","model-inspection","user-observation"].includes(i.kind))throw new Error(`Assurance operation ${i.id} kind is invalid.`);if(!i.covers.length||i.covers.some(s=>!t.has(s)))throw new Error(`Assurance operation ${i.id} coverage is invalid.`);if(new Set(i.covers).size!==i.covers.length)throw new Error(`Assurance operation ${i.id} repeats coverage.`);if(i.dependsOn.some(s=>!r.has(s)||s===i.id))throw new Error(`Assurance operation ${i.id} dependency is invalid.`);if(i.fingerprintMode==="scoped"&&!i.scopeRefs.length)throw new Error(`Scoped operation ${i.id} requires declared scope.`);if(i.conditional!==!!i.activationPredicateRef)throw new Error(`Operation ${i.id} activation predicate is invalid.`);if(i.kind==="command"){if(!i.checkIdentity||!i.successPredicate)throw new Error(`Command operation ${i.id} requires identity and predicate.`);C1(i);let s=Hs(i.checkIdentity);if(n.has(s))throw new Error(`Command operation ${i.id} duplicates normalized identity.`);n.add(s);let o=i.successPredicate;if(!o.exitCodes?.length&&!o.requiredOutputRefs?.length&&!o.requiredArtifactRefs?.length&&!o.thresholdRef)throw new Error(`Command operation ${i.id} success predicate is empty.`);if(o.exitCodes?.some(a=>!Number.isInteger(a)||a<0||a>255))throw new Error(`Command operation ${i.id} exit-code predicate is invalid.`)}else if(i.checkIdentity||i.successPredicate)throw new Error(`Non-command operation ${i.id} cannot define command contract.`)}return T1(e),[...e]}function C1(e){let t=e.checkIdentity;if(!t.executable||!t.logicalCwd||!Array.isArray(t.argv))throw new Error(`Command operation ${e.id} identity is invalid.`);if(t.executable.includes("/")||t.executable.includes("\\")||t.logicalCwd.startsWith("/")||t.logicalCwd.includes("\\")||t.logicalCwd.split("/").includes("..")||t.argv.some(r=>r.includes("\0")))throw new Error(`Command operation ${e.id} contains non-portable identity.`);for(let[r,n]of Object.entries(t.environment))if(!/^[A-Z_][A-Z0-9_]*$/.test(r)||/(?:^|_)(?:TOKEN|SECRET|PASSWORD|KEY)(?:_|$)/.test(r)||!n)throw new Error(`Command operation ${e.id} environment is unsafe.`);for(let r of t.toolFingerprintRefs)Ge(r,"Tool fingerprint")}function T1(e){let t=new Map(e.map(s=>[s.id,s])),r=new Set,n=new Set,i=s=>{if(!n.has(s)){if(r.has(s))throw new Error(`Assurance operation graph contains cycle at ${s}.`);r.add(s);for(let o of t.get(s)?.dependsOn??[])i(o);r.delete(s),n.add(s)}};for(let s of t.keys())i(s)}function Lr(e,t){let r=e.operations.find(n=>n.id===t);if(!r)throw new Error(`Unknown assurance operation ${t}.`);return r}function jt(e,t){if(!S1.test(e))throw new Error(`${t} id is invalid.`)}function Ge(e,t){if(!_1.test(e))throw new Error(`${t} is invalid.`)}function ll(e){return Number.isInteger(e)&&e>0}function Wm(e,t){return e.length===t.length&&[...e].toSorted().every((r,n)=>r===[...t].toSorted()[n])}function hl(e){let t=e??new Date().toISOString();if(Number.isNaN(Date.parse(t)))throw new Error("Timestamp is invalid.");return t}function xt(e){return`sha256:${b1("sha256").update(Hs(e)).digest("hex")}`}function Hs(e){return Array.isArray(e)?`[${e.map(Hs).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,t])=>t!==void 0).toSorted(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${Hs(r)}`).join(",")}}`:JSON.stringify(e)}var Ym=Hn(".codex","benchmarks"),Xm=new Set(["success","failed"]),N1=2e3,Zm=256,q1=/\b(?:sk-[A-Za-z0-9_-]{8,}|(?:api[_-]?key|token|password|secret)\s*[:=]\s*\S+)\b/gi,M1=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi;function L1(e){return e.benchmarkEnabled===!0&&(e.status==="failed"||e.status==="assuring"&&pt(e.assurance))}function F1(e){if(Sl(e.taskId),!Xm.has(e.outcome))throw new Error("Benchmark survey is available only after success or failed.");let t=bl(e.survey),r=e.canonicalChangeContract;if(!r)throw new Error("Benchmark requires canonical Shape contract authority.");return{schemaVersion:1,taskId:e.taskId,recordedAt:U1(e.recordedAt),preparationProfile:e.preparationProfile,outcome:e.outcome,authority:"canonical_change_contract",survey:t,deviations:eg(r,e.actual)}}function eg(e,t){let r=new Set((e.plannedFiles??[]).map(Jm).filter(Boolean)),n=[...new Set(t.createdFiles.map(Jm).filter(Boolean))].slice(0,Zm),i=[];for(let s of n)e.forbidNewFiles?i.push({code:"forbidden_new_file",surfaceRef:s}):r.size&&!r.has(s)&&i.push({code:"unplanned_new_file",surfaceRef:s});return e.validationRequired&&!t.validationComplete&&i.push({code:"missing_validation",surfaceRef:"validation"}),i}var Ws=class{workspaceRoot;root;constructor(t){try{if(this.workspaceRoot=x1(Qm(t)),!O1(this.workspaceRoot).isDirectory())throw new Error("not directory")}catch{throw new Error("Benchmark workspace root must be an existing directory.")}this.root=Qm(this.workspaceRoot,Ym)}path(t){return Sl(t),Hn(this.root,`${t}.json`)}async write(t){let r=vl(t);await this.#e(!0);let n=this.path(r.taskId),i=Hn(this.root,`.${r.taskId}.${D1()}.tmp`);try{let s=await pe.open(i,ml.O_CREAT|ml.O_EXCL|ml.O_WRONLY,384);try{await s.writeFile(`${JSON.stringify(r,null,2)}
151
+ `,"utf8"),await s.sync()}finally{await s.close()}await pe.rename(i,n)}finally{await pe.unlink(i).catch(()=>{})}}async summary(){if(!await this.#e(!1))return yl();let t;try{t=await pe.readdir(this.root)}catch(n){if(gl(n,"ENOENT"))return yl();throw n}let r=[];for(let n of t.toSorted())if(!(!n.endsWith(".json")||j1(n)!==n))try{let i=JSON.parse(await pe.readFile(Hn(this.root,n),"utf8"));r.push(vl(i))}catch{}return tg(r)}async#e(t){for(let r of[Hn(this.workspaceRoot,".codex"),this.root]){t&&await pe.mkdir(r,{mode:448}).catch(i=>{if(!gl(i,"EEXIST"))throw i});let n;try{n=await pe.lstat(r)}catch(i){if(!t&&gl(i,"ENOENT"))return!1;throw i}if(n.isSymbolicLink()||!n.isDirectory())throw new Error("Benchmark path contains a symlink or non-directory component.")}if(await pe.realpath(this.root)!==this.root)throw new Error("Benchmark root resolves outside canonical workspace path.");return!0}};function wl(e){return new Ws(e)}async function V1(e,t){if(!t)return{written:!1};try{return await e.write(t),{written:!0}}catch{return{written:!1,error:"benchmark_write_failed"}}}function tg(e){let t=yl(),r=0;for(let n of e){let i=vl(n);t.recordCount+=1,r+=i.survey.satisfaction,t.conformance[i.survey.conformance]+=1,t.pluginValue[i.survey.pluginValue]+=1,t.outcomes[i.outcome]+=1;for(let s of i.deviations)t.deviations[s.code]+=1}return t.satisfactionAverage=t.recordCount?Math.round(r/t.recordCount*100)/100:null,t}function yl(){return{schemaVersion:1,recordCount:0,satisfactionAverage:null,conformance:{yes:0,partial:0,no:0},pluginValue:{useful:0,neutral:0,counterproductive:0},deviations:{unplanned_new_file:0,forbidden_new_file:0,missing_validation:0},outcomes:{success:0,failed:0}}}function bl(e){if(!Qs(e))throw new Error("Benchmark survey must be an object.");let t=new Set(["satisfaction","conformance","pluginValue","comment"]);if(Object.keys(e).some(n=>!t.has(n)))throw new Error("Benchmark survey contains unsupported data.");if(![1,2,3,4,5].includes(e.satisfaction))throw new Error("Benchmark satisfaction must be 1\u20135.");if(!["yes","partial","no"].includes(e.conformance))throw new Error("Benchmark conformance is invalid.");if(!["useful","neutral","counterproductive"].includes(e.pluginValue))throw new Error("Benchmark plugin value is invalid.");let r=K1(e.comment);return{satisfaction:e.satisfaction,conformance:e.conformance,pluginValue:e.pluginValue,...r?{comment:r}:{}}}function vl(e){return B1(e),{schemaVersion:1,taskId:e.taskId,recordedAt:e.recordedAt,preparationProfile:e.preparationProfile,outcome:e.outcome,authority:e.authority,survey:bl(e.survey),deviations:e.deviations.map(t=>({...t}))}}function B1(e){if(!Qs(e))throw new Error("Benchmark record must be an object.");let t=Object.keys(e),r=new Set(["schemaVersion","taskId","recordedAt","preparationProfile","outcome","authority","survey","deviations"]);if(t.some(n=>!r.has(n)))throw new Error("Benchmark record contains unsupported data.");if(e.schemaVersion!==1||typeof e.taskId!="string")throw new Error("Benchmark record identity is invalid.");if(Sl(e.taskId),typeof e.recordedAt!="string"||Number.isNaN(Date.parse(e.recordedAt)))throw new Error("Benchmark recordedAt is invalid.");if(!["quick","plan"].includes(e.preparationProfile))throw new Error("Benchmark preparation profile is invalid.");if(typeof e.outcome!="string"||!Xm.has(e.outcome))throw new Error("Benchmark outcome is invalid.");if(e.authority!=="canonical_change_contract")throw new Error("Benchmark authority must be canonical Shape contract.");if(bl(e.survey),!Array.isArray(e.deviations)||e.deviations.length>Zm+2)throw new Error("Benchmark deviations are invalid.");for(let n of e.deviations)if(!Qs(n)||!["unplanned_new_file","forbidden_new_file","missing_validation"].includes(n.code)||typeof n.surfaceRef!="string"||!n.surfaceRef||n.surfaceRef.length>512||Object.keys(n).some(i=>i!=="code"&&i!=="surfaceRef"))throw new Error("Benchmark deviation is invalid.")}function K1(e){return typeof e!="string"?"":e.replace(q1,"[REDACTED]").replace(M1,"[REDACTED_EMAIL]").replace(/\u0000/g,"").trim().slice(0,N1)}function Jm(e){if(typeof e!="string")return"";let t=e.replace(/\\/g,"/").replace(/^\.\/+/,"").replace(/\u0000/g,"").trim();return!t||t.startsWith("/")||t.split("/").includes("..")?"":t.slice(0,512)}function U1(e){return e&&!Number.isNaN(Date.parse(e))?new Date(e).toISOString():new Date().toISOString()}function Sl(e){if(!e||e==="."||e===".."||/[/\\\u0000]/.test(e))throw new Error("Benchmark task ID must be one non-traversing path segment.")}function gl(e,t){return Qs(e)&&e.code===t}function Qs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var nw=Ve(_d(),1),sw=Ve(Mr(),1);import{existsSync as RT,readFileSync as iw}from"node:fs";import{join as kd}from"node:path";import{fileURLToPath as AT}from"node:url";var Ae={SUCCESS:0,INVALID_INVOCATION:2,INVALID_CONFIGURATION:3,POLICY_CONTRADICTION:4,STATE_CONFLICT:5,BLOCKED:6,INTERNAL_ERROR:10};var $i=class extends Error{constructor(r,n,i){super(r);this.source=n;this.errors=i}source;errors;exitCode=Ae.INVALID_CONFIGURATION},ow={plan:"auto",quota:{warningPercent:50,criticalPercent:80,unknownPolicy:"conservative"},modelAllowlist:["gpt-5.6-luna","gpt-5.6-terra","gpt-5.6-sol"],modelCosts:sl},$d={schemaVersion:1,worktree:{mode:"auto"},merge:"never",integrations:{plugins:[],skills:[]},subscription:ow},rw=new Map;function nn(e,t){let r=rw.get(e);if(!r){let i=JSON.parse(iw(AT(new URL("../schemas/"+e+".schema.json",import.meta.url)),"utf8"));r=new nw.Ajv2020({allErrors:!0,strict:!0}).compile(i),rw.set(e,r)}return{valid:r(t),errors:r.errors?[...r.errors]:[]}}function Co(e,t="config"){let r=aw($d,e),n=nn("config",r);if(!n.valid){let i=n.errors[0];throw new $i(`Invalid configuration from ${t} at ${i?.instancePath||"/"}: ${i?.message??"schema validation failed"}.`,t,n.errors)}}function Ed(e={}){let t=e.cwd??process.cwd(),r=e.home??process.env.HOME??"",n=[{source:"user",path:kd(r,".codex","dev-flow.yaml")},{source:"repo",path:kd(t,".codex","dev-flow.yaml")},{source:"local",path:kd(t,".codex","dev-flow.local.yaml")}],i=[];for(let s of n){if(!RT(s.path))continue;let o=(0,sw.parse)(iw(s.path,"utf8"));if(!vr(o))throw new $i(`Invalid configuration from ${s.source}: root must be an object.`,s.source,[]);i.push({source:s.source,value:o})}return e.flags&&i.push({source:"flags",value:e.flags}),i}function aw(e,t){let r=rn(e);for(let[n,i]of Object.entries(t)){let s=r[n];vr(s)&&vr(i)?r[n]=aw(s,i):r[n]=rn(i)}return r}function vr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function rn(e){return Array.isArray(e)?e.map(rn):vr(e)?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,rn(r)])):e}function cw(e,t,r,n){if(vr(e)){for(let[i,s]of Object.entries(e))cw(s,t,r,n?n+"."+i:i);return}r[n]=t}function lw(e,t,r,n,i=""){for(let[s,o]of Object.entries(t)){let a=i?i+"."+s:s,c=e[s];if(vr(c)&&vr(o)){lw(c,o,r,n,a);continue}e[s]=rn(o),cw(o,r,n,a)}}function Id(e){let r=e.some(s=>s.source==="defaults")?e:[{source:"defaults",value:$d},...e];for(let s of r)Co(s.value,s.source);let n={},i={};for(let s of r)lw(n,s.value,s.source,i);return{value:n,provenance:i}}function Pd(e){return{value:rn(e.value),provenance:{...e.provenance}}}var ye=class extends Error{exitCode=Ae.INVALID_INVOCATION};function Ye(e){throw new ye(e)}function Rd(e){e.length===0&&Ye("An objective or subcommand is required.");let[t,...r]=e;if(t||Ye("An objective or subcommand is required."),t==="--help")return r.length!==0&&Ye("help accepts no arguments."),{command:"help"};if(t==="init")return r.length!==0&&Ye("init accepts no arguments."),{command:"init"};if(t==="resume")return(r.length!==1||!r[0])&&Ye("resume requires exactly one task id."),{command:"resume",taskId:r[0]};if(t==="status")return r.length>1&&Ye("status accepts at most one task id."),{command:"status",taskId:r[0]};if(t==="benchmark"){if(r.length===1&&r[0]==="summary")return{command:"benchmark_summary"};Ye("benchmark requires exactly the summary subcommand.")}if(t==="config"){let[s,...o]=r;if(s==="show"&&(o.length===0||o.length===1&&o[0]==="--explain"))return{command:"config_show",explain:o[0]==="--explain"};if(s==="validate"&&(o.length===0||o.length===1&&o[0]==="--json"))return{command:"config_validate",json:o[0]==="--json"};Ye("Invalid config invocation.")}if(t==="project-profile"){let[s,...o]=r,a=o.length===1&&o[0]==="--local";if(o.length!==0&&!a&&Ye("Invalid project-profile invocation."),s==="inspect"&&o.length===0)return{command:"project_profile_inspect",local:!1};if(s==="view")return{command:"project_profile_view",local:a};if(s==="validate")return{command:"project_profile_validate",local:a};if(s==="publish")return{command:"project_profile_publish",local:a};if(s==="session-view"&&o.length===0)return{command:"project_profile_session_view"};if(s==="session-save"&&o.length===0)return{command:"project_profile_session_save"};if(s==="session-clear"&&o.length===0)return{command:"project_profile_session_clear"};Ye("Invalid project-profile invocation.")}let n=t==="--benchmark",i=n?r:e;return(i.length===0||i.some(s=>s.startsWith("--")))&&Ye("A run requires an objective and no unsupported flags."),{command:"run",objective:i.join(" "),flags:n?{benchmark:!0}:{}}}var yw=Ve(Cd(),1);import{stdout as vw,stdin as jT}from"node:process";var qe=Ve(Dd(),1);import NT from"node:readline";var qT=e=>e===161||e===164||e===167||e===168||e===170||e===173||e===174||e>=176&&e<=180||e>=182&&e<=186||e>=188&&e<=191||e===198||e===208||e===215||e===216||e>=222&&e<=225||e===230||e>=232&&e<=234||e===236||e===237||e===240||e===242||e===243||e>=247&&e<=250||e===252||e===254||e===257||e===273||e===275||e===283||e===294||e===295||e===299||e>=305&&e<=307||e===312||e>=319&&e<=322||e===324||e>=328&&e<=331||e===333||e===338||e===339||e===358||e===359||e===363||e===462||e===464||e===466||e===468||e===470||e===472||e===474||e===476||e===593||e===609||e===708||e===711||e>=713&&e<=715||e===717||e===720||e>=728&&e<=731||e===733||e===735||e>=768&&e<=879||e>=913&&e<=929||e>=931&&e<=937||e>=945&&e<=961||e>=963&&e<=969||e===1025||e>=1040&&e<=1103||e===1105||e===8208||e>=8211&&e<=8214||e===8216||e===8217||e===8220||e===8221||e>=8224&&e<=8226||e>=8228&&e<=8231||e===8240||e===8242||e===8243||e===8245||e===8251||e===8254||e===8308||e===8319||e>=8321&&e<=8324||e===8364||e===8451||e===8453||e===8457||e===8467||e===8470||e===8481||e===8482||e===8486||e===8491||e===8531||e===8532||e>=8539&&e<=8542||e>=8544&&e<=8555||e>=8560&&e<=8569||e===8585||e>=8592&&e<=8601||e===8632||e===8633||e===8658||e===8660||e===8679||e===8704||e===8706||e===8707||e===8711||e===8712||e===8715||e===8719||e===8721||e===8725||e===8730||e>=8733&&e<=8736||e===8739||e===8741||e>=8743&&e<=8748||e===8750||e>=8756&&e<=8759||e===8764||e===8765||e===8776||e===8780||e===8786||e===8800||e===8801||e>=8804&&e<=8807||e===8810||e===8811||e===8814||e===8815||e===8834||e===8835||e===8838||e===8839||e===8853||e===8857||e===8869||e===8895||e===8978||e>=9312&&e<=9449||e>=9451&&e<=9547||e>=9552&&e<=9587||e>=9600&&e<=9615||e>=9618&&e<=9621||e===9632||e===9633||e>=9635&&e<=9641||e===9650||e===9651||e===9654||e===9655||e===9660||e===9661||e===9664||e===9665||e>=9670&&e<=9672||e===9675||e>=9678&&e<=9681||e>=9698&&e<=9701||e===9711||e===9733||e===9734||e===9737||e===9742||e===9743||e===9756||e===9758||e===9792||e===9794||e===9824||e===9825||e>=9827&&e<=9829||e>=9831&&e<=9834||e===9836||e===9837||e===9839||e===9886||e===9887||e===9919||e>=9926&&e<=9933||e>=9935&&e<=9939||e>=9941&&e<=9953||e===9955||e===9960||e===9961||e>=9963&&e<=9969||e===9972||e>=9974&&e<=9977||e===9979||e===9980||e===9982||e===9983||e===10045||e>=10102&&e<=10111||e>=11094&&e<=11097||e>=12872&&e<=12879||e>=57344&&e<=63743||e>=65024&&e<=65039||e===65533||e>=127232&&e<=127242||e>=127248&&e<=127277||e>=127280&&e<=127337||e>=127344&&e<=127373||e===127375||e===127376||e>=127387&&e<=127404||e>=917760&&e<=917999||e>=983040&&e<=1048573||e>=1048576&&e<=1114109,MT=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,LT=e=>e>=4352&&e<=4447||e===8986||e===8987||e===9001||e===9002||e>=9193&&e<=9196||e===9200||e===9203||e===9725||e===9726||e===9748||e===9749||e>=9800&&e<=9811||e===9855||e===9875||e===9889||e===9898||e===9899||e===9917||e===9918||e===9924||e===9925||e===9934||e===9940||e===9962||e===9970||e===9971||e===9973||e===9978||e===9981||e===9989||e===9994||e===9995||e===10024||e===10060||e===10062||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e===11035||e===11036||e===11088||e===11093||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=19968&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=94176&&e<=94180||e===94192||e===94193||e>=94208&&e<=100343||e>=100352&&e<=101589||e>=101632&&e<=101640||e>=110576&&e<=110579||e>=110581&&e<=110587||e===110589||e===110590||e>=110592&&e<=110882||e===110898||e>=110928&&e<=110930||e===110933||e>=110948&&e<=110951||e>=110960&&e<=111355||e===126980||e===127183||e===127374||e>=127377&&e<=127386||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e===127568||e===127569||e>=127584&&e<=127589||e>=127744&&e<=127776||e>=127789&&e<=127797||e>=127799&&e<=127868||e>=127870&&e<=127891||e>=127904&&e<=127946||e>=127951&&e<=127955||e>=127968&&e<=127984||e===127988||e>=127992&&e<=128062||e===128064||e>=128066&&e<=128252||e>=128255&&e<=128317||e>=128331&&e<=128334||e>=128336&&e<=128359||e===128378||e===128405||e===128406||e===128420||e>=128507&&e<=128591||e>=128640&&e<=128709||e===128716||e>=128720&&e<=128722||e>=128725&&e<=128727||e>=128732&&e<=128735||e===128747||e===128748||e>=128756&&e<=128764||e>=128992&&e<=129003||e===129008||e>=129292&&e<=129338||e>=129340&&e<=129349||e>=129351&&e<=129535||e>=129648&&e<=129660||e>=129664&&e<=129672||e>=129680&&e<=129725||e>=129727&&e<=129733||e>=129742&&e<=129755||e>=129760&&e<=129768||e>=129776&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141,Od=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,Oo=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,xo=/\t{1,1000}/y,xd=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),jo=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,FT=new RegExp("\\p{M}+","gu"),VT={limit:1/0,ellipsis:""},ww=(e,t={},r={})=>{let n=t.limit??1/0,i=t.ellipsis??"",s=t?.ellipsisWidth??(i?ww(i,VT,r).width:0),o=r.ansiWidth??0,a=r.controlWidth??0,c=r.tabWidth??8,l=r.ambiguousWidth??1,d=r.emojiWidth??2,u=r.fullWidthWidth??2,h=r.regularWidth??1,m=r.wideWidth??2,p=0,f=0,g=e.length,y=0,w=!1,b=g,$=Math.max(0,n-s),S=0,I=0,k=0,_=0;e:for(;;){if(I>S||f>=g&&f>p){let q=e.slice(S,I)||e.slice(p,f);y=0;for(let Q of q.replaceAll(FT,"")){let re=Q.codePointAt(0)||0;if(MT(re)?_=u:LT(re)?_=m:l!==h&&qT(re)?_=l:_=h,k+_>$&&(b=Math.min(b,Math.max(S,p)+y)),k+_>n){w=!0;break e}y+=Q.length,k+=_}S=I=0}if(f>=g)break;if(jo.lastIndex=f,jo.test(e)){if(y=jo.lastIndex-f,_=y*h,k+_>$&&(b=Math.min(b,f+Math.floor(($-k)/h))),k+_>n){w=!0;break}k+=_,S=p,I=f,f=p=jo.lastIndex;continue}if(Od.lastIndex=f,Od.test(e)){if(k+o>$&&(b=Math.min(b,f)),k+o>n){w=!0;break}k+=o,S=p,I=f,f=p=Od.lastIndex;continue}if(Oo.lastIndex=f,Oo.test(e)){if(y=Oo.lastIndex-f,_=y*a,k+_>$&&(b=Math.min(b,f+Math.floor(($-k)/a))),k+_>n){w=!0;break}k+=_,S=p,I=f,f=p=Oo.lastIndex;continue}if(xo.lastIndex=f,xo.test(e)){if(y=xo.lastIndex-f,_=y*c,k+_>$&&(b=Math.min(b,f+Math.floor(($-k)/c))),k+_>n){w=!0;break}k+=_,S=p,I=f,f=p=xo.lastIndex;continue}if(xd.lastIndex=f,xd.test(e)){if(k+d>$&&(b=Math.min(b,f)),k+d>n){w=!0;break}k+=d,S=p,I=f,f=p=xd.lastIndex;continue}f+=1}return{width:w?$:k,index:w?b:g,truncated:w,ellipsed:w&&n>=s}},BT={limit:1/0,ellipsis:"",ellipsisWidth:0},Ei=(e,t={})=>ww(e,BT,t).width,Vo="\x1B",bw="\x9B",KT=39,qd="\x07",Sw="[",UT="]",_w="m",Md=`${UT}8;;`,pw=new RegExp(`(?:\\${Sw}(?<code>\\d+)m|\\${Md}(?<uri>.*)${qd})`,"y"),GT=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},hw=e=>`${Vo}${Sw}${e}${_w}`,mw=e=>`${Vo}${Md}${e}${qd}`,HT=e=>e.map(t=>Ei(t)),jd=(e,t,r)=>{let n=t[Symbol.iterator](),i=!1,s=!1,o=e.at(-1),a=o===void 0?0:Ei(o),c=n.next(),l=n.next(),d=0;for(;!c.done;){let u=c.value,h=Ei(u);a+h<=r?e[e.length-1]+=u:(e.push(u),a=0),(u===Vo||u===bw)&&(i=!0,s=t.startsWith(Md,d+1)),i?s?u===qd&&(i=!1,s=!1):u===_w&&(i=!1):(a+=h,a===r&&!l.done&&(e.push(""),a=0)),c=l,l=n.next(),d+=u.length}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop())},zT=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(Ei(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},WT=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",i,s,o=e.split(" "),a=HT(o),c=[""];for(let[p,f]of o.entries()){r.trim!==!1&&(c[c.length-1]=(c.at(-1)??"").trimStart());let g=Ei(c.at(-1)??"");if(p!==0&&(g>=t&&(r.wordWrap===!1||r.trim===!1)&&(c.push(""),g=0),(g>0||r.trim===!1)&&(c[c.length-1]+=" ",g++)),r.hard&&a[p]>t){let y=t-g,w=1+Math.floor((a[p]-y-1)/t);Math.floor((a[p]-1)/t)<w&&c.push(""),jd(c,f,t);continue}if(g+a[p]>t&&g>0&&a[p]>0){if(r.wordWrap===!1&&g<t){jd(c,f,t);continue}c.push("")}if(g+a[p]>t&&r.wordWrap===!1){jd(c,f,t);continue}c[c.length-1]+=f}r.trim!==!1&&(c=c.map(p=>zT(p)));let l=c.join(`
152
+ `),d=l[Symbol.iterator](),u=d.next(),h=d.next(),m=0;for(;!u.done;){let p=u.value,f=h.value;if(n+=p,p===Vo||p===bw){pw.lastIndex=m+1;let y=pw.exec(l)?.groups;if(y?.code!==void 0){let w=Number.parseFloat(y.code);i=w===KT?void 0:w}else y?.uri!==void 0&&(s=y.uri.length===0?void 0:y.uri)}let g=i?GT(i):void 0;f===`
153
+ `?(s&&(n+=mw("")),i&&g&&(n+=hw(g))):p===`
154
+ `&&(i&&g&&(n+=hw(i)),s&&(n+=mw(s))),m+=p.length,u=h,h=d.next()}return n};function Nd(e,t,r){return String(e).normalize().replaceAll(`\r
155
+ `,`
156
+ `).split(`
157
+ `).map(n=>WT(n,t,r)).join(`
158
+ `)}var QT=["up","down","left","right","space","enter","cancel"],Ut={actions:new Set(QT),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0};function kw(e,t){if(typeof e=="string")return Ut.aliases.get(e)===t;for(let r of e)if(r!==void 0&&kw(r,t))return!0;return!1}function JT(e,t){if(e===t)return;let r=e.split(`
159
+ `),n=t.split(`
160
+ `),i=Math.max(r.length,n.length),s=[];for(let o=0;o<i;o++)r[o]!==n[o]&&s.push(o);return{lines:s,numLinesBefore:r.length,numLinesAfter:n.length,numLines:i}}var fM=globalThis.process.platform.startsWith("win"),gw=Symbol("clack:cancel");function No(e,t){let r=e;r.isTTY&&r.setRawMode(t)}var Bo=e=>"columns"in e&&typeof e.columns=="number"?e.columns:80,Ld=e=>"rows"in e&&typeof e.rows=="number"?e.rows:20;function Ko(e,t,r,n=r){let i=Bo(e??vw);return Nd(t,i-r.length,{hard:!0,trim:!1}).split(`
161
+ `).map((s,o)=>`${o===0?n:r}${s}`).join(`
162
+ `)}var Mo=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(t,r=!0){let{input:n=jT,output:i=vw,render:s,signal:o,...a}=t;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=s.bind(this),this._track=r,this._abortSignal=o,this.input=n,this.output=i}unsubscribe(){this._subscribers.clear()}setSubscriber(t,r){let n=this._subscribers.get(t)??[];n.push(r),this._subscribers.set(t,n)}on(t,r){this.setSubscriber(t,{cb:r})}once(t,r){this.setSubscriber(t,{cb:r,once:!0})}emit(t,...r){let n=this._subscribers.get(t)??[],i=[];for(let s of n)s.cb(...r),s.once&&i.push(()=>n.splice(n.indexOf(s),1));for(let s of i)s()}prompt(){return new Promise(t=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(gw);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=NT.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),No(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(qe.cursor.show),this.output.off("resize",this.render),No(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(qe.cursor.show),this.output.off("resize",this.render),No(this.input,!1),t(gw)})})}_isActionKey(t,r){return t===" "}_setValue(t){this.value=t,this.emit("value",this.value)}_setUserInput(t,r){this.userInput=t??"",this.emit("userInput",this.userInput),r&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(t,r){if(this._track&&r.name!=="return"&&(r.name&&this._isActionKey(t,r)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),r?.name&&(!this._track&&Ut.aliases.has(r.name)&&this.emit("cursor",Ut.aliases.get(r.name)),Ut.actions.has(r.name)&&this.emit("cursor",r.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t?.toLowerCase(),r),r?.name==="return"){if(this.opts.validate){let n=this.opts.validate(this.value);n&&(this.error=n instanceof Error?n.message:n,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}kw([t,r?.name,r?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
163
+ `),No(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=Nd(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
164
+ `).length-1;this.output.write(qe.cursor.move(-999,t*-1))}render(){let t=Nd(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(qe.cursor.hide);else{let r=JT(this._prevFrame,t),n=Ld(this.output);if(this.restoreCursor(),r){let i=Math.max(0,r.numLinesAfter-n),s=Math.max(0,r.numLinesBefore-n),o=r.lines.find(a=>a>=i);if(o===void 0){this._prevFrame=t;return}if(r.lines.length===1){this.output.write(qe.cursor.move(0,o-s)),this.output.write(qe.erase.lines(1));let a=t.split(`
165
+ `);this.output.write(a[o]),this._prevFrame=t,this.output.write(qe.cursor.move(0,a.length-o-1));return}else if(r.lines.length>1){if(i<s)o=i;else{let c=o-s;c>0&&this.output.write(qe.cursor.move(0,c))}this.output.write(qe.erase.down());let a=t.split(`
166
+ `).slice(o);this.output.write(a.join(`
167
+ `)),this._prevFrame=t;return}}this.output.write(qe.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}};function qo(e,t,r){let n=e+t,i=Math.max(r.length-1,0),s=n<0?i:n>i?0:n;return r[s].disabled?qo(s,t<0?-1:1,r):s}var Lo=class extends Mo{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(t){super(t,!1),this.options=t.options;let r=this.options.findIndex(({value:i})=>i===t.initialValue),n=r===-1?0:r;this.cursor=this.options[n].disabled?qo(n,1,this.options):n,this.changeValue(),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=qo(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=qo(this.cursor,1,this.options);break}this.changeValue()})}};var Fo=class extends Mo{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${this.userInput}\u2588`;let r=t.slice(0,this.cursor),[n,...i]=t.slice(this.cursor);return`${r}${yw.default.inverse(n)}${i.join("")}`}get cursor(){return this._cursor}constructor(t){super({...t,initialUserInput:t.initialUserInput??t.initialValue}),this.on("userInput",r=>{this._setValue(r)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}};var R=Ve(Cd(),1);import Me from"node:process";var Aw=Ve(Dd(),1);function XT(){return Me.platform!=="win32"?Me.env.TERM!=="linux":!!Me.env.CI||!!Me.env.WT_SESSION||!!Me.env.TERMINUS_SUBLIME||Me.env.ConEmuTask==="{cmd::Cmder}"||Me.env.TERM_PROGRAM==="Terminus-Sublime"||Me.env.TERM_PROGRAM==="vscode"||Me.env.TERM==="xterm-256color"||Me.env.TERM==="alacritty"||Me.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var ZT=XT();var W=(e,t)=>ZT?e:t,eD=W("\u25C6","*"),tD=W("\u25A0","x"),rD=W("\u25B2","x"),Cw=W("\u25C7","o"),nD=W("\u250C","T"),ae=W("\u2502","|"),Ii=W("\u2514","\u2014"),$M=W("\u2510","T"),EM=W("\u2518","\u2014"),iD=W("\u25CF",">"),$w=W("\u25CB"," "),IM=W("\u25FB","[\u2022]"),PM=W("\u25FC","[+]"),RM=W("\u25FB","[ ]"),AM=W("\u25AA","\u2022"),Ew=W("\u2500","-"),sD=W("\u256E","+"),oD=W("\u251C","+"),aD=W("\u256F","+"),cD=W("\u2570","+"),CM=W("\u256D","+"),TM=W("\u25CF","\u2022"),DM=W("\u25C6","*"),OM=W("\u25B2","!"),xM=W("\u25A0","x"),Tw=e=>{switch(e){case"initial":case"active":return R.default.cyan(eD);case"cancel":return R.default.red(tD);case"error":return R.default.yellow(rD);case"submit":return R.default.green(Cw)}},lD=e=>{switch(e){case"initial":case"active":return R.default.cyan(ae);case"cancel":return R.default.red(ae);case"error":return R.default.yellow(ae);case"submit":return R.default.green(ae)}},uD=e=>e===161||e===164||e===167||e===168||e===170||e===173||e===174||e>=176&&e<=180||e>=182&&e<=186||e>=188&&e<=191||e===198||e===208||e===215||e===216||e>=222&&e<=225||e===230||e>=232&&e<=234||e===236||e===237||e===240||e===242||e===243||e>=247&&e<=250||e===252||e===254||e===257||e===273||e===275||e===283||e===294||e===295||e===299||e>=305&&e<=307||e===312||e>=319&&e<=322||e===324||e>=328&&e<=331||e===333||e===338||e===339||e===358||e===359||e===363||e===462||e===464||e===466||e===468||e===470||e===472||e===474||e===476||e===593||e===609||e===708||e===711||e>=713&&e<=715||e===717||e===720||e>=728&&e<=731||e===733||e===735||e>=768&&e<=879||e>=913&&e<=929||e>=931&&e<=937||e>=945&&e<=961||e>=963&&e<=969||e===1025||e>=1040&&e<=1103||e===1105||e===8208||e>=8211&&e<=8214||e===8216||e===8217||e===8220||e===8221||e>=8224&&e<=8226||e>=8228&&e<=8231||e===8240||e===8242||e===8243||e===8245||e===8251||e===8254||e===8308||e===8319||e>=8321&&e<=8324||e===8364||e===8451||e===8453||e===8457||e===8467||e===8470||e===8481||e===8482||e===8486||e===8491||e===8531||e===8532||e>=8539&&e<=8542||e>=8544&&e<=8555||e>=8560&&e<=8569||e===8585||e>=8592&&e<=8601||e===8632||e===8633||e===8658||e===8660||e===8679||e===8704||e===8706||e===8707||e===8711||e===8712||e===8715||e===8719||e===8721||e===8725||e===8730||e>=8733&&e<=8736||e===8739||e===8741||e>=8743&&e<=8748||e===8750||e>=8756&&e<=8759||e===8764||e===8765||e===8776||e===8780||e===8786||e===8800||e===8801||e>=8804&&e<=8807||e===8810||e===8811||e===8814||e===8815||e===8834||e===8835||e===8838||e===8839||e===8853||e===8857||e===8869||e===8895||e===8978||e>=9312&&e<=9449||e>=9451&&e<=9547||e>=9552&&e<=9587||e>=9600&&e<=9615||e>=9618&&e<=9621||e===9632||e===9633||e>=9635&&e<=9641||e===9650||e===9651||e===9654||e===9655||e===9660||e===9661||e===9664||e===9665||e>=9670&&e<=9672||e===9675||e>=9678&&e<=9681||e>=9698&&e<=9701||e===9711||e===9733||e===9734||e===9737||e===9742||e===9743||e===9756||e===9758||e===9792||e===9794||e===9824||e===9825||e>=9827&&e<=9829||e>=9831&&e<=9834||e===9836||e===9837||e===9839||e===9886||e===9887||e===9919||e>=9926&&e<=9933||e>=9935&&e<=9939||e>=9941&&e<=9953||e===9955||e===9960||e===9961||e>=9963&&e<=9969||e===9972||e>=9974&&e<=9977||e===9979||e===9980||e===9982||e===9983||e===10045||e>=10102&&e<=10111||e>=11094&&e<=11097||e>=12872&&e<=12879||e>=57344&&e<=63743||e>=65024&&e<=65039||e===65533||e>=127232&&e<=127242||e>=127248&&e<=127277||e>=127280&&e<=127337||e>=127344&&e<=127373||e===127375||e===127376||e>=127387&&e<=127404||e>=917760&&e<=917999||e>=983040&&e<=1048573||e>=1048576&&e<=1114109,dD=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,fD=e=>e>=4352&&e<=4447||e===8986||e===8987||e===9001||e===9002||e>=9193&&e<=9196||e===9200||e===9203||e===9725||e===9726||e===9748||e===9749||e>=9800&&e<=9811||e===9855||e===9875||e===9889||e===9898||e===9899||e===9917||e===9918||e===9924||e===9925||e===9934||e===9940||e===9962||e===9970||e===9971||e===9973||e===9978||e===9981||e===9989||e===9994||e===9995||e===10024||e===10060||e===10062||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e===11035||e===11036||e===11088||e===11093||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=19968&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=94176&&e<=94180||e===94192||e===94193||e>=94208&&e<=100343||e>=100352&&e<=101589||e>=101632&&e<=101640||e>=110576&&e<=110579||e>=110581&&e<=110587||e===110589||e===110590||e>=110592&&e<=110882||e===110898||e>=110928&&e<=110930||e===110933||e>=110948&&e<=110951||e>=110960&&e<=111355||e===126980||e===127183||e===127374||e>=127377&&e<=127386||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e===127568||e===127569||e>=127584&&e<=127589||e>=127744&&e<=127776||e>=127789&&e<=127797||e>=127799&&e<=127868||e>=127870&&e<=127891||e>=127904&&e<=127946||e>=127951&&e<=127955||e>=127968&&e<=127984||e===127988||e>=127992&&e<=128062||e===128064||e>=128066&&e<=128252||e>=128255&&e<=128317||e>=128331&&e<=128334||e>=128336&&e<=128359||e===128378||e===128405||e===128406||e===128420||e>=128507&&e<=128591||e>=128640&&e<=128709||e===128716||e>=128720&&e<=128722||e>=128725&&e<=128727||e>=128732&&e<=128735||e===128747||e===128748||e>=128756&&e<=128764||e>=128992&&e<=129003||e===129008||e>=129292&&e<=129338||e>=129340&&e<=129349||e>=129351&&e<=129535||e>=129648&&e<=129660||e>=129664&&e<=129672||e>=129680&&e<=129725||e>=129727&&e<=129733||e>=129742&&e<=129755||e>=129760&&e<=129768||e>=129776&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141,Fd=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,Uo=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Go=/\t{1,1000}/y,Vd=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),Ho=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,pD=new RegExp("\\p{M}+","gu"),hD={limit:1/0,ellipsis:""},Dw=(e,t={},r={})=>{let n=t.limit??1/0,i=t.ellipsis??"",s=t?.ellipsisWidth??(i?Dw(i,hD,r).width:0),o=r.ansiWidth??0,a=r.controlWidth??0,c=r.tabWidth??8,l=r.ambiguousWidth??1,d=r.emojiWidth??2,u=r.fullWidthWidth??2,h=r.regularWidth??1,m=r.wideWidth??2,p=0,f=0,g=e.length,y=0,w=!1,b=g,$=Math.max(0,n-s),S=0,I=0,k=0,_=0;e:for(;;){if(I>S||f>=g&&f>p){let q=e.slice(S,I)||e.slice(p,f);y=0;for(let Q of q.replaceAll(pD,"")){let re=Q.codePointAt(0)||0;if(dD(re)?_=u:fD(re)?_=m:l!==h&&uD(re)?_=l:_=h,k+_>$&&(b=Math.min(b,Math.max(S,p)+y)),k+_>n){w=!0;break e}y+=Q.length,k+=_}S=I=0}if(f>=g)break;if(Ho.lastIndex=f,Ho.test(e)){if(y=Ho.lastIndex-f,_=y*h,k+_>$&&(b=Math.min(b,f+Math.floor(($-k)/h))),k+_>n){w=!0;break}k+=_,S=p,I=f,f=p=Ho.lastIndex;continue}if(Fd.lastIndex=f,Fd.test(e)){if(k+o>$&&(b=Math.min(b,f)),k+o>n){w=!0;break}k+=o,S=p,I=f,f=p=Fd.lastIndex;continue}if(Uo.lastIndex=f,Uo.test(e)){if(y=Uo.lastIndex-f,_=y*a,k+_>$&&(b=Math.min(b,f+Math.floor(($-k)/a))),k+_>n){w=!0;break}k+=_,S=p,I=f,f=p=Uo.lastIndex;continue}if(Go.lastIndex=f,Go.test(e)){if(y=Go.lastIndex-f,_=y*c,k+_>$&&(b=Math.min(b,f+Math.floor(($-k)/c))),k+_>n){w=!0;break}k+=_,S=p,I=f,f=p=Go.lastIndex;continue}if(Vd.lastIndex=f,Vd.test(e)){if(k+d>$&&(b=Math.min(b,f)),k+d>n){w=!0;break}k+=d,S=p,I=f,f=p=Vd.lastIndex;continue}f+=1}return{width:w?$:k,index:w?b:g,truncated:w,ellipsed:w&&n>=s}},mD={limit:1/0,ellipsis:"",ellipsisWidth:0},at=(e,t={})=>Dw(e,mD,t).width,Wo="\x1B",Ow="\x9B",gD=39,Ud="\x07",xw="[",yD="]",jw="m",Gd=`${yD}8;;`,Iw=new RegExp(`(?:\\${xw}(?<code>\\d+)m|\\${Gd}(?<uri>.*)${Ud})`,"y"),vD=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},Pw=e=>`${Wo}${xw}${e}${jw}`,Rw=e=>`${Wo}${Gd}${e}${Ud}`,wD=e=>e.map(t=>at(t)),Bd=(e,t,r)=>{let n=t[Symbol.iterator](),i=!1,s=!1,o=e.at(-1),a=o===void 0?0:at(o),c=n.next(),l=n.next(),d=0;for(;!c.done;){let u=c.value,h=at(u);a+h<=r?e[e.length-1]+=u:(e.push(u),a=0),(u===Wo||u===Ow)&&(i=!0,s=t.startsWith(Gd,d+1)),i?s?u===Ud&&(i=!1,s=!1):u===jw&&(i=!1):(a+=h,a===r&&!l.done&&(e.push(""),a=0)),c=l,l=n.next(),d+=u.length}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop())},bD=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(at(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},SD=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",i,s,o=e.split(" "),a=wD(o),c=[""];for(let[p,f]of o.entries()){r.trim!==!1&&(c[c.length-1]=(c.at(-1)??"").trimStart());let g=at(c.at(-1)??"");if(p!==0&&(g>=t&&(r.wordWrap===!1||r.trim===!1)&&(c.push(""),g=0),(g>0||r.trim===!1)&&(c[c.length-1]+=" ",g++)),r.hard&&a[p]>t){let y=t-g,w=1+Math.floor((a[p]-y-1)/t);Math.floor((a[p]-1)/t)<w&&c.push(""),Bd(c,f,t);continue}if(g+a[p]>t&&g>0&&a[p]>0){if(r.wordWrap===!1&&g<t){Bd(c,f,t);continue}c.push("")}if(g+a[p]>t&&r.wordWrap===!1){Bd(c,f,t);continue}c[c.length-1]+=f}r.trim!==!1&&(c=c.map(p=>bD(p)));let l=c.join(`
168
+ `),d=l[Symbol.iterator](),u=d.next(),h=d.next(),m=0;for(;!u.done;){let p=u.value,f=h.value;if(n+=p,p===Wo||p===Ow){Iw.lastIndex=m+1;let y=Iw.exec(l)?.groups;if(y?.code!==void 0){let w=Number.parseFloat(y.code);i=w===gD?void 0:w}else y?.uri!==void 0&&(s=y.uri.length===0?void 0:y.uri)}let g=i?vD(i):void 0;f===`
169
+ `?(s&&(n+=Rw("")),i&&g&&(n+=Pw(g))):p===`
170
+ `&&(i&&g&&(n+=Pw(i)),s&&(n+=Rw(s))),m+=p.length,u=h,h=d.next()}return n};function Kd(e,t,r){return String(e).normalize().replaceAll(`\r
171
+ `,`
172
+ `).split(`
173
+ `).map(n=>SD(n,t,r)).join(`
174
+ `)}var _D=(e,t,r,n,i)=>{let s=t,o=0;for(let a=r;a<n;a++){let c=e[a];if(s=s-c.length,o++,s<=i)break}return{lineCount:s,removals:o}},kD=e=>{let{cursor:t,options:r,style:n}=e,i=e.output??process.stdout,s=Bo(i),o=e.columnPadding??0,a=e.rowPadding??4,c=s-o,l=Ld(i),d=R.default.dim("..."),u=e.maxItems??Number.POSITIVE_INFINITY,h=Math.max(l-a,0),m=Math.max(Math.min(u,h),5),p=0;t>=m-3&&(p=Math.max(Math.min(t-m+3,r.length-m),0));let f=m<r.length&&p>0,g=m<r.length&&p+m<r.length,y=Math.min(p+m,r.length),w=[],b=0;f&&b++,g&&b++;let $=p+(f?1:0),S=y-(g?1:0);for(let k=$;k<S;k++){let _=Kd(n(r[k],k===t),c,{hard:!0,trim:!1}).split(`
175
+ `);w.push(_),b+=_.length}if(b>h){let k=0,_=0,q=b,Q=t-$,re=(te,Jt)=>_D(w,q,te,Jt,h);f?({lineCount:q,removals:k}=re(0,Q),q>h&&({lineCount:q,removals:_}=re(Q+1,w.length))):({lineCount:q,removals:_}=re(Q+1,w.length),q>h&&({lineCount:q,removals:k}=re(0,Q))),k>0&&(f=!0,w.splice(0,k)),_>0&&(g=!0,w.splice(w.length-_,_))}let I=[];f&&I.push(d);for(let k of w)for(let _ of k)I.push(_);return g&&I.push(d),I};var Nw=(e="",t)=>{(t?.output??process.stdout).write(`${R.default.gray(Ii)} ${R.default.red(e)}
176
+
177
+ `)},qw=(e="",t)=>{(t?.output??process.stdout).write(`${R.default.gray(nD)} ${e}
178
+ `)},Mw=(e="",t)=>{(t?.output??process.stdout).write(`${R.default.gray(ae)}
179
+ ${R.default.gray(Ii)} ${e}
180
+
181
+ `)};var $D=e=>R.default.dim(e),ED=(e,t,r)=>{let n={hard:!0,trim:!1},i=Kd(e,t,n).split(`
182
+ `),s=i.reduce((c,l)=>Math.max(at(l),c),0),o=i.map(r).reduce((c,l)=>Math.max(at(l),c),0),a=t-(o-s);return Kd(e,a,n)},Lw=(e="",t="",r)=>{let n=r?.output??Me.stdout,i=(r?.withGuide??Ut.withGuide)!==!1,s=r?.format??$D,o=["",...ED(e,Bo(n)-6,s).split(`
183
+ `).map(s),""],a=at(t),c=Math.max(o.reduce((h,m)=>{let p=at(m);return p>h?p:h},0),a)+2,l=o.map(h=>`${R.default.gray(ae)} ${h}${" ".repeat(c-at(h))}${R.default.gray(ae)}`).join(`
184
+ `),d=i?`${R.default.gray(ae)}
185
+ `:"",u=i?oD:cD;n.write(`${d}${R.default.green(Cw)} ${R.default.reset(t)} ${R.default.gray(Ew.repeat(Math.max(c-a-1,1))+sD)}
186
+ ${l}
187
+ ${R.default.gray(u+Ew.repeat(c+2)+aD)}
188
+ `)};var jM=R.default.magenta;var NM={light:W("\u2500","-"),heavy:W("\u2501","="),block:W("\u2588","#")};var zo=(e,t)=>e.includes(`
189
+ `)?e.split(`
190
+ `).map(r=>t(r)).join(`
191
+ `):t(e),Fw=e=>{let t=(r,n)=>{let i=r.label??String(r.value);switch(n){case"disabled":return`${R.default.gray($w)} ${zo(i,R.default.gray)}${r.hint?` ${R.default.dim(`(${r.hint??"disabled"})`)}`:""}`;case"selected":return`${zo(i,R.default.dim)}`;case"active":return`${R.default.green(iD)} ${i}${r.hint?` ${R.default.dim(`(${r.hint})`)}`:""}`;case"cancelled":return`${zo(i,s=>R.default.strikethrough(R.default.dim(s)))}`;default:return`${R.default.dim($w)} ${zo(i,R.default.dim)}`}};return new Lo({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let r=`${Tw(this.state)} `,n=`${lD(this.state)} `,i=Ko(e.output,e.message,n,r),s=`${R.default.gray(ae)}
192
+ ${i}
193
+ `;switch(this.state){case"submit":{let o=`${R.default.gray(ae)} `,a=Ko(e.output,t(this.options[this.cursor],"selected"),o);return`${s}${a}`}case"cancel":{let o=`${R.default.gray(ae)} `,a=Ko(e.output,t(this.options[this.cursor],"cancelled"),o);return`${s}${a}
194
+ ${R.default.gray(ae)}`}default:{let o=`${R.default.cyan(ae)} `,a=s.split(`
195
+ `).length;return`${s}${o}${kD({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:o.length,rowPadding:a+2,style:(c,l)=>t(c,c.disabled?"disabled":l?"active":"inactive")}).join(`
196
+ ${o}`)}
197
+ ${R.default.cyan(Ii)}
198
+ `}}}}).prompt()};var qM=`${R.default.gray(ae)} `;var Vw=e=>new Fo({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=(e?.withGuide??Ut.withGuide)!==!1,r=`${`${t?`${R.default.gray(ae)}
199
+ `:""}${Tw(this.state)} `}${e.message}
200
+ `,n=e.placeholder?R.default.inverse(e.placeholder[0])+R.default.dim(e.placeholder.slice(1)):R.default.inverse(R.default.hidden("_")),i=this.userInput?this.userInputWithCursor:n,s=this.value??"";switch(this.state){case"error":{let o=this.error?` ${R.default.yellow(this.error)}`:"",a=t?`${R.default.yellow(ae)} `:"",c=t?R.default.yellow(Ii):"";return`${r.trim()}
201
+ ${a}${i}
202
+ ${c}${o}
203
+ `}case"submit":{let o=s?` ${R.default.dim(s)}`:"",a=t?R.default.gray(ae):"";return`${r}${a}${o}`}case"cancel":{let o=s?` ${R.default.strikethrough(R.default.dim(s))}`:"",a=t?R.default.gray(ae):"";return`${r}${a}${o}${s.trim()?`
204
+ ${a}`:""}`}default:{let o=t?`${R.default.cyan(ae)} `:"",a=t?R.default.cyan(Ii):"";return`${r}${o}${i}
205
+ ${a}
206
+ `}}}}).prompt();var Jo=Ve(Mr(),1);import{existsSync as ID,readFileSync as PD}from"node:fs";import{mkdir as RD,rename as AD,unlink as CD,writeFile as TD}from"node:fs/promises";import{join as Bw}from"node:path";var DD=/^[A-Za-z0-9][A-Za-z0-9._/-]*(?::[A-Za-z0-9][A-Za-z0-9._/-]*)?$/,OD=[{stage:"design",risk:"medium",ambiguity:"medium"},{stage:"discover",risk:"medium",ambiguity:"medium"},{stage:"plan",risk:"medium",ambiguity:"medium"},{stage:"debug",risk:"medium",ambiguity:"medium"},{stage:"review",risk:"medium",ambiguity:"medium"}];async function Hd(e={}){if(!e.prompts&&(!process.stdin.isTTY||!process.stdout.isTTY))throw new Error("init requires an interactive terminal.");let t=e.prompts??MD(),r=e.cwd??process.cwd(),n=Bw(r,".codex"),i=Bw(n,"dev-flow.yaml"),s=ID(i),o=s?LD(i):{},a=jD(o);t.intro("Dev Flow \xB7 project setup"),t.note(`Configure workflow isolation, subscription-aware routing, quota safeguards, and optional integrations.
207
+ No model choice is required: Dev Flow assigns models and reasoning automatically.`,"What this wizard does");try{for(a=await Kw(t,a),a=await Uw(t,a),a=await Gw(t,a);;){let c=xD(o,a);Co(c,"init"),t.note(ND(i,a),"Configuration summary"),t.note(qD(a.plan,"normal"),`Automatic routing \xB7 ${ir}`);let l=await Pi(t,t.select({message:s?"Review complete. What should Dev Flow do?":"Configuration ready. What should Dev Flow do?",initialValue:"write",choices:[{value:"write",label:s?"Update configuration":"Create configuration",hint:i},{value:"workflow",label:"Edit workflow behavior",hint:"Worktree isolation"},{value:"subscription",label:"Edit subscription and quota",hint:"Plan and pressure thresholds"},{value:"integrations",label:"Edit integrations",hint:"External plugin and skill allowlists"},{value:"cancel",label:"Cancel",hint:"Leave existing files unchanged"}]}));if(l==="workflow"){a=await Kw(t,a);continue}if(l==="subscription"){a=await Uw(t,a);continue}if(l==="integrations"){a=await Gw(t,a);continue}if(l==="cancel")return Qw(t,i);let d=(0,Jo.stringify)(c,{lineWidth:0});await RD(n,{recursive:!0});let u=`${i}.tmp-${process.pid}-${Date.now()}`;try{await TD(u,d,{encoding:"utf8",mode:384}),await AD(u,i)}catch(h){throw await CD(u).catch(()=>{}),h}return t.outro(`Configuration ${s?"updated":"created"}: ${i}`),{command:"init",status:s?"updated":"created",data:{path:i,config:c}}}}catch(c){if(c instanceof Qo)return Qw(t,i);throw c}}function Zw(e,t="normal"){let r=e==="auto"?"unknown":e,n=["gpt-5.6-luna","gpt-5.6-terra","gpt-5.6-sol"].map(i=>({id:i,supportedReasoningEfforts:[...nr]}));return OD.map(i=>Gn({schemaVersion:1,capturedAt:"preview",plan:r,account:{},quota:{pressure:t,source:"unknown"},models:n,warnings:[],provenance:{plan:e==="auto"?"unknown":"config",quota:"unknown",models:"model/list"}},i))}async function Kw(e,t){e.note("Choose how Dev Flow isolates changes.","1/3 \xB7 Workflow behavior");let r=await Pi(e,e.select({message:"How should isolated Git worktrees be used?",initialValue:t.worktreeMode,choices:[{value:"auto",label:"Automatic (recommended)",hint:"Require isolation only when workflow risk needs it"},{value:"required",label:"Always required",hint:"Every applicable change runs in an isolated worktree"}]}));return{...t,worktreeMode:r}}async function Uw(e,t){e.note("Your plan controls available routing depth. Dev Flow still chooses each model by skill, workflow risk, and initial quota pressure.","2/3 \xB7 Subscription and quota");let r=await Pi(e,e.select({message:"Which Codex subscription capacity should this project use?",initialValue:t.plan,choices:[{value:"auto",label:"Detect automatically (recommended)",hint:"Read account plan once at workflow start; unknown uses Plus baseline"},{value:"plus",label:"Codex Plus",hint:"1x capacity \xB7 conservative routing depth"},{value:"pro_5x",label:"Codex Pro 5x",hint:"5x capacity \xB7 deeper reasoning on high-leverage skills"},{value:"pro_20x",label:"Codex Pro 20x",hint:"20x capacity \xB7 deepest default routing"}]})),n=t.warningPercent,i=t.criticalPercent;for(;n=await Hw(e,"When should quota pressure become a warning?",n,"Example: 50 means 50% of the five-hour window used"),i=await Hw(e,"When should quota pressure become critical?",i,"Example: 80 means 80% of the five-hour window used"),!(n<i);)e.note("Warning threshold must be lower than critical threshold. Please enter both values again.","Invalid quota thresholds");return{...t,plan:r,warningPercent:n,criticalPercent:i}}async function Gw(e,t){e.note(`Optional allowlists restrict external capabilities Dev Flow may use. Leave empty for none.
208
+ Examples: impeccable, context-mode:ctx-search`,"3/3 \xB7 External integrations");let r=await zw(e,"Allowed external plugin IDs",t.plugins,"impeccable, context-mode"),n=await zw(e,"Allowed external skill IDs",t.skills,"impeccable:frontend-design");return{...t,plugins:r,skills:n}}function xD(e,t){let r=Gt(e.worktree),n=Gt(e.subscription),i=Gt(n.quota),s=Gt(e.integrations);return{...e,schemaVersion:1,worktree:{...r,mode:t.worktreeMode},merge:"never",subscription:{...n,plan:t.plan,quota:{...i,warningPercent:t.warningPercent,criticalPercent:t.criticalPercent,unknownPolicy:"conservative"}},integrations:{...s,plugins:t.plugins,skills:t.skills}}}function jD(e){let t=Gt(e.worktree),r=Gt(e.subscription),n=Gt(r.quota),i=Gt(e.integrations);return{worktreeMode:Jw(t.mode,["auto","required"],"auto"),plan:Jw(r.plan,["auto","plus","pro_5x","pro_20x"],"auto"),warningPercent:Yw(n.warningPercent,50),criticalPercent:Yw(n.criticalPercent,80),plugins:Xw(i.plugins),skills:Xw(i.skills)}}function ND(e,t){return[`Target: ${e}`,`Worktrees: ${t.worktreeMode}`,`Subscription: ${t.plan==="auto"?"automatic (Plus if unknown)":t.plan}`,`Quota pressure: warning ${t.warningPercent}% \xB7 critical ${t.criticalPercent}%`,`Plugins: ${t.plugins.join(", ")||"none"}`,`Skills: ${t.skills.join(", ")||"none"}`,`Model costs: Luna ${Un["gpt-5.6-luna"]}x \xB7 Terra ${Un["gpt-5.6-terra"]}x \xB7 Sol ${Un["gpt-5.6-sol"]}x`].join(`
209
+ `)}function qD(e,t){let r={design:"Design",discover:"Discover",plan:"Plan",review:"Review",debug:"Debug root cause"},n=Zw(e,t).map(i=>`${r[i.stage]}: ${i.model??"unavailable"} \xB7 ${i.effort??"unavailable"}`);return[`Baseline: ${e==="auto"?"Plus until account detection":e} \xB7 ${t} quota`,...n,"Live availability is captured once when a Dev Flow workflow starts; exact unavailable routes block instead of falling back."].join(`
210
+ `)}async function Hw(e,t,r,n){let i=await Pi(e,e.text({message:t,defaultValue:String(r),placeholder:n,validate:s=>{let o=Number(s);return Number.isFinite(o)&&o>=0&&o<=100?void 0:"Enter a number from 0 to 100."}}));return Number(i)}async function zw(e,t,r,n){let i=await Pi(e,e.text({message:t,defaultValue:r.join(", "),placeholder:n,validate:s=>{let o=Ww(s).find(a=>!DD.test(a));return o?`Invalid integration identifier: ${o}`:void 0}}));return Ww(i)}function Ww(e){return[...new Set(e.split(",").map(t=>t.trim()).filter(Boolean))]}async function Pi(e,t){let r=await t;if(typeof r=="symbol")throw new Qo;return r}function Qw(e,t){return e.cancel("Initialization cancelled. No files changed."),{command:"init",status:"cancelled",data:{path:t}}}function MD(){return{intro:qw,outro:Mw,note:Lw,cancel:Nw,select:e=>{let t=e.choices.map(r=>({value:r.value,label:r.label,...r.hint?{hint:r.hint}:{}}));return Fw({message:e.message,options:t,initialValue:e.initialValue})},text:e=>Vw({message:e.message,...e.placeholder!==void 0?{placeholder:e.placeholder}:{},...e.defaultValue!==void 0?{defaultValue:e.defaultValue}:{},...e.validate?{validate:t=>e.validate?.(t??"")}:{}})}}function LD(e){let t=(0,Jo.parse)(PD(e,"utf8"));if(!eb(t))throw new Error(`Invalid configuration at ${e}: root must be an object.`);return t}function Gt(e){return eb(e)?e:{}}function Jw(e,t,r){return typeof e=="string"&&t.includes(e)?e:r}function Yw(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}function Xw(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function eb(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Qo=class extends Error{};var Ci=Ve(Mr(),1);import{createHash as FD,randomUUID as VD}from"node:crypto";import{constants as wr,lstatSync as BD,realpathSync as KD}from"node:fs";import*as B from"node:fs/promises";import{isAbsolute as rb,join as Pe,relative as nb,resolve as sn,sep as ib,win32 as UD}from"node:path";var sb=Pe(".codex","dev-flow.project.yaml"),ob=Pe(".codex","dev-flow.project.local.yaml"),Yo="/.codex/dev-flow.project.local.yaml",GD=Pe(".codex","dev-flow","diagrams"),ab=Pe(".codex","project-init","state.yaml"),cb=["stack","source_structure","architecture","dependency_direction","naming","error_handling","testing","quality"],HD=["frontend","api","data","security","concurrency","performance","compatibility","migration","observability","deployment","rollback","operations"],E=class extends Error{constructor(r,n){super(n);this.code=r;this.name="ProjectProfileError",this.exitCode=r==="profile_revision_conflict"||r==="profile_no_change"||r==="profile_session_conflict"?Ae.STATE_CONFLICT:r==="profile_write_failed"||r==="profile_read_failed"?Ae.INTERNAL_ERROR:Ae.INVALID_CONFIGURATION}code;exitCode};function Wd(e){hb(e,"Project profile proposal must be an object.");let t=new Set(["schemaVersion","profileId","revision","contentDigest","content"]);if(Object.keys(e).some(i=>!t.has(i)))throw new E("profile_invalid","Project profile proposal contains unsupported fields or an approval receipt.");if(e.schemaVersion!==1)throw new E("profile_schema_incompatible","Project profile schemaVersion must be 1.");let r=ea(e.content),n=yt({schemaVersion:1,profileId:e.profileId,revision:e.revision,contentDigest:r,content:e.content});if(db(n,!1),e.contentDigest!==void 0&&e.contentDigest!==r)throw new E("profile_digest_mismatch","Project profile proposal contentDigest does not match canonical content.");return n}function lb(e,t=new Date().toISOString()){let r=Wd(e);Xd(t,"Profile approval timestamp is invalid.");let n={schemaVersion:1,actor:"user",approvedAt:t,profileId:r.profileId,revision:r.revision,contentDigest:r.contentDigest},i={...r,approval:{...n,receiptDigest:ea(n)}};return Qd(i),i}function Qd(e){db(e,!0);let t=yt(e);if(t.contentDigest!==ea(t.content))throw new E("profile_digest_mismatch","Project profile content digest is invalid.");let{receiptDigest:r,...n}=t.approval;if(t.approval.profileId!==t.profileId||t.approval.revision!==t.revision||t.approval.contentDigest!==t.contentDigest||r!==ea(n))throw new E("profile_receipt_invalid","Project profile approval receipt is not bound to current content.");return t}function Ai(e,t){let r=nn("project-profile-local",e);if(!r.valid)throw ef("Local project profile",r.errors);let n=yt(e);if(Zd(n))throw new E("profile_invalid","Local project profile contains secret-like data.");br(n.servicePaths.map(({serviceId:i})=>i),"Local service IDs"),br(n.preferences.map(({key:i})=>i),"Local preference keys");for(let i of n.servicePaths)if(!pb(i.path))throw new E("profile_invalid",`Local service path for ${i.serviceId} must be absolute.`);if(t){if(n.profileId!==t.profileId)throw new E("profile_local_conflict","Local profile identity differs from shared profile.");if(n.sharedContentDigest&&n.sharedContentDigest!==t.contentDigest)throw new E("profile_local_conflict","Local profile is bound to a different shared content digest.");let i=new Set(t.content.topology.services.map(({id:o})=>o));for(let o of n.servicePaths)if(!i.has(o.serviceId))throw new E("profile_local_conflict",`Local path references unknown service ${o.serviceId}.`);let s=new Set(t.content.decisions.map(({key:o})=>o));for(let o of n.preferences)if(s.has(o.key))throw new E("profile_local_conflict",`Local preference ${o.key} cannot override shared decision.`)}return n}function Sr(e){return(0,Ci.stringify)(yt(e),{lineWidth:0})}function ub(e){return(0,Ci.stringify)(yt(Xo(e)),{lineWidth:0})}function zD(e,t){let r=new Set,n=new Set;for(let o of e.content.decisions)for(let a of o.sourceFingerprints){let c=t[a.sourceRef];c===void 0?n.add(a.sourceRef):c!==a.value&&r.add(o.key)}let i=!1;for(let o of e.content.domainDocumentation?.sourceFingerprints??[]){let a=t[o.sourceRef];a===void 0?n.add(o.sourceRef):a!==o.value&&(i=!0)}let s=QD(e.content.decisions,r);return{staleDecisionKeys:[...r].toSorted(),invalidatedDecisionKeys:[...s].toSorted(),missingSourceRefs:[...n].toSorted(),...e.content.domainDocumentation?{domainDocumentationStale:i}:{},current:r.size===0&&n.size===0&&!i}}function Jd(e,t){if(!e)return{addedDecisionKeys:t.content.decisions.map(({key:a})=>a).toSorted(),changedDecisionKeys:[],removedDecisionKeys:[],topologyChanged:!0,stackChanged:!0,domainDocumentationChanged:!!t.content.domainDocumentation};let r=new Map(e.content.decisions.map(a=>[a.key,a])),n=new Map(t.content.decisions.map(a=>[a.key,a])),i=[...n.keys()].filter(a=>!r.has(a)).toSorted(),s=[...r.keys()].filter(a=>!n.has(a)).toSorted(),o=[...n.keys()].filter(a=>r.has(a)&&Xe(r.get(a))!==Xe(n.get(a))).toSorted();return{addedDecisionKeys:i,changedDecisionKeys:o,removedDecisionKeys:s,topologyChanged:Xe(e.content.topology)!==Xe(t.content.topology),stackChanged:Xe(e.content.stack)!==Xe(t.content.stack),domainDocumentationChanged:Xe(e.content.domainDocumentation)!==Xe(t.content.domainDocumentation)}}function ta(e,t){let r=new Set(e.content.diagramRefs),n=new Map;for(let i of t){if(!r.has(i.path)||n.has(i.path)||!i.content||i.content.length>262144||i.content.includes("\0")||!/```mermaid\s/u.test(i.content))throw new E("profile_projection_invalid","Project diagram projections must match profile diagramRefs exactly.");n.set(i.path,i.content)}if(r.size!==n.size)throw new E("profile_projection_invalid","Every project diagram ref requires one projection payload.");return[...n].map(([i,s])=>({path:i,content:s}))}function Xo(e){let t=nn("project-init-state",e);if(!t.valid)throw ef("Project INIT state",t.errors);let r=yt(e);Xd(r.updatedAt,"Project INIT state timestamp is invalid."),br(r.decisions.map(({key:i})=>i),"Project INIT decision keys");let n=new Set(r.decisions.map(({key:i})=>i));for(let i of r.decisions)for(let s of i.dependsOn)if(!n.has(s)||s===i.key)throw new E("profile_invalid",`Project INIT decision ${i.key} has invalid dependency ${s}.`);fb(r.decisions);for(let i of r.staleDecisionKeys)if(!n.has(i))throw new E("profile_invalid",`Project INIT stale decision ${i} is not normalized.`);if(r.activeQuestion){if(br(r.activeQuestion.options.map(({id:i})=>i),"Project INIT question option IDs"),!r.activeQuestion.options.some(({id:i})=>i===r.activeQuestion?.recommendedOptionId))throw new E("profile_invalid","Project INIT recommendation must reference one visible option.");for(let i of r.activeQuestion.parentDecisionKeys)if(!n.has(i))throw new E("profile_invalid",`Project INIT question parent ${i} is not normalized.`)}if(Zd(r))throw new E("profile_invalid","Project INIT state contains secret-like data.");return r}var Zo=class{workspaceRoot;sharedPath;localPath;initStatePath;#e;constructor(t,r={}){try{if(this.workspaceRoot=KD(sn(t)),!BD(this.workspaceRoot).isDirectory())throw new Error("not directory")}catch{throw new E("profile_path_invalid","Project profile workspace root must be an existing directory.")}this.sharedPath=Pe(this.workspaceRoot,sb),this.localPath=Pe(this.workspaceRoot,ob),this.initStatePath=Pe(this.workspaceRoot,ab),this.#e=r.temporaryId??VD}async loadShared(t=!0){let r=await this.#t(this.sharedPath,t);return r===void 0?void 0:Qd(r)}async loadLocal(t=!0){let r=await this.#t(this.localPath,t);if(r!==void 0)return Ai(r,await this.loadShared(!0))}async loadInitState(t=!0){await this.#s(t);let r=await this.#t(this.initStatePath,t);return r===void 0?void 0:Xo(r)}async saveInitState(t){let r=Xo(t),n=await this.loadShared(!0);if(n&&r.profileId!==n.profileId)throw new E("profile_session_conflict","Project INIT session identity differs from shared profile.");let i=await this.loadInitState(!0);if(i){if(r.sessionId!==i.sessionId||r.profileId!==i.profileId||r.revision!==i.revision+1)throw new E("profile_session_conflict","Project INIT state must preserve identity and increment revision by one.")}else if(r.revision!==1)throw new E("profile_session_conflict","Initial Project INIT state revision must be 1.");return await this.#a(),await this.#n(this.initStatePath,ub(r)),r}async clearInitState(){await this.#s(!0);try{let t=await B.lstat(this.initStatePath);if(t.isSymbolicLink()||!t.isFile())throw new E("profile_path_invalid","Project INIT state is symlink or non-file.");return await B.unlink(this.initStatePath),await B.rmdir(sn(this.initStatePath,"..")).catch(()=>{}),!0}catch(t){if(t instanceof E)throw t;if(Ce(t,"ENOENT"))return!1;throw new E("profile_write_failed","Project INIT state could not be cleared.")}}async prepareShared(t){let r=Wd(t),n=await this.loadShared(!0);if(n){if(r.profileId!==n.profileId||r.revision!==n.revision+1)throw new E("profile_revision_conflict","Project profile update must preserve identity and increment revision by one.");if(r.contentDigest===n.contentDigest)throw new E("profile_no_change","Project profile proposal contains no content change.")}else if(r.revision!==1)throw new E("profile_revision_conflict","Initial project profile revision must be 1.");return r}async publishShared(t,r={}){let n=await this.prepareShared(t),i=ta(n,r.projections??[]),s=lb(n,r.approvedAt);return await this.#i(),await Promise.all(i.map(o=>this.#o(o))),await this.#n(this.sharedPath,Sr(s)),s}async publishLocal(t){if(!await this.isLocalIgnored())throw new E("profile_local_not_ignored",`Local profile must be ignored with ${Yo}.`);let r=Ai(t,await this.loadShared(!0));return await this.#i(),await this.#n(this.localPath,Sr(r)),r}async isLocalIgnored(){let t,r;try{if(r=await B.open(Pe(this.workspaceRoot,".gitignore"),wr.O_RDONLY|(wr.O_NOFOLLOW??0)),!(await r.stat()).isFile())throw new E("profile_path_invalid","Repository ignore rules are not a regular file.");t=await r.readFile("utf8")}catch(i){if(i instanceof E)throw i;if(Ce(i,"ENOENT"))return!1;throw new E("profile_read_failed","Repository ignore rules could not be read.")}finally{await r?.close()}let n=new Set([Yo,Yo.slice(1)]);return t.split(/\r?\n/u).map(i=>i.trim()).some(i=>n.has(i))}async#t(t,r){await this.#r(r);let n;try{if(n=await B.open(t,wr.O_RDONLY|(wr.O_NOFOLLOW??0)),!(await n.stat()).isFile())throw new E("profile_path_invalid","Project profile is not a file.");let s=await n.readFile("utf8");try{return(0,Ci.parse)(s)}catch{throw new E("profile_invalid","Project profile is not valid YAML.")}}catch(i){if(i instanceof E)throw i;if(r&&Ce(i,"ENOENT"))return;throw Ce(i,"ENOENT")?new E("profile_not_found","Project profile does not exist."):new E("profile_read_failed","Project profile could not be read.")}finally{await n?.close()}}async#i(){let t=Pe(this.workspaceRoot,".codex");try{await B.mkdir(t,{mode:448})}catch(r){if(!Ce(r,"EEXIST"))throw new E("profile_write_failed","Project profile directory could not be created.")}await this.#r(!1)}async#a(){await this.#i();let t=sn(this.initStatePath,"..");try{await B.mkdir(t,{mode:448})}catch(r){if(!Ce(r,"EEXIST"))throw new E("profile_write_failed","Project INIT state directory could not be created.")}await this.#s(!1)}async#s(t){await this.#r(t);let r=sn(this.initStatePath,".."),n;try{n=await B.lstat(r)}catch(i){if(t&&Ce(i,"ENOENT"))return;throw Ce(i,"ENOENT")?new E("profile_not_found","Project INIT state directory is absent."):new E("profile_read_failed","Project INIT state directory could not be inspected.")}if(n.isSymbolicLink()||!n.isDirectory()||await B.realpath(r)!==r)throw new E("profile_path_invalid","Project INIT state directory is unsafe.")}async#r(t){let r=Pe(this.workspaceRoot,".codex"),n;try{n=await B.lstat(r)}catch(i){if(t&&Ce(i,"ENOENT"))return;throw Ce(i,"ENOENT")?new E("profile_not_found","Project profile directory is absent."):new E("profile_read_failed","Project profile directory could not be inspected.")}if(n.isSymbolicLink()||!n.isDirectory())throw new E("profile_path_invalid","Project profile directory is a symlink or non-directory.");if(await B.realpath(r)!==r)throw new E("profile_path_invalid","Project profile directory resolves outside canonical workspace.")}async#n(t,r){try{let s=await B.lstat(t);if(s.isSymbolicLink()||!s.isFile())throw new E("profile_path_invalid","Project profile destination is symlink or non-file.")}catch(s){if(s instanceof E)throw s;if(!Ce(s,"ENOENT"))throw new E("profile_read_failed","Project profile destination could not be inspected.")}let n=this.#e();tb(n);let i=Pe(Pe(this.workspaceRoot,".codex"),`.profile.${n}.tmp`);try{let s=await B.open(i,wr.O_CREAT|wr.O_EXCL|wr.O_WRONLY,384);try{await s.writeFile(r,"utf8"),await s.sync()}finally{await s.close()}await B.rename(i,t)}catch{throw new E("profile_write_failed","Project profile could not be written atomically.")}finally{await B.unlink(i).catch(()=>{})}}async#o(t){let r=sn(this.workspaceRoot,t.path);XD(this.workspaceRoot,r);let n=sn(r,".."),i=nb(this.workspaceRoot,n),s=this.workspaceRoot;for(let c of i.split(ib).filter(Boolean)){s=Pe(s,c);try{await B.mkdir(s,{mode:448})}catch(d){if(!Ce(d,"EEXIST"))throw new E("profile_write_failed","Project diagram directory could not be created.")}let l=await B.lstat(s);if(l.isSymbolicLink()||!l.isDirectory())throw new E("profile_path_invalid","Project diagram path contains symlink or non-directory.")}try{let c=await B.lstat(r);if(c.isSymbolicLink()||!c.isFile())throw new E("profile_path_invalid","Project diagram destination is symlink or non-file.");if(await B.readFile(r,"utf8")!==t.content)throw new E("profile_projection_invalid","Project diagram projection already exists with different content.");return}catch(c){if(c instanceof E)throw c;if(!Ce(c,"ENOENT"))throw new E("profile_read_failed","Project diagram projection could not be inspected.")}let o=this.#e();tb(o);let a=Pe(n,`.diagram.${o}.tmp`);try{await B.writeFile(a,t.content,{flag:"wx",mode:384}),await B.rename(a,r)}catch{throw new E("profile_write_failed","Project diagram projection could not be published.")}finally{await B.unlink(a).catch(()=>{})}}};function Yd(e,t={}){return new Zo(e,t)}function db(e,t){hb(e,"Project profile must be an object.");let r=!t&&e.approval===void 0?{...e,approval:{schemaVersion:1,actor:"user",approvedAt:"1970-01-01T00:00:00.000Z",profileId:e.profileId,revision:e.revision,contentDigest:e.contentDigest,receiptDigest:"0".repeat(64)}}:e,n=nn("project-profile",r);if(!n.valid)throw ef("Project profile",n.errors);if(t&&e.approval===void 0)throw new E("profile_receipt_invalid","Published project profile requires approval receipt.");let i=e;if(i.content.project.id!==i.profileId)throw new E("profile_invalid","Project content identity must match profileId.");WD(i.content)}function WD(e){br(e.stack.map(({id:i})=>i),"Stack IDs");let t=new Set(e.topology.services.map(({id:i})=>i));if(t.size!==e.topology.services.length)throw new E("profile_invalid","Service IDs must be unique.");if(!t.has(e.topology.rootServiceId))throw new E("profile_invalid","Project topology rootServiceId must reference a declared service.");for(let i of e.topology.services){for(let s of i.dependencies)if(!t.has(s)||s===i.id)throw new E("profile_invalid",`Service ${i.id} has invalid dependency ${s}.`);for(let s of i.sourceRefs)Ri(s);i.profileRef&&zd(i.profileRef,"Service profileRef")}for(let i of e.stack)for(let s of i.sourceRefs)Ri(s);let r=new Set(e.decisions.map(({key:i})=>i));if(r.size!==e.decisions.length)throw new E("profile_invalid","Project decision keys must be unique.");let n=new Set(e.decisions.map(({category:i})=>i));for(let i of cb)if(!n.has(i))throw new E("profile_invalid",`Project profile core category ${i} is missing.`);for(let i of e.decisions){Xd(i.provenance.capturedAt,`Decision ${i.key} timestamp is invalid.`);for(let s of i.provenance.sourceRefs)Ri(s);if(br(i.sourceFingerprints.map(({sourceRef:s})=>s),`Decision ${i.key} fingerprint sources`),i.provenance.kind==="user_asserted"&&i.sourceFingerprints.length)throw new E("profile_invalid",`User-asserted decision ${i.key} cannot carry verified fingerprints.`);for(let s of i.sourceFingerprints)if(Ri(s.sourceRef),!i.provenance.sourceRefs.includes(s.sourceRef))throw new E("profile_invalid",`Decision ${i.key} fingerprint lacks matching provenance source.`);for(let s of i.dependsOn)if(!r.has(s)||s===i.key)throw new E("profile_invalid",`Decision ${i.key} has invalid dependency ${s}.`)}if(JD(e.decisions),e.domainDocumentation){let i=e.domainDocumentation;for(let[s,o]of[["glossaryPath",i.glossaryPath],["rulesPath",i.rulesPath],["adrDirectory",i.adrDirectory],...i.contextMapPath?[["contextMapPath",i.contextMapPath]]:[]])if(zd(o,`Domain documentation ${s}`),o.includes("\\")||o.startsWith("/")||o.split("/").includes(".."))throw new E("profile_invalid",`Domain documentation ${s} must be a portable repository path.`);if(i.contextMode==="multiple"&&!i.contextMapPath)throw new E("profile_invalid","Multiple domain contexts require contextMapPath.");if(![i.language,i.identityConvention,i.linkConvention].every(s=>typeof s=="string"&&s.trim().length>0))throw new E("profile_invalid","Domain documentation conventions are incomplete.");br(i.sourceFingerprints.map(({sourceRef:s})=>s),"Domain documentation fingerprint sources");for(let s of i.sourceFingerprints)Ri(s.sourceRef)}for(let i of e.diagramRefs){if(i.includes("\\"))throw new E("profile_projection_invalid","Project diagram refs must use portable forward slashes.");let s=i.replaceAll("\\","/");if(!s.startsWith(".codex/dev-flow/diagrams/")||!s.endsWith(".md"))throw new E("profile_projection_invalid","Project diagram refs must be Markdown files below .codex/dev-flow/diagrams/.")}if(Zd(e))throw new E("profile_invalid","Project profile contains secret-like data.");if(YD(e))throw new E("profile_invalid","Shared project profile contains local absolute filesystem path.")}function QD(e,t){let r=new Set(t),n=!0;for(;n;){n=!1;for(let i of e)!r.has(i.key)&&i.dependsOn.some(s=>r.has(s))&&(r.add(i.key),n=!0)}return r}function JD(e){fb(e)}function fb(e){let t=new Map(e.map(s=>[s.key,s])),r=new Set,n=new Set,i=s=>{if(r.has(s))throw new E("profile_invalid","Project decision graph contains a cycle.");if(!n.has(s)){r.add(s);for(let o of t.get(s)?.dependsOn??[])i(o);r.delete(s),n.add(s)}};for(let s of t.keys())i(s)}function br(e,t){if(new Set(e).size!==e.length)throw new E("profile_invalid",`${t} must be unique.`)}function Ri(e){zd(e,"Shared source reference")}function zd(e,t){if(pb(e)||/^~[\\/]/u.test(e)||/^\/(?:Users|home|private|var|tmp|opt|Volumes)\//u.test(e))throw new E("profile_invalid",`${t} cannot contain local absolute path.`)}function pb(e){return rb(e)||UD.isAbsolute(e)}function Xd(e,t){if(!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/u.test(e)||!Number.isFinite(Date.parse(e)))throw new E("profile_invalid",t)}function Zd(e){let t=Xe(e);return/\b(?:sk-[A-Za-z0-9_-]{8,}|(?:api[_-]?key|token|password|secret)\s*[:=]\s*\S+)\b/iu.test(t)}function YD(e){let t=Xe(e);return/(?:file:\/\/\/|(?:^|[\s"'(])~[\\/]|(?:^|[\s"'(])\/(?:Users|home|private|tmp|Volumes|var\/folders)\/|(?:^|[\s"'(])[A-Za-z]:[\\/])/iu.test(t)}function ef(e,t){let r=t[0];return new E("profile_invalid",`${e} is invalid at ${r?.instancePath||"/"}: ${r?.message??"schema validation failed"}.`)}function hb(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new E("profile_invalid",t)}function tb(e){if(!e||/[\\/\u0000]/u.test(e))throw new E("profile_path_invalid","Temporary profile ID is invalid.")}function XD(e,t){let r=nb(e,t);if(!r||r===".."||r.startsWith(`..${ib}`)||rb(r))throw new E("profile_path_invalid","Project profile artifact resolves outside workspace.")}function ea(e){return FD("sha256").update(Xe(e)).digest("hex")}function Xe(e){return JSON.stringify(yt(e))}function yt(e){return Array.isArray(e)?e.map(yt):typeof e=="object"&&e!==null?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).toSorted(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,yt(r)])):e}function Ce(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}import{randomUUID as ZD}from"node:crypto";import{mkdir as eO,readFile as tO,rename as rO,rm as nO,writeFile as iO}from"node:fs/promises";import{dirname as sO}from"node:path";var oO=300*60;async function tf(e,t){try{let r=JSON.parse(await tO(e,"utf8"));return!aO(r)||r.resetsAt<=t||r.resetsAt>t+oO?void 0:r}catch{return}}async function rf(e,t){if(t.windowDurationMins!==300||!Number.isFinite(t.resetsAt))throw new Error("Invalid five-hour reset cache value.");let r={schemaVersion:1,...t},n=e+"."+process.pid+"."+ZD()+".tmp";await eO(sO(e),{recursive:!0,mode:448});try{await iO(n,JSON.stringify(r,null,2)+`
211
+ `,{encoding:"utf8",mode:384}),await rO(n,e)}catch(i){throw await nO(n,{force:!0}).catch(()=>{}),i}}function nf(e,t){return!t||e.quota.source==="app-server"?e:{...e,quota:{windowDurationMins:300,resetsAt:t.resetsAt,pressure:"unknown",source:"last-known",...e.quota.observedWindow?{observedWindow:e.quota.observedWindow}:{}},warnings:e.warnings.includes("quota_fallback_last_known")?e.warnings:[...e.warnings,"quota_fallback_last_known"],provenance:{...e.provenance,quota:"last-known-cache"}}}function aO(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return t.schemaVersion===1&&t.windowDurationMins===300&&typeof t.resetsAt=="number"&&Number.isFinite(t.resetsAt)}var Di=Object.freeze(["INTAKE","SHAPE","GATE","BUILD","ASSURE"]),na=Object.freeze(["task_initialized","effective_constraints_valid","intake_complete","intake_reopened","routing_ready","workspace_ready","discovery_sufficient","profile_selected","contract_complete","approval_current","resume_metadata_valid","resume_reconciled","terminal_source_recorded","gate_decision_valid"]),ct={INTAKE:{consumes:["request","constraints","design.product-reopen"],produces:["design.product-baseline","design.glossary-deltas","design.domain-rules","design.question","risk","routing","workspace","freshness.config","freshness.policy"],invalidates:["intake.dependent-decisions","shape.dependency-closure","approvals"]},SHAPE:{consumes:["design.product-baseline","design.glossary-deltas","design.domain-rules","risk","constraints","routing","workspace","shape.state"],produces:["shape.targets","shape.evidence","shape.profile-choice","design.technical-decisions","design.question","shape.contract","shape.projection","freshness.sources"],invalidates:["shape.dependency-closure","approvals","build","assurance"]},GATE:{consumes:["shape.contract","shape.evidence","risk"],produces:["planApproval"],invalidates:["approvals"]},BUILD:{consumes:["shape.contract","approvals","workspace"],produces:[],invalidates:["assurance"]},ASSURE:{consumes:["shape.contract","workspace","issues.active","freshness"],produces:["assurance","issues.active","freshness.commands"],invalidates:["assurance.findings","assurance.evidence","approvals"]}},lt={INTAKE:["task.initialized","intake.checkpoint","advance.rejected","intake.reopened","design.question_recorded","design.answer_recorded","design.invalidated","routing.captured","state.transition"],SHAPE:["discovery.target_recorded","discovery.evidence_recorded","discovery.completed","profile.choice_requested","profile.choice_recorded","design.question_recorded","design.answer_recorded","design.invalidated","contract.projected","projection.reconciliation_requested","evidence.invalidated","shape.checkpoint","state.transition"],GATE:["approval.requested","approval.recorded","approval.invalidated","state.transition"],BUILD:["state.transition"],ASSURE:["issue.recorded","correction.recorded","assurance.issue_resolved","assurance.evidence_recorded","assurance.evidence_invalidated","assurance.human_observation_requested","assure.completed","state.transition"]},C=(...e)=>({guards:e}),Ze={blocked:C("resume_metadata_valid"),cancelled:C("terminal_source_recorded"),failed:C("terminal_source_recorded")},cO={new:{macroPhase:"INTAKE",stable:!1,terminal:!1,capsule:ct.INTAKE,events:lt.INTAKE,transitions:{intaking:C("task_initialized","effective_constraints_valid"),...Ze}},intaking:{macroPhase:"INTAKE",stable:!1,terminal:!1,capsule:ct.INTAKE,events:lt.INTAKE,transitions:{awaiting_intake_decision:C(),discovering:C("intake_complete","routing_ready","workspace_ready"),...Ze}},discovering:{macroPhase:"SHAPE",stable:!1,terminal:!1,capsule:ct.SHAPE,events:lt.SHAPE,transitions:{awaiting_profile_choice:C("discovery_sufficient"),awaiting_shape_decision:C(),awaiting_intake_decision:C(),intaking:C("intake_reopened"),...Ze}},awaiting_shape_decision:{macroPhase:"SHAPE",stable:!1,terminal:!1,capsule:ct.SHAPE,events:lt.SHAPE,transitions:{discovering:C(),planning:C("discovery_sufficient","profile_selected"),awaiting_intake_decision:C(),intaking:C("intake_reopened"),...Ze}},awaiting_profile_choice:{macroPhase:"SHAPE",stable:!1,terminal:!1,capsule:ct.SHAPE,events:lt.SHAPE,transitions:{planning:C("profile_selected"),discovering:C(),intaking:C("intake_reopened"),...Ze}},planning:{macroPhase:"SHAPE",stable:!1,terminal:!1,capsule:ct.SHAPE,events:lt.SHAPE,transitions:{discovering:C(),awaiting_intake_decision:C(),awaiting_approval:C("discovery_sufficient","profile_selected","contract_complete"),intaking:C("intake_reopened"),...Ze}},awaiting_intake_decision:{macroPhase:"INTAKE",stable:!1,terminal:!1,capsule:ct.INTAKE,events:lt.INTAKE,transitions:{intaking:C("intake_reopened"),discovering:C("intake_complete"),planning:C("intake_complete","discovery_sufficient","profile_selected"),...Ze}},awaiting_approval:{macroPhase:"GATE",stable:!1,terminal:!1,capsule:ct.GATE,events:lt.GATE,transitions:{planning:C("gate_decision_valid"),executing:C("gate_decision_valid"),cancelled:C("gate_decision_valid","terminal_source_recorded"),intaking:C("intake_reopened"),blocked:Ze.blocked,failed:Ze.failed}},executing:{macroPhase:"BUILD",stable:!1,terminal:!1,capsule:ct.BUILD,events:lt.BUILD,transitions:{assuring:C(),planning:C(),intaking:C("intake_reopened"),...Ze}},assuring:{macroPhase:"ASSURE",stable:!1,terminal:!1,capsule:ct.ASSURE,events:lt.ASSURE,transitions:{planning:C(),intaking:C("intake_reopened"),...Ze}},blocked:{macroPhase:"resumeTo",stable:!0,terminal:!1,capsule:{consumes:["resume.metadata","freshness"],produces:["resume.reconciliation"],invalidates:[]},events:["task.resumed","state.transition"],transitions:{intaking:C("resume_metadata_valid","resume_reconciled","task_initialized","effective_constraints_valid"),discovering:C("resume_metadata_valid","resume_reconciled","intake_complete","routing_ready","workspace_ready"),awaiting_shape_decision:C("resume_metadata_valid","resume_reconciled"),awaiting_profile_choice:C("resume_metadata_valid","resume_reconciled","discovery_sufficient"),planning:C("resume_metadata_valid","resume_reconciled","discovery_sufficient","profile_selected"),awaiting_intake_decision:C("resume_metadata_valid","resume_reconciled"),awaiting_approval:C("resume_metadata_valid","resume_reconciled","contract_complete"),executing:C("resume_metadata_valid","resume_reconciled","approval_current"),assuring:C("resume_metadata_valid","resume_reconciled"),cancelled:C("terminal_source_recorded"),failed:C("terminal_source_recorded")}},cancelled:{macroPhase:"terminalSource",stable:!0,terminal:!0,transitions:{},capsule:{consumes:["terminal.source","freshness"],produces:["terminal.summary"],invalidates:[]},events:["task.cancelled"]},failed:{macroPhase:"terminalSource",stable:!0,terminal:!0,transitions:{},capsule:{consumes:["terminal.source","issues.active","freshness"],produces:["terminal.summary"],invalidates:[]},events:["task.failed"]}},de=yb(cO),sf=Object.freeze(Object.keys(de));function mb(e,t){return e==="cancelled"||e==="failed"||e==="assuring"&&t}function gb(){return{macroPhases:[...Di],guards:[...na],states:sf.map(e=>{let t=de[e];return{status:e,macroPhase:t.macroPhase,stable:t.stable,terminal:t.terminal,transitions:Object.entries(t.transitions).map(([r,n])=>({target:r,guards:[...n.guards]})),capsule:{consumes:[...t.capsule.consumes],produces:[...t.capsule.produces],invalidates:[...t.capsule.invalidates]},events:[...t.events]}})}}function vt(e){return typeof e=="string"&&Object.hasOwn(de,e)}function wt(e){return ra(e.status,e,new Set)}function ra(e,t,r){if(r.has(e))throw new Error(`Cannot derive macro-phase: recursive source at ${e}.`);r.add(e);let n=de[e].macroPhase;if(n!=="resumeTo"&&n!=="terminalSource")return n;if(n==="resumeTo"){if(!t.resumeTo||!Ti(t.resumeTo))throw new Error(`Cannot derive macro-phase for blocked: invalid resumeTo ${String(t.resumeTo)}.`);return ra(t.resumeTo,t,r)}let i=[...t.history].toReversed().find(o=>lO(o)&&o.type==="state.transition"),s=i?.terminalSource;if(i?.to!==e||!vt(s)||i.from!==s||de[s].terminal)throw new Error(`Cannot derive macro-phase for ${e}: valid terminal source event missing.`);if(s==="blocked"){let o=i.terminalResumeTo;if(!vt(o)||!Ti(o))throw new Error(`Cannot derive macro-phase for ${e}: blocked terminal source lacks operational resumeTo.`);return ra(o,{...t,status:o},r)}return ra(s,{...t,status:s},r)}function Ti(e){return e!=="new"&&!de[e].stable&&!de[e].terminal}function lO(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yb(e){if(typeof e!="object"||e===null||Object.isFrozen(e))return e;for(let t of Object.values(e))yb(t);return Object.freeze(e)}var Fi=Ve(Mr(),1);import{randomUUID as Px}from"node:crypto";import{constants as Gb,lstatSync as Rx,realpathSync as Ax}from"node:fs";import*as Re from"node:fs/promises";import{isAbsolute as Hb,join as ga,relative as zb,resolve as Rf,sep as Wb}from"node:path";import{createHash as zO}from"node:crypto";import{createHash as dO}from"node:crypto";var bb=Object.freeze(["decision","product","terminology","domain_rule","domain_scenario","technical_decision","source","evidence","criterion","task","risk","validation","guide","projection","assurance_subject","assurance_operation"]),vb=/^[A-Za-z0-9][A-Za-z0-9._:/#@+~=-]{0,255}$/,wb=4096,uO=128;function et(e){if(!e||e.schemaVersion!==1||!Array.isArray(e.nodes))throw new Error("Dependency graph must use schemaVersion 1 and contain nodes.");if(e.nodes.length>wb)throw new Error(`Dependency graph exceeds ${wb} nodes.`);let t=new Map;for(let s of e.nodes){if(!s||!vb.test(s.id))throw new Error("Dependency node id is invalid.");if(!bb.includes(s.kind))throw new Error(`Dependency node ${s.id} kind is invalid.`);if(t.has(s.id))throw new Error(`Duplicate dependency node ${s.id}.`);if(!Array.isArray(s.dependsOn)||s.dependsOn.length>uO)throw new Error(`Dependency node ${s.id} dependencies are invalid.`);if(new Set(s.dependsOn).size!==s.dependsOn.length)throw new Error(`Dependency node ${s.id} contains duplicate dependencies.`);if(s.dependsOn.some(o=>!vb.test(o)))throw new Error(`Dependency node ${s.id} contains an invalid dependency id.`);if(s.dependsOn.includes(s.id))throw new Error(`Dependency node ${s.id} cannot depend on itself.`);t.set(s.id,{id:s.id,kind:s.kind,dependsOn:[...s.dependsOn]})}for(let s of t.values())for(let o of s.dependsOn)if(!t.has(o))throw new Error(`Dependency node ${s.id} references unknown dependency ${o}.`);let r=new Set,n=new Set,i=s=>{if(!n.has(s)){if(r.has(s))throw new Error(`Dependency graph contains a cycle at ${s}.`);r.add(s);for(let o of t.get(s)?.dependsOn??[])i(o);r.delete(s),n.add(s)}};for(let s of t.keys())i(s);return{schemaVersion:1,nodes:[...t.values()].toSorted((s,o)=>s.id.localeCompare(o.id))}}function bt(e,t){let r=et(e),n=new Set(r.nodes.map(c=>c.id)),i=[...new Set(t)];for(let c of i)if(!n.has(c))throw new Error(`Dependency closure root ${c} does not exist.`);let s=new Map;for(let c of r.nodes)for(let l of c.dependsOn){let d=s.get(l)??[];d.push(c.id),s.set(l,d)}let o=new Set,a=[...i];for(;a.length;){let c=a.shift();if(!o.has(c)){o.add(c);for(let l of s.get(c)??[])a.push(l)}}return[...o].toSorted()}var fO=/^[A-Za-z0-9][A-Za-z0-9._:/#@+~=-]{0,255}$/,pO=4096,of=512,ia=["objective","users_value","scope","success","risks_constraints"];function cf(){let e={schemaVersion:1,graph:{schemaVersion:1,nodes:ia.map(t=>({id:`product:${t}`,kind:"product",dependsOn:[]}))},productBaseline:{schemaVersion:1,dimensions:ia.map(t=>({key:t,status:"missing",provenance:{sourceRefs:[],freshnessRefs:[]},dependencyNodeId:`product:${t}`}))},glossaryDeltas:[],domainRules:[],decisions:[],invalidations:[],semanticComplete:!1};return Oi(e)}function sa(e){let t=Oi(e);return ut(t),t}function ut(e){if(!e||e.schemaVersion!==1)throw new Error("DesignState schemaVersion must be 1.");let t=et(e.graph);if(e.glossaryDeltas.length>of||e.domainRules.length>of||e.decisions.length>of)throw new Error("DesignState record budget exceeded.");let r=e.productBaseline?.dimensions;if(!Array.isArray(r)||r.length!==ia.length)throw new Error("ProductBaseline requires exactly five dimensions.");let n=r.map(s=>s.key);if(new Set(n).size!==n.length||ia.some(s=>!n.includes(s)))throw new Error("ProductBaseline dimension keys are incomplete or duplicated.");for(let s of r){if(zt(s.dependencyNodeId,"ProductBaseline dependency node"),ff(s.provenance),t.nodes.find(a=>a.id===s.dependencyNodeId)?.kind!=="product")throw new Error(`ProductBaseline ${s.key} requires product dependency node.`);if(s.status==="resolved"&&!Z(s.value))throw new Error(`ProductBaseline ${s.key} resolved without value.`);if(s.status==="not_applicable"&&!Z(s.notApplicableReason))throw new Error(`ProductBaseline ${s.key} N/A requires reason.`);if(["missing","unknown"].includes(s.status)&&(s.value||s.notApplicableReason))throw new Error(`ProductBaseline ${s.key} unresolved payload is invalid.`)}if(df(e.activeQuestion),e.activeQuestion){let s=new Map(t.nodes.map(o=>[o.id,o]));for(let o of[...e.activeQuestion.subjectIds,...e.activeQuestion.prerequisiteIds])if(!s.has(o))throw new Error(`Design question references unknown node ${o}.`);if(e.activeQuestion.owner==="shape"&&e.activeQuestion.subjectIds.some(o=>s.get(o)?.kind!=="technical_decision"))throw new Error("SHAPE design question requires technical-decision subjects.")}vO(t),yO(e,t);for(let s of e.invalidations)if(!Z(s.reason)||Number.isNaN(Date.parse(s.at))||!s.rootIds.length||s.rootIds.some(o=>!t.nodes.some(a=>a.id===o))||s.invalidatedNodeIds.some(o=>!t.nodes.some(a=>a.id===o)))throw new Error("Design invalidation record is invalid.");let i=_b({...e,digest:void 0});if(e.digest!==i)throw new Error("DesignState digest is stale.");return structuredClone(e)}function hO(e,t){ut(e);let r=new Set(e.graph.nodes.map(s=>s.id)),i=t.filter(({question:s,scores:o,scoreReason:a})=>(df(s),wO(o,a),s.subjectIds.length>0&&s.subjectIds.every(c=>r.has(c))&&s.prerequisiteIds.every(c=>r.has(c)&&Sb(e,c))&&s.subjectIds.some(c=>!Sb(e,c)))).toSorted((s,o)=>{let a=Object.values(s.scores).reduce((l,d)=>l+d,0);return Object.values(o.scores).reduce((l,d)=>l+d,0)-a||o.scores.risk-s.scores.risk||o.scores.impact-s.scores.impact||s.question.id.localeCompare(o.question.id)})[0];return i?structuredClone(i.question):void 0}function mO(e,t){if(ut(e),!t.length||new Set(t.map(c=>c.key)).size!==t.length)throw new Error("ProductBaseline resolution set is empty or duplicated.");for(let c of t){if(ff(c.provenance),c.status==="resolved"&&!Z(c.value))throw new Error(`ProductBaseline ${c.key} resolved without value.`);if(c.status==="not_applicable"&&!Z(c.notApplicableReason))throw new Error(`ProductBaseline ${c.key} N/A requires reason.`)}let r=new Map(t.map(c=>[c.key,c])),n=e.productBaseline.dimensions.map(c=>{let l=r.get(c.key);return l?{key:c.key,status:l.status,...l.value?{value:l.value.trim()}:{},...l.notApplicableReason?{notApplicableReason:l.notApplicableReason.trim()}:{},provenance:structuredClone(l.provenance),dependencyNodeId:c.dependencyNodeId}:c}),i=new Set(t.map(c=>`product:${c.key}`)),s=e.activeQuestion&&!e.activeQuestion.subjectIds.some(c=>i.has(c)),{activeQuestion:o,...a}=e;return Oi({...a,productBaseline:{schemaVersion:1,dimensions:n},...s?{activeQuestion:e.activeQuestion}:{},semanticComplete:!1})}function gO(e,t){if(ut(e),e.activeQuestion)throw new Error("Only one ActiveDesignQuestion may exist.");df(t);let r=new Set(e.graph.nodes.map(n=>n.id));for(let n of[...t.subjectIds,...t.prerequisiteIds])if(!r.has(n))throw new Error(`Design question references unknown node ${n}.`);return Oi({...e,activeQuestion:structuredClone(t),semanticComplete:!1})}function lf(e,t,r,n=new Date().toISOString()){if(ut(e),!Z(r))throw new Error("Design invalidation requires reason.");let i=bt(e.graph,t),s=new Set(i),{activeQuestion:o,...a}=e,c=o&&!o.subjectIds.some(l=>s.has(l));return Oi({...a,productBaseline:{schemaVersion:1,dimensions:e.productBaseline.dimensions.map(l=>s.has(l.dependencyNodeId)?{key:l.key,status:"unknown",provenance:l.provenance,dependencyNodeId:l.dependencyNodeId}:l)},glossaryDeltas:e.glossaryDeltas.map(l=>s.has(l.dependencyNodeId)?{...l,status:"invalidated"}:l),domainRules:e.domainRules.map(l=>s.has(l.dependencyNodeId)?{...l,status:"invalidated"}:l),decisions:e.decisions.map(l=>s.has(l.dependencyNodeId)?{...l,status:"invalidated"}:l),...c?{activeQuestion:o}:{},invalidations:[...e.invalidations,{rootIds:[...new Set(t)].toSorted(),invalidatedNodeIds:i,reason:r,at:n}].slice(-128),semanticComplete:!1})}function uf(e){return ut(e),e.semanticComplete&&!e.activeQuestion&&e.productBaseline.dimensions.every(t=>["resolved","not_applicable"].includes(t.status))&&[...e.glossaryDeltas,...e.domainRules,...e.decisions].every(t=>t.status!=="proposed"&&t.status!=="invalidated")}function yO(e,t){let r=new Set(t.nodes.map(i=>i.id)),n=new Set;for(let i of[...e.glossaryDeltas,...e.domainRules,...e.decisions]){if(zt(i.id,"Design record"),zt(i.dependencyNodeId,"Design dependency node"),n.has(i.id))throw new Error(`Duplicate design record ${i.id}.`);if(n.add(i.id),!r.has(i.dependencyNodeId))throw new Error(`Design record ${i.id} references unknown dependency node.`)}for(let i of[...e.glossaryDeltas,...e.domainRules])if(ff(i.provenance),["approved","projected"].includes(i.status)&&!i.disposition)throw new Error(`Durable design record ${i.id} requires disposition.`);for(let i of e.glossaryDeltas)if(!Z(i.context)||!Z(i.term)||!Z(i.definition)||!Ht(i.aliases,!0)||!Ht(i.relatedTermIds,!0)||i.rejectedTerms.some(s=>!Z(s.term)||!Z(s.reason))||t.nodes.find(s=>s.id===i.dependencyNodeId)?.kind!=="terminology")throw new Error(`Glossary delta ${i.id} is malformed.`);for(let i of e.domainRules){let s=new Set(i.scenarios.map(o=>o.angle));if(!Z(i.context)||!Ht(i.termIds)||!Ht(i.actors)||!Ht(i.conditions,!0)||!Z(i.outcome)||!Ht(i.exceptions,!0)||!i.scenarios.length||!s.has("nominal")||![...s].some(o=>o!=="nominal")||new Set(i.scenarios.map(o=>o.id)).size!==i.scenarios.length||t.nodes.find(o=>o.id===i.dependencyNodeId)?.kind!=="domain_rule")throw new Error(`Domain rule ${i.id} lacks valid stress scenarios.`);for(let o of i.scenarios)if(zt(o.id,"Domain scenario"),!Z(o.startingSituation)||!Z(o.action)||!Z(o.expectedResult))throw new Error(`Domain scenario ${o.id} is malformed.`)}for(let i of e.decisions){if(!Z(i.context)||!Z(i.materialityReason)||i.alternatives.length<2||i.alternatives.length>8||new Set(i.alternatives.map(o=>o.id)).size!==i.alternatives.length||!Ht(i.evidenceRefs))throw new Error(`Decision ${i.id} alternatives are invalid.`);for(let o of i.alternatives)if(zt(o.id,"Decision alternative"),!Z(o.label)||!Ht(o.consequences)||o.excludedReason!==void 0&&!Z(o.excludedReason))throw new Error(`Decision ${i.id} alternative is malformed.`);if(i.selectedOptionId&&!i.alternatives.some(o=>o.id===i.selectedOptionId))throw new Error(`Decision ${i.id} selected option is unknown.`);if(["resolved","approved","projected"].includes(i.status)&&!i.selectedOptionId)throw new Error(`Resolved decision ${i.id} lacks explicit selection.`);let s=i.owner==="shape"?"technical_decision":"decision";if(t.nodes.find(o=>o.id===i.dependencyNodeId)?.kind!==s)throw new Error(`Decision ${i.id} dependency ownership is invalid.`)}}function Ht(e,t=!1){return Array.isArray(e)&&(t||e.length>0)&&new Set(e).size===e.length&&e.every(Z)}function vO(e){let t=new Map(e.nodes.map(n=>[n.id,n])),r=new Set(["product","terminology","domain_rule","domain_scenario"]);for(let n of e.nodes)if(r.has(n.kind)){for(let i of n.dependsOn)if(t.get(i)?.kind==="technical_decision")throw new Error(`INTAKE node ${n.id} cannot depend on SHAPE technical decision.`)}}function Sb(e,t){let r=e.productBaseline.dimensions.find(i=>i.dependencyNodeId===t);if(r)return r.status==="resolved"||r.status==="not_applicable";let n=[...e.glossaryDeltas,...e.domainRules,...e.decisions].find(i=>i.dependencyNodeId===t);return!!(n&&["resolved","approved","projected"].includes(n.status))}function wO(e,t){if(!Z(t)||Object.values(e).some(r=>!Number.isInteger(r)||r<0||r>5))throw new Error("Design frontier score is invalid.")}function df(e){if(e){if(zt(e.id,"Design question"),zt(e.decisionKey,"Design decision"),!Z(e.prompt)||!Z(e.selectionReason))throw new Error("Design question prompt and selection reason are required.");if(e.owner==="intake"&&e.kind==="technical")throw new Error("Technical question belongs to SHAPE.");if(e.owner==="shape"&&e.kind!=="technical")throw new Error("Product/domain questions belong to INTAKE.");if(e.options&&(e.options.length<2||e.options.length>3))throw new Error("Design question requires two or three options.");if(e.recommendedOptionId&&!e.options?.some(t=>t.id===e.recommendedOptionId))throw new Error("Design question recommendation is unknown.");if(!["choice","elicitation"].includes(e.mode)||e.mode==="choice"!=!!e.options||!e.freeFormAllowed||!Number.isInteger(e.clarificationCount)||e.clarificationCount<0||!Array.isArray(e.directConsequences)||e.directConsequences.some(t=>!Z(t)))throw new Error("Design question interaction contract is invalid.")}}function ff(e){if(!e||!Array.isArray(e.sourceRefs)||!Array.isArray(e.freshnessRefs))throw new Error("Design provenance is invalid.");for(let t of[...e.sourceRefs,...e.freshnessRefs])zt(t,"Provenance")}function zt(e,t){if(!fO.test(e))throw new Error(`${t} id is invalid.`)}function Z(e){return typeof e=="string"&&e.trim().length>0&&e.length<=pO}function Oi(e){let t={...structuredClone(e),digest:void 0};return{...t,digest:_b(t)}}function _b(e){return`sha256:${dO("sha256").update(af(e)).digest("hex")}`}function af(e){return Array.isArray(e)?`[${e.map(af).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,t])=>t!==void 0).toSorted(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${af(r)}`).join(",")}}`:JSON.stringify(e)}import{createHash as SO}from"node:crypto";var St=/^[^\r\n\u0000]{1,1024}$/;function kb(e,t,r=new Date().toISOString()){$b(e);let n=typeof t=="string"?{value:t}:t;if(!n||n.value!==e.value||e.kind==="command"&&n.inputDigest!==e.inputDigest)return!1;if(e.kind==="external"&&e.expiresAt!==void 0){let i=Date.parse(r),s=Date.parse(e.expiresAt);if(!Number.isFinite(i)||!Number.isFinite(s))throw new Error("Freshness timestamp is invalid.");if(i>=s)return!1}return!0}function xi(e){let t=et(e.graph),r=new Map;for(let d of e.fingerprints){if($b(d),r.has(d.id))throw new Error(`Duplicate source fingerprint ${d.id}.`);r.set(d.id,d)}let n=[...r.values()].filter(d=>{let u=e.observedValues[d.id];return u===void 0||!kb(d,u,e.now)}).map(d=>d.id).toSorted(),i=new Set(n),s=[],o=[],a=new Set,c=new Set,l=new Map(t.nodes.map(d=>[d.id,d]));for(let d of r.values())if(l.get(d.dependencyNodeId)?.kind!=="source")throw new Error(`Source fingerprint ${d.id} requires a source dependency node.`);for(let d of e.evidence){if(bO(d,r,l),c.has(d.id))throw new Error(`Duplicate evidence item ${d.id}.`);if(c.add(d.id),d.sourceFingerprintIds.some(u=>i.has(u))){s.push(d.id),a.add(d.dependencyNodeId);for(let u of d.sourceFingerprintIds.filter(h=>i.has(h)))a.add(r.get(u).dependencyNodeId)}else o.push(d.id)}return{staleFingerprintIds:n,staleEvidenceIds:s.toSorted(),reusedEvidenceIds:o.toSorted(),invalidatedNodeIds:a.size?bt(t,[...a]):[],refreshTargetIds:s.map(d=>`refresh:${d}`).toSorted()}}function $b(e){if(!e||!St.test(e.id)||!St.test(e.value)||!St.test(e.provenanceRef)||!St.test(e.dependencyNodeId))throw new Error("Source fingerprint is malformed.");if(!["git_blob","content","command","external"].includes(e.kind))throw new Error(`Source fingerprint ${e.id} kind is invalid.`);if(e.kind==="command"&&!St.test(e.inputDigest??""))throw new Error(`Command fingerprint ${e.id} requires inputDigest.`);if(e.kind==="external"){if(!e.observedAt||!Number.isFinite(Date.parse(e.observedAt)))throw new Error(`External fingerprint ${e.id} requires observedAt.`);if(e.expiresAt!==void 0&&!Number.isFinite(Date.parse(e.expiresAt)))throw new Error(`External fingerprint ${e.id} expiresAt is invalid.`)}}function bO(e,t,r){if(!e||!St.test(e.id)||!St.test(e.fact)||!St.test(e.dependencyNodeId))throw new Error("Evidence item is malformed.");if(!Array.isArray(e.provenanceRefs)||!e.provenanceRefs.length||e.provenanceRefs.some(n=>!St.test(n)))throw new Error(`Evidence item ${e.id} requires provenance.`);if(!Array.isArray(e.sourceFingerprintIds)||!e.sourceFingerprintIds.length)throw new Error(`Evidence item ${e.id} requires source fingerprints.`);if(e.sourceFingerprintIds.some(n=>!t.has(n)))throw new Error(`Evidence item ${e.id} references unknown source fingerprint.`);if(r.get(e.dependencyNodeId)?.kind!=="evidence")throw new Error(`Evidence item ${e.id} requires an evidence dependency node.`)}var H=/^[^\r\n\u0000]{1,1024}$/,Le=/^[A-Za-z0-9][A-Za-z0-9._:/#@+~=-]{0,255}$/,Ib=new Set(["low","medium","high","critical"]),_O=new Set(["scope","risk","acceptance","plan","validation","profile_recommendation"]),kO=new Set(["architectural_boundary","compatibility_migration","non_obvious_order","security_concurrency_performance","mandatory_repository_pattern","complex_rollback_deployment"]),$O=4096;function hf(e){if(!Ib.has(e.risk)||!H.test(e.productBaselineRef))throw new Error("Shape state requires risk and INTAKE assessment reference.");return Cb(e.budget??{}),{schemaVersion:1,risk:e.risk,productBaselineRef:e.productBaselineRef,discoveryTargets:[],evidence:[],sourceFingerprints:[],technicalDecisions:[],dependencyGraph:{schemaVersion:1,nodes:[]},invalidations:[],budget:{limits:{...e.budget},usage:{reasoningCalls:0,inputTokens:0,outputTokens:0,contextBytes:0},continuations:0},semanticRetryCounts:{discovery:0,planning:0},evaluatorReceipts:[]}}function EO(e,t){if(tt(e),!t||!Array.isArray(t.targets)||!Array.isArray(t.evidence)||!Array.isArray(t.sourceFingerprints)||!Array.isArray(t.dependencyNodes))throw new Error("Discovery evaluation is structurally invalid.");for(let l of t.targets)gf(l);let r=_r(e.discoveryTargets,t.targets),n=_r(e.evidence,t.evidence),i=_r(e.sourceFingerprints,t.sourceFingerprints),s=et({schemaVersion:1,nodes:_r(e.dependencyGraph.nodes,t.dependencyNodes)});if([r.length,n.length,i.length,s.nodes.length].some(l=>l>$O))throw new Error("Discovery evaluation exceeds SHAPE item bounds.");let o=mf({...e,discoveryTargets:r,evidence:n,sourceFingerprints:i,dependencyGraph:s},t.usage??{reasoningCalls:1});yf(o);let c=Ni(o).reasons.filter(l=>l!=="budget_checkpoint");if(t.semanticSufficient&&c.length)throw new Error(`Discovery semantic sufficiency contradicts unresolved targets: ${c.join(", ")}.`);return t.semanticSufficient?o:vf(o)}function Ni(e){tt(e);let t=[],r=e.discoveryTargets.filter(n=>n.status!=="resolved");r.length&&t.push(...r.map(n=>`target:${n.id}:${n.status}`));for(let n of e.discoveryTargets.filter(i=>i.status==="resolved")){n.evidenceIds.length||t.push(`target:${n.id}:missing_evidence`);for(let i of n.evidenceIds)e.evidence.some(s=>s.id===i)||t.push(`target:${n.id}:unknown_evidence:${i}`)}e.discoveryTargets.length||t.push("no_discovery_target"),e.activeTechnicalDecisionId&&t.push("active_technical_decision"),e.budget.checkpoint&&t.push("budget_checkpoint");try{yf(e);let n=Object.fromEntries(e.sourceFingerprints.map(s=>[s.id,s.kind==="command"?{value:s.value,inputDigest:s.inputDigest}:s.value])),i=xi({graph:e.dependencyGraph,fingerprints:e.sourceFingerprints,evidence:e.evidence,observedValues:n});i.staleEvidenceIds.length&&t.push(...i.staleEvidenceIds.map(s=>`stale_evidence:${s}`))}catch(n){t.push(n instanceof Error?n.message:"invalid_evidence")}return{complete:t.length===0,reasons:[...new Set(t)].toSorted()}}function Pb(e){let t=Ni(e);if(!t.complete)throw new Error(`Discovery is incomplete: ${t.reasons.join(", ")}.`);let r=e.discoveryTargets.map(o=>o.id).toSorted(),n=e.evidence.map(o=>o.id).toSorted(),s={schemaVersion:1,evaluator:"discovery",outcome:"discovery_sufficient",inputDigest:Wt({productBaselineRef:e.productBaselineRef,risk:e.risk,discoveryTargets:e.discoveryTargets,evidence:e.evidence,sourceFingerprints:e.sourceFingerprints,dependencyGraph:e.dependencyGraph}),evidenceRefs:n,subjectIds:r,completedIds:r,receiptDigest:""};return s.receiptDigest=Wt({...s,receiptDigest:void 0}),s}function IO(e,t){if(tt(e),e.activeTechnicalDecisionId)throw new Error("Only one Technical Decision may be active.");let r=e.discoveryTargets.find(i=>i.id===t.targetId);if(!r||!["open","blocked","stale"].includes(r.status))throw new Error("Technical Decision requires an unresolved Discovery Target.");if(!Le.test(t.id)||!Le.test(t.decisionKey)||!H.test(t.materialityReason)||!H.test(t.recommendationBasis)||!["low","medium","high"].includes(t.confidence)||!["discovering","planning"].includes(t.priorRole))throw new Error("Technical Decision identity or impact is invalid.");if(e.technicalDecisions.some(i=>i.id===t.id||i.decisionKey===t.decisionKey))throw new Error("Technical Decision identity already exists.");if(t.options.length<2||t.options.length>3||new Set(t.options.map(i=>i.id)).size!==t.options.length)throw new Error("Technical Decision requires two or three distinct options.");for(let i of t.options)if(!Le.test(i.id)||!H.test(i.label)||!H.test(i.impact)||i.excludedReason!==void 0&&!H.test(i.excludedReason))throw new Error("Technical Decision option is invalid.");if(!t.options.some(i=>i.id===t.recommendedOptionId))throw new Error("Technical Decision recommendation must reference an option.");if(!t.evidenceIds.length||t.evidenceIds.some(i=>!e.evidence.some(s=>s.id===i)))throw new Error("Technical Decision requires known technical evidence.");bt(e.dependencyGraph,t.affectedDependencyRootIds);let n={schemaVersion:1,...on(t),status:"active"};return{...vf(e),discoveryTargets:e.discoveryTargets.map(i=>i.id===r.id?{...i,status:"escalated"}:i),technicalDecisions:[...e.technicalDecisions,n],activeTechnicalDecisionId:n.id}}function PO(e,t){tt(e);let r=e.technicalDecisions.find(l=>l.id===t.technicalDecisionId);if(!r||r.status!=="active"||e.activeTechnicalDecisionId!==r.id)throw new Error("Active Technical Decision does not exist.");if(!r.options.some(l=>l.id===t.selectedOptionId)||!H.test(t.evidenceRef))throw new Error("Technical Decision requires explicit selected option and evidence.");let n=bt(e.dependencyGraph,r.affectedDependencyRootIds),i=new Set(n),{activeTechnicalDecisionId:s,...o}=vf(e),a={...o,discoveryTargets:e.discoveryTargets.map(l=>l.id===r.targetId?{...l,status:"stale"}:l),technicalDecisions:e.technicalDecisions.map(l=>l.id===r.id?{...l,status:"resolved",selectedOptionId:t.selectedOptionId,answerEvidenceRef:t.evidenceRef}:l),invalidations:[...e.invalidations,{rootIds:[...r.affectedDependencyRootIds],invalidatedNodeIds:n,reason:`decision:${r.decisionKey}`}],evidence:e.evidence.filter(l=>!i.has(l.dependencyNodeId))},c=a.discoveryTargets.some(l=>["open","stale","blocked"].includes(l.status));return{state:a,resumeRole:c?"discovering":r.priorRole,invalidatedNodeIds:n}}function RO(e,t){if(tt(e),jO(e,t.discoveryReceipt),e.preparationProfileChoice)throw new Error("Preparation profile choice already exists.");if(!["quick","plan"].includes(t.recommendation)||!H.test(t.recommendationBasis))throw new Error("Preparation profile recommendation is invalid.");if(Ab(t.checkpoint),t.preselectedProfile&&!H.test(t.selectionEvidenceRef??""))throw new Error("Preselected preparation profile requires evidence.");if(t.preselectedProfile&&t.preselectedProfile!=="plan")throw new Error("Only explicit durable-plan request or policy may preselect Plan.");let r=t.preselectedProfile;return{...e,evaluatorReceipts:[...e.evaluatorReceipts,on(t.discoveryReceipt)],preparationProfileChoice:{schemaVersion:1,status:r?"selected":"pending",recommendation:t.recommendation,recommendationBasis:t.recommendationBasis,discoveryReceiptDigest:t.discoveryReceipt.receiptDigest,checkpoint:on(t.checkpoint),...r?{selectedProfile:r,selectionEvidenceRef:t.selectionEvidenceRef}:{}}}}function AO(e,t){tt(e);let r=e.preparationProfileChoice;if(!r||r.status!=="pending")throw new Error("Pending preparation profile choice does not exist.");if(!e.evaluatorReceipts.some(n=>n.evaluator==="discovery"&&n.receiptDigest===r.discoveryReceiptDigest))throw new Error("Preparation profile choice is stale because Discovery changed.");if(!["quick","plan"].includes(t.profile)||!H.test(t.evidenceRef))throw new Error("Preparation profile requires explicit profile and evidence.");return{...e,preparationProfileChoice:{...r,status:"selected",selectedProfile:t.profile,selectionEvidenceRef:t.evidenceRef}}}function CO(e,t){tt(e);let r=e.preparationProfileChoice;if(!r||r.status!=="selected"||!r.selectedProfile)throw new Error("Planning requires selected preparation profile.");let n=e.evaluatorReceipts.find(l=>l.evaluator==="discovery");if(!n)throw new Error("Planning requires current Discovery receipt.");if(!t||!Array.isArray(t.dependencyNodes))throw new Error("Planning evaluation is structurally invalid.");let i=et({schemaVersion:1,nodes:_r(e.dependencyGraph.nodes,t.dependencyNodes)}),s=mf({...e,dependencyGraph:i},t.usage??{reasoningCalls:1});if(t.missingEvidenceTarget){if(t.semanticImplementable||t.contract)throw new Error("Missing Planning evidence cannot accompany implementable contract.");if(gf(t.missingEvidenceTarget),t.missingEvidenceTarget.status!=="open"||t.missingEvidenceTarget.evidenceIds.length)throw new Error("Missing Planning evidence must create one open Discovery Target.");return{...Eb(s),discoveryTargets:_r(s.discoveryTargets,[t.missingEvidenceTarget])}}if(!t.contract)throw new Error("Planning evaluation requires contract or missing-evidence target.");if(t.contract.profile!==r.selectedProfile)throw new Error("Planning contract profile does not match selected profile.");let o={...on(t.contract),risk:e.risk,productBaselineRef:e.productBaselineRef,discoveryReceiptDigest:n.receiptDigest,digest:""};o.assuranceContract??=qO(o),o.digest=Wt(Tb(o)),s={...Eb(s),contract:o};let a=Qt(s);if(t.semanticImplementable&&!a.complete)throw new Error(`Planning semantic implementability contradicts contract: ${a.reasons.join(", ")}.`);if(!t.semanticImplementable){let{contract:l,...d}=s;return d}let c=ca(s);return{...s,evaluatorReceipts:[...s.evaluatorReceipts.filter(l=>l.evaluator!=="planning"),c]}}function Qt(e){tt(e);let t=e.contract,r=[],n=e.preparationProfileChoice;if((!n||n.status!=="selected"||!n.selectedProfile)&&r.push("profile_not_selected"),!t)return{complete:!1,reasons:[...r,"contract_missing"].toSorted()};(t.schemaVersion!==1||!Le.test(t.artifactId)||!Number.isInteger(t.revision)||t.revision<1)&&r.push("contract_identity"),t.profile!==n?.selectedProfile&&r.push("profile_mismatch"),(t.risk!==e.risk||t.productBaselineRef!==e.productBaselineRef)&&r.push("intake_binding");let i=e.evaluatorReceipts.find(u=>u.evaluator==="discovery");if((!i||t.discoveryReceiptDigest!==i.receiptDigest)&&r.push("discovery_binding"),(!Array.isArray(t.scope)||!t.scope.length||t.scope.some(u=>!H.test(u)))&&r.push("scope"),t.profile==="plan"&&(!Array.isArray(t.nonGoals)||!t.nonGoals.length)&&r.push("plan_non_goals"),t.acceptanceCriteria.length||r.push("acceptance_criteria"),t.tasks.length||r.push("tasks"),t.validations.length||r.push("validations"),!t.assuranceContract)r.push("assurance_contract");else try{sr(t.assuranceContract)}catch(u){r.push(`assurance_contract:${u instanceof Error?u.message:"invalid"}`)}let s=aa(t.acceptanceCriteria,"criterion",r),o=aa(t.tasks,"task",r),a=aa(t.validations,"validation",r),c=aa(t.risks,"risk",r),l=new Set(e.evidence.map(u=>u.id)),d=new Map(e.dependencyGraph.nodes.map(u=>[u.id,u]));for(let u of t.acceptanceCriteria)oa(u,"criterion",d,r),(!u.validationIds.length||u.validationIds.some(h=>!a.has(h)))&&r.push(`criterion:${u.id}:validation_coverage`),t.tasks.some(h=>h.criterionIds.includes(u.id))||r.push(`criterion:${u.id}:task_coverage`);for(let u of t.tasks)oa(u,"task",d,r),(!u.criterionIds.length||u.criterionIds.some(h=>!s.has(h)))&&r.push(`task:${u.id}:criterion_coverage`),u.dependsOnTaskIds.some(h=>!o.has(h)||h===u.id)&&r.push(`task:${u.id}:dependencies`);for(let u of t.validations)oa(u,"validation",d,r),(!u.criterionIds.length||u.criterionIds.some(h=>!s.has(h)))&&r.push(`validation:${u.id}:criterion_coverage`);for(let u of t.risks)oa(u,"risk",d,r),H.test(u.control)||r.push(`risk:${u.id}:control`);if(t.guide){t.profile!=="plan"&&r.push("quick_guide_forbidden"),d.get(t.guide.dependencyNodeId)?.kind!=="guide"&&r.push("guide_dependency_node"),(!t.guide.content.length||t.guide.content.some(u=>!H.test(u)))&&r.push("guide_content"),t.guide.requiredBecause.length||r.push("guide_reason");for(let u of t.guide.requiredBecause)kO.has(u.kind)||r.push("guide_reason_kind"),!u.evidenceIds.length&&!u.riskIds.length&&r.push("Guide reason requires evidence or risk"),(u.evidenceIds.some(h=>!l.has(h))||u.riskIds.some(h=>!c.has(h)))&&r.push("guide_reason_reference")}try{et(e.dependencyGraph)}catch(u){r.push(u instanceof Error?u.message:"dependency_graph")}return t.digest!==Wt(Tb(t))&&r.push("contract_digest"),e.budget.checkpoint&&r.push("budget_checkpoint"),{complete:r.length===0,reasons:[...new Set(r)].toSorted()}}function ca(e){let t=Qt(e);if(!t.complete||!e.contract)throw new Error(`Contract is incomplete: ${t.reasons.join(", ")}.`);let r=[...e.contract.acceptanceCriteria.map(s=>s.id),...e.contract.tasks.map(s=>s.id),...e.contract.validations.map(s=>s.id)].toSorted(),i={schemaVersion:1,evaluator:"planning",outcome:"contract_complete",inputDigest:Wt({contract:e.contract,dependencyGraph:e.dependencyGraph,profileChoice:e.preparationProfileChoice}),evidenceRefs:e.evidence.map(s=>s.id).toSorted(),subjectIds:r,completedIds:r,receiptDigest:""};return i.receiptDigest=Wt({...i,receiptDigest:void 0}),i}function mf(e,t){tt(e);let r={reasoningCalls:ji(t.reasoningCalls??0,"reasoningCalls"),inputTokens:ji(t.inputTokens??0,"inputTokens"),outputTokens:ji(t.outputTokens??0,"outputTokens"),contextBytes:ji(t.contextBytes??0,"contextBytes")},n={reasoningCalls:e.budget.usage.reasoningCalls+r.reasoningCalls,inputTokens:e.budget.usage.inputTokens+r.inputTokens,outputTokens:e.budget.usage.outputTokens+r.outputTokens,contextBytes:e.budget.usage.contextBytes+r.contextBytes},i=NO(e.budget.limits,n);return{...e,budget:{...e.budget,usage:n,...i?{checkpoint:{reason:i,actions:["continue","reduce_scope","cancel"]}}:{}}}}function TO(e,t){return Rb(e,t).state}function Rb(e,t){if(tt(e),!e.budget.checkpoint||!e.budget.checkpoint.actions.includes(t))throw new Error("Active SHAPE budget checkpoint and explicit action are required.");let{checkpoint:r,...n}=e.budget;return{state:{...e,budget:{...n,continuations:n.continuations+(t==="continue"?1:0)}},nextAction:t==="continue"?"continue_shape":t==="reduce_scope"?"return_to_intake_scope_reduction":"cancel_shape"}}function DO(e,t,r){an(e);let n=xi({graph:e.dependencyGraph,fingerprints:e.sourceFingerprints,evidence:e.evidence,observedValues:t,...r?{now:r}:{}});if(!n.staleEvidenceIds.length)return{state:e,reusedEvidenceIds:n.reusedEvidenceIds,staleEvidenceIds:[],refreshTargetIds:[],invalidatedNodeIds:[],reasoningRequired:!1};let i=new Set(n.invalidatedNodeIds),s=new Set(n.staleEvidenceIds),o=e.evidence.filter(p=>s.has(p.id)).map(p=>({id:`refresh:${p.id}`,question:`Refresh stale evidence ${p.id}`,createdBecause:"Referenced source fingerprint changed during resume reconciliation.",createdAt:r??new Date().toISOString(),materialImpacts:["plan","validation"],candidateSourceRefs:p.provenanceRefs,status:"open",evidenceIds:[],dependencyNodeId:p.dependencyNodeId})),a=xO(e.contract,i),c=a!==e.contract,l=[...i].some(p=>["criterion","task","risk","validation","guide","projection"].includes(e.dependencyGraph.nodes.find(f=>f.id===p)?.kind??"")),{contract:d,projection:u,...h}=e,m={...h,discoveryTargets:_r(e.discoveryTargets.map(p=>{let f=p.evidenceIds.filter(g=>!s.has(g));return f.length===p.evidenceIds.length?p:{...p,evidenceIds:f,status:"stale"}}),o),evidence:e.evidence.filter(p=>!i.has(p.dependencyNodeId)),invalidations:[...e.invalidations,{rootIds:n.staleFingerprintIds.map(p=>e.sourceFingerprints.find(f=>f.id===p)?.dependencyNodeId).filter(p=>p!==void 0),invalidatedNodeIds:n.invalidatedNodeIds,reason:"resume:source_freshness"}],...a?{contract:a}:{},...!(l||c)&&e.projection?{projection:e.projection}:{},evaluatorReceipts:e.evaluatorReceipts.filter(p=>p.evaluator!=="discovery"&&(!c||p.evaluator!=="planning"))};return{state:FO(m),reusedEvidenceIds:n.reusedEvidenceIds,staleEvidenceIds:n.staleEvidenceIds,refreshTargetIds:o.map(p=>p.id).toSorted(),invalidatedNodeIds:n.invalidatedNodeIds,reasoningRequired:!0}}function an(e){let t=e;tt(t),Cb(t.budget.limits);for(let[i,s]of Object.entries(t.budget.usage))ji(s,i);et(t.dependencyGraph);for(let i of t.discoveryTargets)gf(i);yf(t);let r=new Set,n=new Set;for(let i of t.technicalDecisions){if(OO(t,i),r.has(i.id)||n.has(i.decisionKey))throw new Error("Technical Decision identity is duplicated.");r.add(i.id),n.add(i.decisionKey)}if(t.activeTechnicalDecisionId&&!t.technicalDecisions.some(i=>i.id===t.activeTechnicalDecisionId&&i.status==="active"))throw new Error("Active Technical Decision reference is invalid.");if(t.preparationProfileChoice&&(Ab(t.preparationProfileChoice.checkpoint),t.preparationProfileChoice.status==="selected"&&(!t.preparationProfileChoice.selectedProfile||!H.test(t.preparationProfileChoice.selectionEvidenceRef??""))))throw new Error("Selected preparation profile lacks explicit evidence.");t.contract&&Qt(t);for(let i of t.evaluatorReceipts){let{receiptDigest:s,...o}=i;if(s!==Wt(o))throw new Error(`${i.evaluator} evaluator receipt digest is invalid.`)}}function OO(e,t){if(t.schemaVersion!==1||!Le.test(t.id)||!Le.test(t.decisionKey)||!Le.test(t.targetId)||!H.test(t.materialityReason)||!H.test(t.recommendationBasis)||!["low","medium","high"].includes(t.confidence)||typeof t.adrQualified!="boolean"||t.proposedDestination!==void 0&&(!H.test(t.proposedDestination)||t.proposedDestination.startsWith("/")||t.proposedDestination.includes(".."))||!["discovering","planning"].includes(t.priorRole)||!["active","resolved"].includes(t.status)||!e.discoveryTargets.some(r=>r.id===t.targetId))throw new Error("Technical Decision record is malformed.");if(t.options.length<2||t.options.length>3||new Set(t.options.map(r=>r.id)).size!==t.options.length)throw new Error(`Technical Decision ${t.id} options are invalid.`);for(let r of t.options)if(!Le.test(r.id)||!H.test(r.label)||!H.test(r.impact)||r.excludedReason!==void 0&&!H.test(r.excludedReason))throw new Error(`Technical Decision ${t.id} option is malformed.`);if(!t.options.some(r=>r.id===t.recommendedOptionId)||!t.evidenceIds.length||t.status==="active"&&t.evidenceIds.some(r=>!e.evidence.some(n=>n.id===r)))throw new Error(`Technical Decision ${t.id} recommendation or evidence is invalid.`);if(bt(e.dependencyGraph,t.affectedDependencyRootIds),t.status==="resolved"){if(!t.selectedOptionId||!t.options.some(r=>r.id===t.selectedOptionId)||!H.test(t.answerEvidenceRef??""))throw new Error(`Resolved Technical Decision ${t.id} lacks explicit answer evidence.`)}else if(t.selectedOptionId!==void 0||t.answerEvidenceRef!==void 0)throw new Error(`Active Technical Decision ${t.id} cannot contain answer.`)}function xO(e,t){if(!e)return;let r=e.acceptanceCriteria.filter(l=>!t.has(l.dependencyNodeId)),n=e.tasks.filter(l=>!t.has(l.dependencyNodeId)),i=e.validations.filter(l=>!t.has(l.dependencyNodeId)),s=e.risks.filter(l=>!t.has(l.dependencyNodeId)),o=e.guide&&!t.has(e.guide.dependencyNodeId)?e.guide:void 0;if(r.length===e.acceptanceCriteria.length&&n.length===e.tasks.length&&i.length===e.validations.length&&s.length===e.risks.length&&o===e.guide)return e;let{guide:a,...c}=e;return{...c,acceptanceCriteria:r,tasks:n,validations:i,risks:s,...o?{guide:o}:{}}}function gf(e){if(!e||!Le.test(e.id)||!H.test(e.question)||!H.test(e.createdBecause)||!Number.isFinite(Date.parse(e.createdAt))||!Le.test(e.dependencyNodeId)||!["open","resolved","escalated","blocked","stale"].includes(e.status))throw new Error("Discovery Target is malformed.");if(!Array.isArray(e.materialImpacts)||!e.materialImpacts.length||e.materialImpacts.some(t=>!_O.has(t))||new Set(e.materialImpacts).size!==e.materialImpacts.length)throw new Error(`Discovery Target ${e.id} material impacts are invalid.`);if(!Array.isArray(e.candidateSourceRefs)||!e.candidateSourceRefs.length||e.candidateSourceRefs.some(t=>!H.test(t)))throw new Error(`Discovery Target ${e.id} requires candidate sources.`);if(!Array.isArray(e.evidenceIds)||e.evidenceIds.some(t=>!Le.test(t)))throw new Error(`Discovery Target ${e.id} evidence IDs are invalid.`)}function yf(e){let t=Object.fromEntries(e.sourceFingerprints.map(r=>[r.id,r.kind==="command"?{value:r.value,inputDigest:r.inputDigest}:r.value]));xi({graph:e.dependencyGraph,fingerprints:e.sourceFingerprints,evidence:e.evidence,observedValues:t,now:new Date().toISOString()})}function jO(e,t){let r=Pb(e);if(t.schemaVersion!==1||t.evaluator!=="discovery"||t.receiptDigest!==r.receiptDigest||t.inputDigest!==r.inputDigest)throw new Error("Discovery receipt is stale or bound to another SHAPE state.")}function Ab(e){if(!e||!H.test(e.changeShape)||!Array.isArray(e.surfaceCategories)||!e.surfaceCategories.length||e.surfaceCategories.length>16||e.surfaceCategories.some(t=>!H.test(t))||!Array.isArray(e.materialFacts)||!e.materialFacts.length||e.materialFacts.length>8||e.materialFacts.some(t=>!H.test(t)))throw new Error("Preparation checkpoint is invalid or not compact.")}function tt(e){if(!e||e.schemaVersion!==1||!Ib.has(e.risk)||!H.test(e.productBaselineRef)||!Array.isArray(e.discoveryTargets)||!Array.isArray(e.evidence)||!Array.isArray(e.sourceFingerprints)||!Array.isArray(e.technicalDecisions)||!e.budget||!e.semanticRetryCounts||!Array.isArray(e.evaluatorReceipts))throw new Error("SHAPE state is malformed.")}function Cb(e){for(let[t,r]of Object.entries(e))if(!["maxReasoningCalls","maxInputTokens","maxOutputTokens","maxContextBytes"].includes(t)||!Number.isInteger(r)||r<=0)throw new Error(`SHAPE budget limit ${t} is invalid.`)}function NO(e,t){if(e.maxReasoningCalls!==void 0&&t.reasoningCalls>=e.maxReasoningCalls)return"reasoning_calls";if(e.maxInputTokens!==void 0&&t.inputTokens>=e.maxInputTokens)return"input_tokens";if(e.maxOutputTokens!==void 0&&t.outputTokens>=e.maxOutputTokens)return"output_tokens";if(e.maxContextBytes!==void 0&&t.contextBytes>=e.maxContextBytes)return"context_bytes"}function ji(e,t){if(!Number.isInteger(e)||e<0)throw new Error(`SHAPE usage ${t} is invalid.`);return e}function vf(e){if(e.preparationProfileChoice?.status==="pending"){let{preparationProfileChoice:t,...r}=e;return{...r,evaluatorReceipts:e.evaluatorReceipts.filter(n=>n.evaluator!=="discovery")}}return{...e,evaluatorReceipts:e.evaluatorReceipts.filter(t=>t.evaluator!=="discovery")}}function Eb(e){return{...e,evaluatorReceipts:e.evaluatorReceipts.filter(t=>t.evaluator!=="planning")}}function oa(e,t,r,n){(!Le.test(e.id)||!H.test(e.description))&&n.push(`${t}:${e.id}:content`),r.get(e.dependencyNodeId)?.kind!==t&&n.push(`${t}:${e.id}:dependency_node`)}function aa(e,t,r){let n=new Set;for(let i of e)n.has(i.id)&&r.push(`${t}:${i.id}:duplicate`),n.add(i.id);return n}function Tb(e){let{digest:t,...r}=e;return r}function qO(e){let t=[...e.acceptanceCriteria.map(l=>({id:l.id,kind:"criterion"})),...e.risks.map(l=>({id:l.id,kind:"risk"})),...e.validations.map(l=>({id:`mandatory:${l.id}`,kind:"mandatory_check"}))],r=new Map;for(let l of e.validations.filter(d=>d.command)){let[d,...u]=LO(l.command),h=JSON.stringify([d,u,".",{},["toolchain:current"]]),m=r.get(h),p=[...new Set([...m?.covers??[],...l.criterionIds,`mandatory:${l.id}`])].toSorted();r.set(h,MO(d,u,p))}let n=[...r.values()].toSorted((l,d)=>l.id.localeCompare(d.id)),i=new Set(n.flatMap(l=>l.covers)),s=t.map(l=>l.id).filter(l=>!i.has(l)),o=s.every(l=>t.some(d=>d.id===l&&d.kind==="risk")),a=s.length?[{id:"review:consolidated",kind:"model-inspection",dependsOn:n.map(l=>l.id),covers:[...new Set(s)].toSorted(),cost:"high",scopeRefs:["scope:approved"],fingerprintMode:"global",readOnly:!0,concurrencySafe:!1,conditional:o,...o?{activationPredicateRef:"policy:applicable-review"}:{}}]:[],c=[...n,...a];return ul({schemaVersion:1,sourceDigest:`sha256:${e.discoveryReceiptDigest.replace(/^sha256:/,"")}`,subjects:t,operations:c,evidencePreference:c.map(l=>l.id),reviewBudget:{maxInputTokens:8e3,maxOutputTokens:1500,maxCalls:a.length?2:0,maxConcurrency:4},policyDigest:"policy:gate-snapshot"})}function MO(e,t,r){let n={executable:e,argv:t,logicalCwd:".",environment:{},toolFingerprintRefs:["toolchain:current"]};return{id:`check:${Wt(n).slice(0,16)}`,kind:"command",dependsOn:[],covers:r,cost:"low",scopeRefs:[],fingerprintMode:"global",readOnly:!0,concurrencySafe:!1,conditional:!1,checkIdentity:n,successPredicate:{exitCodes:[0]}}}function LO(e){let t=e.trim().split(/\s+/).filter(Boolean);if(!t.length||/[|;&<>`]/.test(e))throw new Error("Assurance command must use canonical executable and argv without shell control operators.");return t}function _r(e,t){let r=new Map(e.map(n=>[n.id,on(n)]));for(let n of t)r.set(n.id,on(n));return[...r.values()].toSorted((n,i)=>n.id.localeCompare(i.id))}function Wt(e){return SO("sha256").update(JSON.stringify(pf(e))).digest("hex")}function pf(e){return Array.isArray(e)?e.map(pf):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).toSorted(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,pf(r)])):e}function on(e){return structuredClone(e)}function FO(e){return JSON.parse(JSON.stringify(e))}function qi(e){if(e.status!=="awaiting_approval"||!e.shape||!e.shape.contract)return{ready:!1,route:"blocked",reason:"gate_state_invalid"};if(e.shape.activeTechnicalDecisionId)return{ready:!1,route:"awaiting_shape_decision",reason:"technical_decision_open"};try{an(e.shape)}catch(i){let s=i instanceof Error?i.message.toLowerCase():"";return{ready:!1,route:/stale|fresh|evidence|source/.test(s)?"discovering":"blocked",reason:/stale|fresh|evidence|source/.test(s)?"shape_evidence_stale":"shape_state_invalid"}}let t=Qt(e.shape);if(!t.complete){let i=t.reasons.some(s=>/discovery|evidence|source|fresh/.test(s));return{ready:!1,route:i?"discovering":"planning",reason:i?"shape_evidence_stale":"contract_incomplete"}}if(e.contractDigest!==e.shape.contract.digest)return{ready:!1,route:"planning",reason:"contract_digest_mismatch"};let r=ca(e.shape),n=e.shape.evaluatorReceipts.find(i=>i.evaluator==="planning");return!n||n.receiptDigest!==r.receiptDigest||n.inputDigest!==r.inputDigest?{ready:!1,route:"planning",reason:"planning_receipt_stale"}:{ready:!0,contractDigest:e.contractDigest}}function VO(e){let t=qi(e);if(!t.ready)throw new Error(`GATE preflight failed: ${t.reason}.`);let r=e.shape.contract;return[`Objectif : ${Db(e.design.productBaseline.dimensions.find(s=>s.key==="objective")?.value??"Objectif non disponible",512)}`,`Plan : ${r.tasks.length} t\xE2ches \xB7 ${r.acceptanceCriteria.length} crit\xE8res \xB7 ${r.validations.length} validations`,`Risque : ${r.risk} \xB7 ${r.risks.length} contr\xF4les`,`Contrat : ${t.contractDigest.slice(0,8)}\u2026`,"[Approuver] [Modifier] [Rejeter] [Voir]"].join(`
212
+ `)}function BO(e){let t=qi(e);if(!t.ready)throw new Error(`GATE preflight failed: ${t.reason}.`);return JSON.stringify(UO(e.shape.contract),null,2)}function KO(e){let t=e.normalize("NFKC").trim();if(!t)return{kind:"invalid",reason:"empty"};if(/^(?:approuver|approve)$/i.test(t))return{kind:"approved"};if(/^(?:rejeter|reject)$/i.test(t))return{kind:"rejected"};if(/^(?:voir|view)$/i.test(t))return{kind:"view"};let r=/^(?:modifier|change)\s*:(.*)$/is.exec(t);if(r){let n=Db(r[1]??"",1024).trim();return n?{kind:"change_requested",instruction:n}:{kind:"invalid",reason:"instruction_required"}}return/^(?:modifier|change)$/i.test(t)?{kind:"invalid",reason:"instruction_required"}:{kind:"invalid",reason:"ambiguous"}}function Db(e,t){return e.replaceAll("\r"," ").replaceAll(`
213
+ `," ").replaceAll("\0"," ").replace(/\s+/g," ").trim().slice(0,t)}function UO(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).toSorted(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,wf(r)]))}function wf(e){return Array.isArray(e)?e.map(wf):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).toSorted(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,wf(r)])):e}var xb=Ve(_d(),1);var Ob={$schema:"https://json-schema.org/draft/2020-12/schema",title:"Dev Flow task state V6",type:"object",additionalProperties:!1,required:["schemaVersion","taskId","status","revision","risk","design","configSnapshot","policySnapshot","issues","history"],properties:{schemaVersion:{const:6},taskId:{$ref:"#/$defs/text"},status:{$ref:"#/$defs/status"},revision:{type:"integer",minimum:0},risk:{enum:["low","medium","high","critical"]},shape:{$ref:"#/$defs/shapeState"},contractDigest:{$ref:"#/$defs/text"},assurance:{type:"object"},design:{type:"object"},resumeTo:{$ref:"#/$defs/resumeTarget"},configSnapshot:{type:"object"},policySnapshot:{type:"object"},issues:{type:"array"},history:{type:"array",minItems:1,items:{oneOf:[{$ref:"#/$defs/transitionEvent"},{$ref:"#/$defs/workflowEvent"}]}},historySummary:{$ref:"#/$defs/historySummary"},activeArtifact:{$ref:"#/$defs/activeArtifact"},activeWorktree:{$ref:"#/$defs/activeWorktree"},contextCapsule:{type:"object"},routingSnapshot:{type:"object"},routingPolicyVersion:{$ref:"#/$defs/text"},routingDecisions:{type:"array",items:{type:"object"}},intake:{$ref:"#/$defs/intakeState"},benchmarkEnabled:{type:"boolean"},resumeReason:{$ref:"#/$defs/text"},planApproval:{$ref:"#/$defs/planApprovalReceipt"}},allOf:[{if:{properties:{status:{const:"blocked"}},required:["status"]},then:{required:["resumeTo","resumeReason"],properties:{resumeTo:{$ref:"#/$defs/resumeTarget"},resumeReason:{$ref:"#/$defs/text"}}}},{if:{properties:{status:{not:{const:"blocked"}}},required:["status"]},then:{not:{anyOf:[{required:["resumeTo"]},{required:["resumeReason"]}]}}},{if:{properties:{status:{const:"awaiting_approval"}},required:["status"]},then:{required:["contractDigest"],properties:{contractDigest:{$ref:"#/$defs/text"}}}},{if:{properties:{status:{enum:["discovering","awaiting_shape_decision","awaiting_profile_choice","planning","awaiting_intake_decision","awaiting_approval","executing","assuring"]}},required:["status"]},then:{required:["shape"],properties:{shape:{$ref:"#/$defs/shapeState"}}}}],$defs:{text:{type:"string",minLength:1,maxLength:4096},ref:{type:"string",minLength:1,maxLength:512,pattern:"^[A-Za-z0-9][A-Za-z0-9._:/#@+~=-]*$"},status:{enum:["new","intaking","discovering","awaiting_shape_decision","awaiting_profile_choice","planning","awaiting_intake_decision","awaiting_approval","executing","assuring","blocked","cancelled","failed"]},resumeTarget:{enum:["intaking","discovering","awaiting_shape_decision","awaiting_profile_choice","planning","awaiting_intake_decision","awaiting_approval","executing","assuring"]},historyReference:{type:"object",additionalProperties:!1,required:["kind","ref"],properties:{kind:{enum:["task","shape","artifact","worktree","context-capsule","context","issue","correction","gate","scope","evidence","receipt","command","criterion","decision","policy","config","git","symbol"]},ref:{$ref:"#/$defs/ref"},fingerprint:{$ref:"#/$defs/ref"}}},workflowEvent:{type:"object",additionalProperties:!1,required:["sequence","at","type","refs"],properties:{sequence:{type:"integer",minimum:1},at:{type:"string"},type:{enum:["task.created","task.blocked","task.resumed","gate.recorded","scope.approved","artifact.recorded","issue.recorded","correction.recorded","context.updated","intake.checkpoint","advance.rejected","intake.reopened","discovery.target_recorded","discovery.evidence_recorded","discovery.completed","profile.choice_requested","profile.choice_recorded","design.question_recorded","design.answer_recorded","design.invalidated","contract.projected","projection.reconciliation_requested","evidence.invalidated","shape.checkpoint","assurance.evidence_recorded","assurance.evidence_invalidated","assurance.issue_resolved","assurance.human_observation_requested","assure.completed"]},refs:{type:"array",minItems:1,maxItems:16,items:{$ref:"#/$defs/historyReference"}}}},transitionEvent:{type:"object",additionalProperties:!1,required:["sequence","at","type","from","to","revision","sourceFingerprint"],properties:{sequence:{type:"integer",minimum:1},at:{type:"string"},type:{const:"state.transition"},from:{$ref:"#/$defs/status"},to:{$ref:"#/$defs/status"},revision:{type:"integer",minimum:1},sourceFingerprint:{$ref:"#/$defs/text"},terminalSource:{$ref:"#/$defs/status"},terminalResumeTo:{$ref:"#/$defs/resumeTarget"},contractDigest:{$ref:"#/$defs/text"},guardEvidence:{type:"array",minItems:1,items:{type:"object"}},gateDecision:{$ref:"#/$defs/gateDecision"}}},historySummary:{type:"object",additionalProperties:!1,required:["removedCount","firstSequence","lastSequence","firstAt","lastAt","typeCounts"],properties:{removedCount:{type:"integer",minimum:1},firstSequence:{type:"integer",minimum:1},lastSequence:{type:"integer",minimum:1},firstAt:{type:"string"},lastAt:{type:"string"},typeCounts:{type:"object",additionalProperties:{type:"integer",minimum:1}},lastTransition:{type:"object"}}},activeArtifact:{type:"object",additionalProperties:!1,required:["artifactId","ownerRef","fingerprint"],properties:{artifactId:{$ref:"#/$defs/text"},ownerRef:{$ref:"#/$defs/text"},fingerprint:{$ref:"#/$defs/text"}}},activeWorktree:{type:"object",additionalProperties:!1,required:["worktreeRef","gitFingerprint"],properties:{worktreeRef:{$ref:"#/$defs/text"},gitFingerprint:{$ref:"#/$defs/text"}}},intakeState:{type:"object",additionalProperties:!1,required:["schemaVersion","risk","provenance","technicalUnknowns","decisions","answeredDecisionKeys","invalidations","contradictions","semanticComplete","deterministicComplete","checkpointDue","semanticRetryCount","metrics"],properties:{schemaVersion:{const:1},decisions:{type:"array"},answeredDecisionKeys:{type:"array",items:{type:"string"}},invalidations:{type:"array"},contradictions:{type:"array",items:{type:"string"}},semanticComplete:{type:"boolean"},deterministicComplete:{type:"boolean"},checkpointDue:{type:"boolean"},semanticRetryCount:{type:"integer",minimum:0},blockedReason:{enum:["semantic_output_invalid","answer_required"]},metrics:{$ref:"#/$defs/intakeMetrics"},risk:{enum:["low","medium","high","critical"]},provenance:{type:"object",additionalProperties:!1,required:["sourceRefs","capturedAt","freshnessRefs"],properties:{sourceRefs:{type:"array",maxItems:32,items:{type:"string"}},capturedAt:{type:"string",minLength:1,maxLength:128},freshnessRefs:{type:"array",maxItems:32,items:{type:"string"}}}},technicalUnknowns:{type:"array",maxItems:32,items:{type:"object",additionalProperties:!1,required:["key","kind","description","owner"],properties:{key:{type:"string"},kind:{enum:["code","dependency","architecture","validation","operations"]},description:{type:"string"},owner:{const:"shape"}}}},activeQuestionId:{type:"string",minLength:1,maxLength:256}}},shapeState:{type:"object",additionalProperties:!1,required:["schemaVersion","risk","productBaselineRef","discoveryTargets","evidence","sourceFingerprints","technicalDecisions","dependencyGraph","invalidations","budget","semanticRetryCounts","evaluatorReceipts"],properties:{schemaVersion:{const:1},risk:{enum:["low","medium","high","critical"]},productBaselineRef:{$ref:"#/$defs/text"},discoveryTargets:{type:"array",maxItems:4096,items:{type:"object"}},evidence:{type:"array",maxItems:4096,items:{type:"object"}},sourceFingerprints:{type:"array",maxItems:4096,items:{type:"object"}},technicalDecisions:{type:"array",maxItems:4096,items:{type:"object"}},activeTechnicalDecisionId:{$ref:"#/$defs/text"},preparationProfileChoice:{type:"object"},contract:{type:"object"},projection:{type:"object"},dependencyGraph:{type:"object"},invalidations:{type:"array",maxItems:4096,items:{type:"object"}},budget:{type:"object"},semanticRetryCounts:{type:"object"},evaluatorReceipts:{type:"array",maxItems:4096,items:{type:"object"}}}},intakeMetrics:{type:"object",additionalProperties:!1,required:["modelCalls","questionsAsked","questionsAvoided","distinctQuestions","recommendationsAccepted","recommendationsModified","zeroQuestionPath","lateReopenings"],properties:{modelCalls:{type:"integer",minimum:0},questionsAsked:{type:"integer",minimum:0},questionsAvoided:{type:"integer",minimum:0},distinctQuestions:{type:"integer",minimum:0},recommendationsAccepted:{type:"integer",minimum:0},recommendationsModified:{type:"integer",minimum:0},lateReopenings:{type:"integer",minimum:0},inputTokens:{type:"integer",minimum:0},outputTokens:{type:"integer",minimum:0},latencyMs:{type:"integer",minimum:0},zeroQuestionPath:{type:"boolean"}}},gateDecision:{type:"object",additionalProperties:!1,required:["schemaVersion","decision","actor","decidedAt","taskId","artifactId","stateRevision","stateFingerprint","contractDigest","receiptDigest"],properties:{schemaVersion:{const:1},decision:{enum:["approved","change_requested","rejected"]},actor:{const:"user"},decidedAt:{type:"string"},taskId:{$ref:"#/$defs/text"},artifactId:{$ref:"#/$defs/text"},stateRevision:{type:"integer",minimum:0},stateFingerprint:{$ref:"#/$defs/text"},contractDigest:{$ref:"#/$defs/text"},instructionRef:{$ref:"#/$defs/ref"},receiptDigest:{$ref:"#/$defs/text"}}},planApprovalReceipt:{type:"object",additionalProperties:!1,required:["schemaVersion","decision","actor","decidedAt","taskId","artifactId","stateRevision","stateFingerprint","contractDigest","receiptDigest"],properties:{schemaVersion:{const:1},decision:{const:"approved"},actor:{const:"user"},decidedAt:{type:"string"},taskId:{$ref:"#/$defs/text"},artifactId:{$ref:"#/$defs/text"},stateRevision:{type:"integer",minimum:0},stateFingerprint:{$ref:"#/$defs/text"},contractDigest:{$ref:"#/$defs/text"},receiptDigest:{$ref:"#/$defs/text"}}}}};var HO=new xb.Ajv2020({allErrors:!0,strict:!0}),bf=HO.compile(Ob);function la(e){return{valid:bf(e),errors:bf.errors?[...bf.errors]:[]}}var ua=200,da=16,Nb=4096,x=class extends Error{constructor(r,n){super(n);this.code=r;this.name="StateValidationError"}code};function WO(e){if(!be(e.taskId)||!Pf(e.risk))throw new Error("createState requires taskId and risk.");let t=e.contextCapsule??Vb(e.configSnapshot,e.policySnapshot),r={schemaVersion:6,taskId:e.taskId,status:"new",revision:0,risk:e.risk,configSnapshot:ee(e.configSnapshot),policySnapshot:ee(e.policySnapshot),issues:[],history:[{sequence:1,at:ha(e.at),type:"task.created",refs:[{kind:"task",ref:"state:taskId"}]}],...e.activeArtifact?{activeArtifact:ee(e.activeArtifact)}:{},...e.activeWorktree?{activeWorktree:ee(e.activeWorktree)}:{},contextCapsule:ee(t),...e.intake?{intake:ee(e.intake)}:{},...e.shape?{shape:ee(e.shape)}:{},design:ee(e.design??cf()),benchmarkEnabled:e.benchmarkEnabled??!1,...e.routingSnapshot?{routingSnapshot:ee(e.routingSnapshot)}:{},routingPolicyVersion:ir,routingDecisions:[]};return ie(r),r}function Li(e){if(!ln(e)||e.schemaVersion!==6){let t=ln(e)?String(e.schemaVersion):"missing";throw new x("state_schema_incompatible",`Task state schema ${t} is incompatible; schemaVersion 6 required. No migration is available.`)}return ie(e),ee(e)}function ie(e){let t=la(e);if(!t.valid)throw new x("state_invalid",`Task state V6 schema validation failed: ${JSON.stringify(t.errors.slice(0,3))}`);let r=e;if(!vt(r.status)||!Pf(r.risk))throw new x("state_invalid","Task state V6 status or risk is invalid.");try{ut(r.design)}catch(o){throw new x("state_invalid",`Persisted DesignState is invalid: ${o instanceof Error?o.message:"unknown error"}.`)}bx(r);let n=r.design.activeQuestion?.owner==="intake"?r.design.activeQuestion.id:void 0;if(r.intake?.activeQuestionId!==n)throw new x("state_invalid","INTAKE active-question reference must match DesignState authority.");if(r.intake&&r.intake.risk!==r.risk)throw new x("state_invalid","Task risk contradicts INTAKE assessment risk.");if(r.shape){try{an(r.shape)}catch(o){throw new x("state_invalid",`Persisted ShapeState is invalid: ${o instanceof Error?o.message:"unknown error"}.`)}if(r.shape.risk!==r.risk||r.shape.productBaselineRef!=="state:design.productBaseline")throw new x("state_invalid","Shape state is not bound to current Product Baseline and risk.")}if(["discovering","awaiting_shape_decision","awaiting_profile_choice","planning","awaiting_intake_decision","awaiting_approval","executing","assuring"].includes(r.status)&&!r.shape)throw new x("state_invalid",`Task status ${r.status} requires persisted ShapeState.`);if(r.status==="blocked"){if(!r.resumeTo||!Ti(r.resumeTo)||!be(r.resumeReason))throw new x("state_invalid","Blocked state requires exact operational resume metadata.")}else if(r.resumeTo!==void 0||r.resumeReason!==void 0)throw new x("state_invalid","Only blocked may contain resume metadata.");if(r.status==="awaiting_approval"&&!be(r.contractDigest))throw new x("state_invalid","awaiting_approval requires contract digest.");if(r.planApproval&&Mb(r,r.planApproval),["executing","assuring"].includes(r.status)&&!r.planApproval)throw new x("state_invalid",`${r.status} requires current PlanApprovalReceipt.`);if(r.assurance){let o=r.shape?.contract?.assuranceContract;if(!o)throw new x("state_invalid","AssuranceState requires canonical assuranceContract.");try{He(o,r.assurance)}catch(a){throw new x("state_invalid",`Persisted AssuranceState is invalid: ${a instanceof Error?a.message:"unknown error"}.`)}}let i=pt(r.assurance),s=r.history.at(-1)?.type==="assure.completed";if(i!==s)throw new x("state_invalid","AssuranceReceipt and assure.completed must be paired.");if(i){let o=r.assurance?.receipt;if(r.status!=="assuring"||o?.taskId!==r.taskId||o.contractDigest!==r.shape?.contract?.digest)throw new x("state_invalid","Completed ASSURE is bound to another task or contract.")}}function _t(e){return Fe({schemaVersion:e.schemaVersion,taskId:e.taskId,status:e.status,revision:e.revision,risk:e.risk,resumeTo:e.resumeTo,resumeReason:e.resumeReason,contractDigest:e.contractDigest,planApproval:e.planApproval,assurance:e.assurance,configSnapshot:e.configSnapshot,policySnapshot:e.policySnapshot,routingSnapshot:e.routingSnapshot,routingDecisions:e.routingDecisions,intake:e.intake,shape:e.shape,design:e.design,issues:e.issues})}function QO(e){return ie(e),mb(e.status,pt(e.assurance))}function pa(e,t,r){if(ie(e),!Kb.has(t))throw new Error(`Unknown transition guard ${t}.`);if(t==="intake_complete")return vx(e),kf(e,t,"deterministic-check",{evaluator:"intake",outcome:"intake_complete",inputDigest:Fe(e.intake),evidenceRefs:[...r.evidenceRefs],subjectIds:["objective","success_signal","risk"],completedIds:["objective","success_signal","risk"]});if(ma.has(t))throw new Error(`Guard ${t} requires trusted evaluator.`);if(t==="profile_selected"&&wx(e),t==="approval_current"){if(!e.planApproval)throw new Error("approval_current requires PlanApprovalReceipt.");Mb(e,e.planApproval)}let n={schemaVersion:1,guard:t,stateRevision:e.revision,stateFingerprint:_t(e),observedFingerprint:r.observedFingerprint,evidenceRefs:[...r.evidenceRefs],provenance:r.provenance,result:r.result??"passed"};return _f(e,n),n}var qb=new WeakSet;function JO(e,t){if(ie(e),!e.shape||!Ni(e.shape).complete)throw new Error("Discovery evaluator requires current complete Shape Discovery.");let r=e.shape.evaluatorReceipts.find(n=>n.evaluator==="discovery"&&n.receiptDigest===t.receiptDigest);if(!r||fa(r)!==fa(t))throw new Error("Discovery receipt is stale or not persisted.");return kf(e,"discovery_sufficient","repository-observation",{evaluator:"discovery",outcome:"discovery_sufficient",inputDigest:t.inputDigest,evidenceRefs:t.evidenceRefs,subjectIds:t.subjectIds,completedIds:t.completedIds})}function YO(e,t){if(ie(e),!e.shape||!Qt(e.shape).complete||e.shape.contract?.digest!==e.contractDigest&&e.status==="awaiting_approval")throw new Error("Planning evaluator requires current complete Shape contract.");let r=e.shape.evaluatorReceipts.find(n=>n.evaluator==="planning"&&n.receiptDigest===t.receiptDigest);if(!r||fa(r)!==fa(t))throw new Error("Planning receipt is stale or not persisted.");return kf(e,"contract_complete","deterministic-check",{evaluator:"planning",outcome:"contract_complete",inputDigest:t.inputDigest,evidenceRefs:t.evidenceRefs,subjectIds:t.subjectIds,completedIds:t.completedIds})}function XO(e,t){ie(e);let r=Object.keys(t).filter(o=>!["decision","instructionRef","at"].includes(o));if(r.length)throw new Error(`Unknown Gate decision fields: ${r.join(", ")}.`);if(!["approved","change_requested","rejected"].includes(t.decision))throw new Error("Gate decision kind is invalid.");if(t.at!==void 0&&!un(t.at))throw new Error("Gate decision time is invalid.");let n=e.shape?.contract;if(e.status!=="awaiting_approval"||!e.contractDigest||!n)throw new Error("Gate decision requires current canonical contract.");let i=qi(e);if(!i.ready)throw new Error(`Gate preflight failed: ${i.reason}.`);if(t.decision==="change_requested"&&!be(t.instructionRef))throw new Error("Gate change request requires structured instruction reference.");if(t.instructionRef!==void 0&&!Mi.test(t.instructionRef))throw new Error("Gate instruction reference is invalid.");if(t.decision!=="change_requested"&&t.instructionRef!==void 0)throw new Error("Only Gate change request may contain instruction reference.");let s={schemaVersion:1,decision:t.decision,actor:"user",decidedAt:ha(t.at),taskId:e.taskId,artifactId:n.artifactId,stateRevision:e.revision,stateFingerprint:_t(e),contractDigest:e.contractDigest,...t.instructionRef?{instructionRef:t.instructionRef}:{}};return{...s,receiptDigest:Fe(s)}}function ZO(e,t,r){if(ie(e),pt(e.assurance))throw new Error("Completed ASSURE is immutable.");if(wt(e)!=="SHAPE"&&e.status!=="awaiting_intake_decision")throw new Error("ShapeState may change only in SHAPE or while resolving linked Intake escalation.");if(!Pf(t.risk)||t.risk!==e.risk||t.productBaselineRef!=="state:design.productBaseline")throw new Error("Shape update must remain bound to current Product Baseline and risk.");let n=e.shape?.contract?.digest!==t.contract?.digest,{planApproval:i,assurance:s,contractDigest:o,...a}=e;return fe(n?{...a,shape:ee(t),...t.contract?{contractDigest:t.contract.digest}:{}}:{...e,shape:ee(t)},r)}function ex(e,t,r){if(ie(e),ut(t),!["INTAKE","SHAPE"].includes(wt(e)))throw new Error("DesignState may change only in INTAKE or SHAPE.");let n=tx(e.intake,t),{planApproval:i,assurance:s,...o}=e;return fe({...o,design:ee(t),...n?{intake:n}:{}},r)}function tx(e,t){let r=t.activeQuestion?.owner==="intake"?t.activeQuestion.id:void 0;if(!e){if(r)throw new Error("INTAKE design question requires IntakeState.");return}let{activeQuestionId:n,...i}=e;return{...i,...r?{activeQuestionId:r}:{}}}function rx(e,t){if(ie(e),!["executing","assuring"].includes(e.status))throw new Error("Assurance evidence may be recorded only in BUILD or ASSURE.");let r=kr(e),n=Um(r,e.assurance,t);return fe({...e,assurance:n},{type:"assurance.evidence_recorded",refs:[{kind:"evidence",ref:t.evidenceId},{kind:"command",ref:t.operationId}],...t.recordedAt?{at:t.recordedAt}:{}})}function nx(e,t,r){if(ie(e),!e.assurance)return e;let n=Gm(kr(e),e.assurance,t);return fe({...e,assurance:n},{type:"assurance.evidence_invalidated",refs:t.slice(0,da).map(i=>({kind:"scope",ref:i})),...r?{at:r}:{}})}function ix(e,t){if(ie(e),e.status!=="assuring")throw new Error("Human observation belongs to ASSURE.");let r=Hm(kr(e),e.assurance,t);return fe({...e,assurance:r},{type:"assurance.human_observation_requested",refs:[{kind:"evidence",ref:t.requestId}],at:t.requestedAt})}function sx(e,t,r){if(ie(e),e.status!=="assuring")throw new Error("Assurance issues belong to ASSURE.");let n=dl(kr(e),e.assurance??{schemaVersion:1,evidenceIndex:[],issues:[]},t);return fe({...e,assurance:n},{type:"issue.recorded",refs:[{kind:"issue",ref:t.issueId},{kind:"evidence",ref:t.evidenceRef}],...r?{at:r}:{}})}function ox(e,t,r){if(ie(e),e.status!=="assuring"||!e.assurance)throw new Error("Assurance correction requires active ASSURE issue state.");let n=fl(kr(e),e.assurance,t);return fe({...e,assurance:n},{type:"correction.recorded",refs:[{kind:"issue",ref:t}],...r?{at:r}:{}})}function ax(e,t,r){if(ie(e),e.status!=="assuring"||!e.assurance)throw new Error("Assurance issue resolution requires active ASSURE issue state.");let n=pl(kr(e),e.assurance,t);return fe({...e,assurance:n},{type:"assurance.issue_resolved",refs:[{kind:"issue",ref:t}],...r?{at:r}:{}})}function cx(e,t){if(ie(e),e.status!=="assuring"||!e.assurance)throw new Error("ASSURE completion requires active assuring state and evidence.");let r=t.completedAt??new Date().toISOString(),n=zm(kr(e),e.assurance,{...t,taskId:e.taskId,contractDigest:e.shape?.contract?.digest??"",completedAt:r}),i={sequence:Ef(e),at:r,type:"assure.completed",refs:[{kind:"receipt",ref:n.receipt?.receiptDigest??"receipt:missing"},{kind:"evidence",ref:n.receipt?.evidenceIndexDigest??"evidence:missing"}]};return $f({...e,assurance:n,history:[...e.history,i]})}function lx(e,t){return ie(e),{...e,routingDecisions:[...e.routingDecisions??[],ee(t)]}}function fe(e,t){if(ie(e),de[e.status].terminal||pt(e.assurance))throw new Error("Terminal state history is immutable.");kx(t.refs,`Workflow event ${t.type}`);let r={sequence:Ef(e),at:ha(t.at),type:t.type,refs:ee(t.refs)};return $f({...e,history:[...e.history,r]})}function ux(e,t){ie(e);let{activeArtifact:r,activeWorktree:n,...i}=e,s={...i,...t.activeArtifact===void 0?e.activeArtifact?{activeArtifact:ee(e.activeArtifact)}:{}:t.activeArtifact===null?{}:{activeArtifact:ee(t.activeArtifact)},...t.activeWorktree===void 0?e.activeWorktree?{activeWorktree:ee(e.activeWorktree)}:{}:t.activeWorktree===null?{}:{activeWorktree:ee(t.activeWorktree)},contextCapsule:t.contextCapsule?ee(t.contextCapsule):ee(e.contextCapsule??Vb(e.configSnapshot,e.policySnapshot))};return fe(s,{type:"context.updated",refs:[{kind:"context-capsule",ref:"state:contextCapsule"}],...t.at?{at:t.at}:{}})}function dx(e,t,r={}){if(ie(e),pt(e.assurance))throw new Error("Completed ASSURE is immutable.");if(Ex(r),!vt(t))throw new Error(`Invalid state transition from ${e.status} to ${String(t)}.`);let n=Fb(e.status,t);if(!n)throw new Error(`Invalid state transition from ${e.status} to ${t}.`);let i=hx(e,t,r,n.guards),s=mx(e,r.guardEvidence??[],n.guards),o=n.guards.filter(S=>!i.has(S)&&s.get(S)?.result!=="passed"&&s.get(S)?.result!=="not_applicable");if(o.length)throw new Error(`Unmet transition guards from ${e.status} to ${t}: ${o.join(", ")}.`);let a=_t(e),c=px(e,t,r),l=ha(r.at),d={sequence:Ef(e),at:l,type:"state.transition",from:e.status,to:t,revision:e.revision+1,sourceFingerprint:a,...t==="cancelled"||t==="failed"?{terminalSource:e.status,...e.status==="blocked"&&e.resumeTo?{terminalResumeTo:e.resumeTo}:{}}:{},...t==="awaiting_approval"||r.gateDecision?{contractDigest:c.contractDigest??e.contractDigest}:{},...s.size?{guardEvidence:[...s.values()].map(ee)}:{},...r.gateDecision?{gateDecision:ee(r.gateDecision)}:{}},u=e.shape;t==="discovering"&&!u&&(u=hf({risk:e.risk,productBaselineRef:"state:design.productBaseline"}));let{resumeTo:h,resumeReason:m,planApproval:p,assurance:f,...g}=e,y=r.gateDecision?.decision==="approved"?r.gateDecision:void 0,w=y||(t==="planning"||t==="intaking"||t==="discovering"?void 0:e.planApproval),b=["planning","intaking","discovering","awaiting_shape_decision"].includes(t)?void 0:e.assurance,$={...g,status:t,revision:e.revision+1,...c,...u?{shape:u}:{},...w?{planApproval:ee(w)}:{},...b?{assurance:ee(b)}:{},history:[...e.history,d]};return $f($)}function fx(e,t){let r=[];return cn(e.configSnapshot)!==cn(t.config)&&r.push("config_changed"),cn(e.policySnapshot)!==cn(t.policy)&&r.push("policy_changed"),e.routingSnapshot&&t.routingSnapshot&&jb(e.routingSnapshot)!==jb(t.routingSnapshot)&&r.push("routing_changed"),{changed:r.length>0,reasons:r}}function px(e,t,r){if(t==="blocked")return{resumeTo:r.resumeTo,resumeReason:r.resumeReason,...e.contractDigest?{contractDigest:e.contractDigest}:{}};if(t==="awaiting_approval"){let n=r.contractDigest;if(!be(n))throw new Error("awaiting_approval requires current contract digest.");return{contractDigest:n}}return e.contractDigest?{contractDigest:e.contractDigest}:{}}function kr(e){let t=e.shape?.contract?.assuranceContract;if(!t)throw new Error("Canonical assuranceContract is missing.");return t}function hx(e,t,r,n){let i=new Set;if(n.includes("task_initialized")){if(!be(e.taskId)||!ln(e.configSnapshot)||!ln(e.policySnapshot))throw new Error("task_initialized failed.");i.add("task_initialized")}if(n.includes("resume_metadata_valid")){if(t==="blocked"){if(!r.resumeTo||!Ti(r.resumeTo)||!be(r.resumeReason))throw new Error("blocked requires operational resumeTo and resumeReason.")}else if(e.status==="blocked"){if(t!==e.resumeTo)throw new Error(`blocked may transition only to exact resumeTo ${e.resumeTo}.`)}else throw new Error(`resume_metadata_valid is not applicable from ${e.status}.`);i.add("resume_metadata_valid")}if(n.includes("terminal_source_recorded")){if(r.terminalSource!==e.status)throw new Error(`${t} requires terminalSource equal to ${e.status}.`);i.add("terminal_source_recorded")}if(n.includes("gate_decision_valid")){if(!r.gateDecision)throw new Error("Gate exit requires decision.");if(yx(e,r.gateDecision),!Lb(r.gateDecision,t))throw new Error(`Gate decision cannot transition to ${t}.`);i.add("gate_decision_valid")}if(r.contractDigest!==void 0&&(e.status!=="planning"||t!=="awaiting_approval"))throw new Error("contractDigest may only enter GATE from Planning.");if(e.status==="planning"&&t==="awaiting_approval"&&e.shape?.contract?.digest!==r.contractDigest)throw new Error("GATE digest must match canonical Shape contract.");return i}function mx(e,t,r){let n=new Map;for(let i of t){if(_f(e,i),!r.includes(i.guard)||Ub.has(i.guard))throw new Error(`Guard evidence for ${i.guard} is not applicable.`);if(ma.has(i.guard)&&!qb.has(i))throw new Error(`Guard ${i.guard} requires trusted evaluator evidence from current runtime.`);if(n.has(i.guard))throw new Error(`Duplicate guard evidence for ${i.guard}.`);n.set(i.guard,i)}return n}function _f(e,t){if(t.schemaVersion!==1||!Kb.has(t.guard)||t.stateRevision!==e.revision||t.stateFingerprint!==_t(e)||!be(t.observedFingerprint)||!t.evidenceRefs?.length||!t.evidenceRefs.every(be)||!["deterministic-check","human-approval","repository-observation"].includes(t.provenance))throw new Error(`Guard evidence for ${t.guard} is stale, malformed, or unproven.`);if(ma.has(t.guard))gx(t,e);else if(t.evaluatorReceipt)throw new Error(`Guard ${t.guard} cannot contain evaluatorReceipt.`)}function kf(e,t,r,n){if(!n.evidenceRefs.length)throw new Error(`${t} evaluator requires evidence references.`);let i={schemaVersion:1,...n,stateRevision:e.revision,stateFingerprint:_t(e)},s={...i,receiptDigest:Fe(i)},o=Bb({schemaVersion:1,guard:t,stateRevision:e.revision,stateFingerprint:_t(e),observedFingerprint:s.receiptDigest,evidenceRefs:[...s.evidenceRefs],provenance:r,result:"passed",evaluatorReceipt:s});return _f(e,o),qb.add(o),o}function gx(e,t){let r=e.evaluatorReceipt,n={intake_complete:"intake",discovery_sufficient:"discovery",contract_complete:"planning"};if(!r||r.evaluator!==n[e.guard]||r.stateRevision!==t.revision||r.stateFingerprint!==_t(t)||r.receiptDigest!==Fe({...r,receiptDigest:void 0})||e.observedFingerprint!==r.receiptDigest||!If(e.evidenceRefs,r.evidenceRefs))throw new Error(`Trusted evaluator receipt for ${e.guard} is stale or malformed.`)}function yx(e,t){if(e.status!=="awaiting_approval"||t.schemaVersion!==1||!["approved","change_requested","rejected"].includes(t.decision)||t.actor!=="user"||t.taskId!==e.taskId||t.artifactId!==e.shape?.contract?.artifactId||t.stateRevision!==e.revision||t.stateFingerprint!==_t(e)||t.contractDigest!==e.contractDigest||t.receiptDigest!==Fe({...t,receiptDigest:void 0})||!un(t.decidedAt)||t.instructionRef!==void 0&&!Mi.test(t.instructionRef)||t.decision==="change_requested"!==be(t.instructionRef))throw new Error("Gate decision is stale or bound to another state.")}function Mb(e,t){if(t.decision!=="approved"||t.actor!=="user"||t.taskId!==e.taskId||t.artifactId!==e.shape?.contract?.artifactId||t.receiptDigest!==Fe({...t,receiptDigest:void 0})||!un(t.decidedAt)||t.instructionRef!==void 0||t.stateRevision>=e.revision||t.contractDigest!==e.contractDigest||t.contractDigest!==e.shape?.contract?.digest)throw new x("state_invalid","PlanApprovalReceipt is stale or bound to another contract.")}function Lb(e,t){return e.decision==="approved"?t==="executing":e.decision==="change_requested"?t==="planning":t==="cancelled"}function Fb(e,t){return de[e].transitions[t]}function vx(e){let t=e.intake;if(!t||!uf(e.design)||!t.semanticComplete||!t.deterministicComplete||t.activeQuestionId||t.contradictions.length||t.blockedReason||t.risk!==e.risk)throw new Error("intake_complete requires complete current INTAKE assessment.")}function wx(e){let t=e.shape?.preparationProfileChoice;if(!t||t.status!=="selected"||!t.selectedProfile||!be(t.selectionEvidenceRef))throw new Error("profile_selected requires explicit persisted Quick/Plan answer.")}function bx(e){if(!Array.isArray(e.history)||!e.history.length)throw new x("state_invalid","Task state history is empty.");let t=e.historySummary?.lastSequence??0,r=e.historySummary?.lastTransition?.to??"new",n=e.historySummary?.lastTransition?.revision??0;for(let i of e.history){if(!Number.isInteger(i.sequence)||i.sequence<=t||!un(i.at))throw new x("state_invalid","History sequence or timestamp is invalid.");if(t=i.sequence,i.type==="state.transition"){let s=Fb(i.from,i.to);if(!vt(i.from)||!vt(i.to)||i.from!==r||!s)throw new x("state_invalid",`History edge ${i.from} -> ${i.to} is invalid.`);if(i.revision!==n+1)throw new x("state_invalid","History transition revision is non-monotonic.");Sx(i,s),n=i.revision,r=i.to}}if(r!==e.status)throw new x("state_invalid",`History latest status ${r} differs from ${e.status}.`);if(n!==e.revision)throw new x("state_invalid",`History latest revision ${n} differs from ${e.revision}.`)}function Sx(e,t){if(!be(e.sourceFingerprint))throw new x("state_invalid","Transition source fingerprint is missing.");if(e.to==="cancelled"||e.to==="failed"){if(e.terminalSource!==e.from)throw new x("state_invalid","Terminal transition source is invalid.")}else if(e.terminalSource!==void 0||e.terminalResumeTo!==void 0)throw new x("state_invalid","Non-terminal transition contains terminal source metadata.");let r=t.guards.filter(i=>!Ub.has(i)).toSorted(),n=e.guardEvidence??[];if(!If(r,n.map(i=>i.guard).toSorted()))throw new x("state_invalid",`Transition ${e.from} -> ${e.to} guard evidence is incomplete.`);for(let i of n){if(i.schemaVersion!==1||i.stateRevision!==e.revision-1||i.stateFingerprint!==e.sourceFingerprint||!be(i.observedFingerprint)||!i.evidenceRefs.length||!i.evidenceRefs.every(be)||!["passed","not_applicable"].includes(i.result))throw new x("state_invalid",`Persisted guard ${i.guard} is malformed or stale.`);if(ma.has(i.guard))_x(i);else if(i.evaluatorReceipt!==void 0)throw new x("state_invalid",`Non-trusted guard ${i.guard} contains evaluator receipt.`)}if(t.guards.includes("gate_decision_valid")){if(!e.gateDecision||e.gateDecision.stateRevision!==e.revision-1||e.gateDecision.stateFingerprint!==e.sourceFingerprint||e.gateDecision.contractDigest!==e.contractDigest||e.gateDecision.schemaVersion!==1||!["approved","change_requested","rejected"].includes(e.gateDecision.decision)||e.gateDecision.actor!=="user"||!Lb(e.gateDecision,e.to)||!un(e.gateDecision.decidedAt)||e.gateDecision.instructionRef!==void 0&&!Mi.test(e.gateDecision.instructionRef)||e.gateDecision.decision==="change_requested"!==be(e.gateDecision.instructionRef)||e.gateDecision.receiptDigest!==Fe({...e.gateDecision,receiptDigest:void 0}))throw new x("state_invalid","Persisted gate decision context is invalid.")}else if(e.gateDecision!==void 0)throw new x("state_invalid","Gate decision is attached to non-gate transition.")}function _x(e){let t=e.evaluatorReceipt,r={intake_complete:"intake",discovery_sufficient:"discovery",contract_complete:"planning"};if(!t||t.evaluator!==r[e.guard]||t.stateRevision!==e.stateRevision||t.stateFingerprint!==e.stateFingerprint||t.receiptDigest!==Fe({...t,receiptDigest:void 0})||e.observedFingerprint!==t.receiptDigest||!If(e.evidenceRefs,t.evidenceRefs))throw new x("state_invalid",`Persisted evaluator receipt for ${e.guard} is invalid.`)}function kx(e,t){if(!Array.isArray(e)||!e.length||e.length>da)throw new Error(`${t} requires 1-${da} references.`);let r=0;for(let n of e){if(!Ix.has(n.kind)||!Mi.test(n.ref)||n.fingerprint!==void 0&&!Mi.test(n.fingerprint))throw new Error(`${t} contains invalid reference.`);r+=n.ref.length+(n.fingerprint?.length??0)}if(r>Nb)throw new Error(`${t} references exceed character budget.`)}function $f(e){let t=e.history.length<=ua?e:{...e,history:e.history.slice(-ua),historySummary:$x(e)};return ie(t),t}function $x(e){let t=e.history.slice(0,-ua),r=t[0],n=t.at(-1),i={};for(let o of t)i[o.type]=(i[o.type]??0)+1;let s=t.toReversed().find(o=>o.type==="state.transition");return{removedCount:t.length,firstSequence:r.sequence,lastSequence:n.sequence,firstAt:r.at,lastAt:n.at,typeCounts:i,...s?{lastTransition:{sequence:s.sequence,revision:s.revision,to:s.to}}:{}}}function Ef(e){return Math.max(e.historySummary?.lastSequence??0,e.history.at(-1)?.sequence??0)+1}function Vb(e,t){return{schemaVersion:1,entries:[{section:"constraints",ownerRef:"state:configSnapshot",provenanceRef:"state:configSnapshot",fingerprintRefs:["config"]},{section:"constraints",ownerRef:"state:policySnapshot",provenanceRef:"state:policySnapshot",fingerprintRefs:["policy"]}],fingerprints:[{id:"config",kind:"config",value:Fe(e),provenanceRef:"state:configSnapshot"},{id:"policy",kind:"policy",value:Fe(t),provenanceRef:"state:policySnapshot"}]}}function jb(e){let{capturedAt:t,...r}=e;return cn(r)}function Ex(e){let t=new Set(["resumeTo","resumeReason","terminalSource","guardEvidence","gateDecision","contractDigest","at"]),r=Object.keys(e).filter(n=>!t.has(n));if(r.length)throw new Error(`Unknown transition options: ${r.join(", ")}.`)}function If(e,t){return e.length===t.length&&[...e].toSorted().every((r,n)=>r===[...t].toSorted()[n])}function fa(e){let{receiptDigest:t,...r}=e;return Fe(r)}function Fe(e){return zO("sha256").update(cn(e)).digest("hex")}function cn(e){return JSON.stringify(Sf(e))}function Sf(e){return Array.isArray(e)?e.map(Sf):ln(e)?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).toSorted(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Sf(r)])):e}function ee(e){return structuredClone(e)}function Bb(e){if(!ln(e)&&!Array.isArray(e)||Object.isFrozen(e))return e;for(let t of Object.values(e))Bb(t);return Object.freeze(e)}function ha(e){return e&&un(e)?new Date(e).toISOString():new Date().toISOString()}function un(e){return typeof e=="string"&&!Number.isNaN(Date.parse(e))}function be(e){return typeof e=="string"&&e.length>0}function ln(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pf(e){return["low","medium","high","critical"].includes(e)}var Mi=/^[A-Za-z0-9][A-Za-z0-9._:/#@+~=-]{0,511}$/,Kb=new Set(na),Ix=new Set(["task","shape","artifact","worktree","context-capsule","context","issue","correction","gate","scope","evidence","receipt","command","criterion","decision","policy","config","git","symbol"]),Ub=new Set(["task_initialized","resume_metadata_valid","terminal_source_recorded","gate_decision_valid"]),ma=new Set(["intake_complete","discovery_sufficient","contract_complete"]);var Af="state.yaml",K=class extends Error{constructor(r,n){super(n);this.code=r;this.name="StateStoreError"}code},Cx={readFile:async e=>{let t=await Re.open(e,Gb.O_RDONLY|(Gb.O_NOFOLLOW??0));try{if(!(await t.stat()).isFile())throw Object.assign(new Error("not regular"),{code:"EINVAL"});return await t.readFile()}finally{await t.close()}},mkdir:(e,t)=>Re.mkdir(e,t),writeFile:(e,t,r)=>Re.writeFile(e,t,r),rename:(e,t)=>Re.rename(e,t),lstat:e=>Re.lstat(e),realpath:e=>Re.realpath(e),unlink:e=>Re.unlink(e)},ya=class{workspaceRoot;tasksRoot;#e;#t;constructor(t,r={}){if(!t||t.includes("\0"))throw new K("state_path_invalid","Workspace root is invalid.");try{if(this.workspaceRoot=Ax(Rf(t)),!Rx(this.workspaceRoot).isDirectory())throw new Error}catch{throw new K("state_path_invalid","Workspace root must be existing directory.")}this.tasksRoot=Rf(this.workspaceRoot,".codex","tasks"),this.#e={...Cx,...r.fileSystem},this.#t=r.temporaryId??Px}paths(t){Tx(t);let r=Rf(this.tasksRoot,t),n=zb(this.tasksRoot,r);if(!n||n===".."||n.startsWith(`..${Wb}`)||Hb(n))throw new K("state_path_invalid","Task ID resolves outside task root.");return{directory:r,statePath:ga(r,Af)}}async load(t){let r=this.paths(t);await this.#s(r.directory),await this.#n(r.statePath,!1);let n;try{n=await this.#e.readFile(r.statePath)}catch(o){throw $r(o,"ENOENT")?new K("state_not_found","Task state does not exist."):new K("state_read_failed","Task state could not be read.")}let i;try{i=(0,Fi.parse)(n.toString("utf8"))}catch{throw new K("state_yaml_invalid","Task state is not valid YAML.")}let s;try{s=Li(i)}catch(o){throw o instanceof x?new K(o.code,o.message):o}if(s.taskId!==t)throw new K("state_task_mismatch","Task state taskId differs from requested task.");return s}async save(t,r){let n=this.paths(t),i;try{i=Li(r)}catch(o){throw o instanceof x?new K(o.code,o.message):o}if(i.taskId!==t)throw new K("state_task_mismatch","Task state taskId differs from requested task.");let s=(0,Fi.stringify)(i);try{Li((0,Fi.parse)(s))}catch{throw new K("state_invalid","Serialized V6 state failed validation.")}await this.#a(n.directory),await this.#n(n.statePath,!0),await this.#i(n.statePath,n.directory,s)}async#i(t,r,n){let i=this.#t();if(!i||/[\\/\u0000]/.test(i))throw new K("state_path_invalid","Temporary identifier is invalid.");let s=ga(r,`.${Af}.${i}.tmp`),o=!0;try{await this.#e.writeFile(s,n,{flag:"wx",mode:384}),await this.#e.rename(s,t),o=!1}catch(a){throw $r(a,"EEXIST")&&(o=!1),new K("state_write_failed","Task state could not be written atomically.")}finally{o&&await this.#e.unlink(s).catch(()=>{})}}async#a(t){for(let r of[ga(this.workspaceRoot,".codex"),this.tasksRoot,t]){try{await this.#e.mkdir(r,{mode:448})}catch(n){if(!$r(n,"EEXIST"))throw new K("state_write_failed","Task directory could not be created.")}await this.#r(r,!1)}await this.#o(t)}async#s(t){for(let r of[ga(this.workspaceRoot,".codex"),this.tasksRoot,t])await this.#r(r,!1);await this.#o(t)}async#r(t,r){try{let n=await this.#e.lstat(t);if(n.isSymbolicLink()||!n.isDirectory())throw new K("state_path_invalid","State path contains symlink or non-directory.")}catch(n){if(n instanceof K)throw n;if(r&&$r(n,"ENOENT"))return;throw $r(n,"ENOENT")?new K("state_not_found","Task state directory does not exist."):new K("state_read_failed","Task directory could not be inspected.")}}async#n(t,r){try{let n=await this.#e.lstat(t);if(n.isSymbolicLink()||!n.isFile())throw new K("state_path_invalid","State path is symlink or non-file.")}catch(n){if(n instanceof K)throw n;if(r&&$r(n,"ENOENT"))return;throw $r(n,"ENOENT")?new K("state_not_found","Task state file does not exist."):new K("state_read_failed","Task state path could not be inspected.")}}async#o(t){try{let[r,n]=await Promise.all([this.#e.realpath(this.tasksRoot),this.#e.realpath(t)]),i=zb(r,n);if(!i||i===".."||i.startsWith(`..${Wb}`)||Hb(i))throw new K("state_path_invalid","Task directory resolves outside task root.")}catch(r){throw r instanceof K?r:new K("state_path_invalid","Task directory could not be resolved safely.")}}};function va(e,t={}){return new ya(e,t)}function Tx(e){if(!e||e==="."||e===".."||/[\\/\u0000]/.test(e))throw new K("state_path_invalid","Task ID must be one non-traversing segment.")}function $r(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}var Vi=class extends Error{constructor(r,n,i){super(r);this.path=n;this.source=i}path;source;exitCode=Ae.POLICY_CONTRADICTION};function Qb(e,t){return t.split(".").reduce((r,n)=>{if(!(typeof r!="object"||r===null||Array.isArray(r)))return r[n]},e)}function Dx(e,t){for(let[r,n]of Object.entries(t.requirements))if(Qb(e.value,r)!==n)throw new Vi("Policy requires "+r+" to be "+JSON.stringify(n)+".",r,e.provenance[r]);for(let[r,n]of Object.entries(t.prohibitions))if(Qb(e.value,r)===n)throw new Vi("Policy prohibits "+r+" from being "+JSON.stringify(n)+".",r,e.provenance[r]);return e}import{createHash as Ox}from"node:crypto";var Cf={glossaryPath:"docs/domain/glossary.md",rulesPath:"docs/domain/rules.md",adrDirectory:"docs/adr"},Jb=/^[A-Za-z0-9][A-Za-z0-9._:/#@+~=-]{0,255}$/;function xx(e){let t=e.detected??[];if(t.length>1)throw new Error("Domain documentation destination is ambiguous.");let r=t[0],n=e.profile,i=e.policy?.contextMapPath??n?.contextMapPath??r?.contextMapPath,s={glossaryPath:e.policy?.glossaryPath??n?.glossaryPath??r?.glossaryPath??Cf.glossaryPath,rulesPath:e.policy?.rulesPath??n?.rulesPath??r?.rulesPath??Cf.rulesPath,adrDirectory:e.policy?.adrDirectory??n?.adrDirectory??r?.adrDirectory??Cf.adrDirectory,...i?{contextMapPath:i}:{}};for(let o of Object.values(s))Yb(o);return s}function jx(e,t){if(!t)throw new Error("Domain projection requires current GATE approval.");let r=new Set,n=new Set;return e.map(i=>{if(!Jb.test(i.operationId)||!Jb.test(i.ownedIdentity))throw new Error("Domain semantic patch identity is invalid.");if(r.has(i.operationId)||n.has(`${i.destinationPath}:${i.ownedIdentity}`))throw new Error("Domain semantic patch identity is duplicated.");if(r.add(i.operationId),n.add(`${i.destinationPath}:${i.ownedIdentity}`),Yb(i.destinationPath),!/^sha256:[a-f0-9]{64}$/.test(i.sourceFingerprint))throw new Error(`Domain semantic patch ${i.operationId} source fingerprint is invalid.`);if(!i.content.trim()||i.content.length>65536||i.content.includes("\0"))throw new Error(`Domain semantic patch ${i.operationId} content is invalid.`);return{...structuredClone(i),schemaVersion:1}})}function Nx(e,t){if(`sha256:${Ox("sha256").update(e).digest("hex")}`!==t.sourceFingerprint)throw new Error(`Domain semantic patch ${t.operationId} source is stale.`);let n=`<!-- dev-flow:${t.ownedIdentity}:start -->`,i=`<!-- dev-flow:${t.ownedIdentity}:end -->`,s=`${n}
214
+ ${t.content.trim()}
215
+ ${i}`,o=e.indexOf(n),a=e.indexOf(i);if(o===-1!=(a===-1)||o!==-1&&a<o)throw new Error(`Domain owned section ${t.ownedIdentity} is malformed.`);if(o===-1)return`${e.trimEnd()}${e.trim()?`
216
+
217
+ `:""}${s}
218
+ `;let c=a+i.length;return`${e.slice(0,o)}${s}${e.slice(c)}`}function Yb(e){if(!e||e.startsWith("/")||e.includes("\\")||e.split("/").includes(".."))throw new Error(`Domain documentation path ${e||"<empty>"} is not portable.`)}import{createHash as qx,randomUUID as Mx}from"node:crypto";var eS=Object.freeze(["model_calls","delegations","input_tokens","output_tokens","token_proxy_context_bytes","context_bytes","latency_ms","capsule_reuses","capsule_invalidations","validation_runs","correction_cycles","review_lanes","human_confirmations","intake_questions","intake_questions_avoided","intake_recommendations_accepted","intake_recommendations_modified","intake_zero_question_paths","intake_late_reopenings","shape_discovery_sessions","shape_planning_sessions","shape_targeted_invalidations","shape_evidence_reuses","routing_decisions","gates","gate_preflight_passes","gate_preflight_failures","gate_approvals","gate_change_requests","gate_rejections","gate_approval_reuses","gate_targeted_returns","blocks","transition_errors","resume_to_first_action_ms","unused_phase_outputs","duplicated_fields","silent_resume_divergences","false_success_detections"]),Lx=new Set(["runId","preparationProfile","phase","metric","value","measurement","source","sequence","occurredAtEpochMs","model","effort","quotaPressure"]),Xb=new Set(["input_tokens","output_tokens"]);function tS(e){let t=Object.keys(e).filter(r=>!Lx.has(r));if(t.length)throw new Error(`Unknown metric event fields: ${t.join(", ")}.`);if(!oS(e.runId)||!Df(e.preparationProfile)||!Di.includes(e.phase))throw new Error("Metric event identity, preparation profile, or phase is invalid.");if(!eS.includes(e.metric)||!wa(e.value))throw new Error("Metric event metric or value is invalid.");if(e.sequence!==void 0&&(!Number.isInteger(e.sequence)||e.sequence<0))throw new Error("Metric sequence is invalid.");if(e.occurredAtEpochMs!==void 0&&(!Number.isInteger(e.occurredAtEpochMs)||e.occurredAtEpochMs<0))throw new Error("Metric timestamp is invalid.");return Ux(e),nS(e.metric,e.measurement,e.source),{schemaVersion:1,runId:e.runId,preparationProfile:e.preparationProfile,phase:e.phase,metric:e.metric,value:e.value,measurement:e.measurement,source:e.source,...e.sequence!==void 0?{sequence:e.sequence}:{},...e.occurredAtEpochMs!==void 0?{occurredAtEpochMs:e.occurredAtEpochMs}:{},...e.model!==void 0?{model:e.model}:{},...e.effort!==void 0?{effort:e.effort}:{},...e.quotaPressure!==void 0?{quotaPressure:e.quotaPressure}:{}}}function Fx(){return Mx()}function Vx(e){try{return{accepted:!0,event:tS(e)}}catch{return{accepted:!1,errorCode:"metric_rejected"}}}function Tf(e){if(!aS(e.runId)||!Df(e.preparationProfile)||!["contract_fixture","runtime"].includes(e.source))throw new Error("Trace identity, preparation profile, or source is invalid.");if(e.source==="runtime"&&!oS(e.runId))throw new Error("Runtime trace requires opaque UUID runId.");if(!Array.isArray(e.statuses)||e.statuses.length<2||e.statuses[0]!=="new")throw new Error("Lifecycle trace must start at new and contain a transition.");let t=[...e.statuses];for(let[d,u]of t.entries()){if(!vt(u))throw new Error(`Unknown lifecycle status ${String(u)}.`);if(d===0)continue;let h=t[d-1];if(!de[h].transitions[u])throw new Error(`Lifecycle trace edge ${h} -> ${u} is illegal.`)}let r=t.at(-1);if(!de[r].stable&&!de[r].terminal&&!(r==="assuring"&&e.outcome==="success"))throw new Error(`Lifecycle trace must end at stable or terminal status; received ${r}.`);let n=zx(t.map((d,u)=>iS(d,t,u))),i=t.slice(1).map((d,u)=>({from:t[u],to:d})),s=e.falseSuccessDetections;if(!Number.isInteger(s)||s<0)throw new Error("falseSuccessDetections must be a non-negative integer.");if(!["contract_tests","operator_audit"].includes(e.falseSuccessDetectionSource))throw new Error("falseSuccessDetectionSource is required.");let o=e.source==="contract_fixture"?"contract_tests":"operator_audit";if(e.falseSuccessDetectionSource!==o)throw new Error(`Trace source ${e.source} requires false-success source ${o}.`);let a=e.tokenUsage?Gx(e.tokenUsage):{availability:"unavailable"},c=e.latency===void 0?{availability:"unavailable"}:Hx(e.latency);if(!["success","failed","incomplete"].includes(e.outcome))throw new Error("Trace outcome is invalid.");if(e.outcome==="success"&&r!=="assuring")throw new Error("Success trace must end in assuring.");if(e.outcome==="failed"&&r!=="failed")throw new Error("Failed trace must end in failed.");let l=e.assurance??{checksRun:0,evidenceReused:0,reviewCalls:0,reviewEscalations:0,correctionCycles:0};for(let[d,u]of Object.entries(l))if(!Number.isInteger(u)||u<0)throw new Error(`Assurance counter ${d} is invalid.`);return{schemaVersion:1,sampleIdHash:Qx(e.runId),preparationProfile:e.preparationProfile,source:e.source,statuses:t,phases:n,transitions:i.length,gates:i.filter(({from:d,to:u})=>u==="awaiting_approval"&&d==="planning").length,blocks:i.filter(({to:d})=>d==="blocked").length,resumes:i.filter(({from:d,to:u})=>d==="blocked"&&u!=="cancelled"&&u!=="failed").length,...l,outcome:e.outcome,terminalStatus:r,falseSuccessDetections:s,falseSuccessDetectionSource:e.falseSuccessDetectionSource,tokenUsage:a,latency:c}}function Bx(e){let t=e.traces.map(Tf),r={schemaVersion:1,baselineId:e.baselineId,capturedAt:e.capturedAt,contractVersion:e.contractVersion,source:e.source,limitations:[...e.limitations],samples:t},n=rS(r);if(!n.valid)throw new Error(`Invalid baseline report: ${n.errors.join("; ")}.`);return r}function rS(e){let t=[];if(!ba(e))return{valid:!1,errors:["report must be an object"]};sS(e,["schemaVersion","baselineId","capturedAt","contractVersion","source","limitations","samples"],"report",t),e.schemaVersion!==1&&t.push("schemaVersion must equal 1"),(!aS(e.baselineId)||!Wx(e.capturedAt)||e.contractVersion!=="P0"||e.source!=="contract_fixture")&&t.push("report identity is invalid");let r=e.limitations,n=["contract_fixture_not_runtime","token_telemetry_unavailable","latency_telemetry_unavailable"];if((!Array.isArray(r)||JSON.stringify(r)!==JSON.stringify(n))&&t.push("limitations are invalid"),!Array.isArray(e.samples)||e.samples.length!==3)t.push("baseline requires exactly three samples");else{let i=[];for(let[s,o]of e.samples.entries())Kx(o,s,i,t);(!i.includes("quick")||!i.includes("plan"))&&t.push("samples must cover quick and plan")}return{valid:t.length===0,errors:t}}function Kx(e,t,r,n){if(!ba(e)){n.push(`sample ${t} must be an object`);return}if(sS(e,["schemaVersion","sampleIdHash","preparationProfile","source","statuses","phases","transitions","gates","blocks","resumes","checksRun","evidenceReused","reviewCalls","reviewEscalations","correctionCycles","outcome","terminalStatus","falseSuccessDetections","falseSuccessDetectionSource","tokenUsage","latency"],`sample ${t}`,n),e.schemaVersion!==1||!Df(e.preparationProfile)||e.source!=="contract_fixture"||!/^[a-f0-9]{64}$/.test(String(e.sampleIdHash))){n.push(`sample ${t} identity is invalid`);return}r.push(e.preparationProfile),(!Number.isInteger(e.falseSuccessDetections)||Number(e.falseSuccessDetections)<0)&&n.push(`sample ${t} falseSuccessDetections is invalid`),e.falseSuccessDetectionSource!=="contract_tests"&&n.push(`sample ${t} falseSuccessDetectionSource is invalid`);try{let i=Tf({runId:"validation-placeholder",preparationProfile:e.preparationProfile,source:e.source,statuses:e.statuses,outcome:e.outcome,assurance:{checksRun:e.checksRun,evidenceReused:e.evidenceReused,reviewCalls:e.reviewCalls,reviewEscalations:e.reviewEscalations,correctionCycles:e.correctionCycles},falseSuccessDetections:e.falseSuccessDetections,falseSuccessDetectionSource:e.falseSuccessDetectionSource});for(let s of["phases","transitions","gates","blocks","resumes","checksRun","evidenceReused","reviewCalls","reviewEscalations","correctionCycles","outcome","terminalStatus"])JSON.stringify(e[s])!==JSON.stringify(i[s])&&n.push(`sample ${t} ${s} is inconsistent with statuses`)}catch(i){n.push(`sample ${t} trace invalid: ${i instanceof Error?i.message:"unknown"}`)}Zb(e.tokenUsage)||n.push(`sample ${t} tokenUsage must be unavailable for P0 fixture`),Zb(e.latency)||n.push(`sample ${t} latency must be unavailable for P0 fixture`)}function nS(e,t,r){if(!(Xb.has(e)&&t==="measured"&&r==="native_token_api"||Xb.has(e)&&t==="estimated"&&r==="explicit_token_estimate"||e==="token_proxy_context_bytes"&&t==="estimated"&&r==="context_bytes_proxy"||(e==="latency_ms"||e==="resume_to_first_action_ms")&&t==="measured"&&r==="monotonic_clock"||e==="false_success_detections"&&t==="measured"&&r==="operator_audit"||["unused_phase_outputs","duplicated_fields","silent_resume_divergences"].includes(e)&&t==="measured"&&r==="operator_audit"||["model_calls","delegations","context_bytes","capsule_reuses","capsule_invalidations","review_lanes","human_confirmations","routing_decisions","intake_questions","intake_questions_avoided","intake_recommendations_accepted","intake_recommendations_modified","intake_zero_question_paths","intake_late_reopenings","shape_discovery_sessions","shape_planning_sessions","shape_targeted_invalidations","shape_evidence_reuses","gate_preflight_passes","gate_preflight_failures","gate_approval_reuses"].includes(e)&&t==="measured"&&r==="orchestrator_counter"||["validation_runs","correction_cycles","gates","gate_approvals","gate_change_requests","gate_rejections","gate_targeted_returns","blocks","transition_errors"].includes(e)&&t==="measured"&&r==="state_history"))throw new Error(`Metric ${e} measurement/source mismatch.`)}function Ux(e){if(e.metric==="model_calls"){if(!Kn.includes(String(e.model))||!nr.includes(String(e.effort)))throw new Error("model_calls requires allowlisted model and effort dimensions.")}else if(e.model!==void 0||e.effort!==void 0)throw new Error(`Metric ${e.metric} cannot contain model or effort dimensions.`);if(e.metric==="model_calls"||e.metric==="routing_decisions"){if(!["normal","warning","critical","unknown"].includes(String(e.quotaPressure)))throw new Error(`${e.metric} requires quotaPressure dimension.`)}else if(e.quotaPressure!==void 0)throw new Error(`Metric ${e.metric} cannot contain quotaPressure dimension.`)}function Gx(e){if(!wa(e.inputTokens)||!wa(e.outputTokens))throw new Error("Token usage values are invalid.");return nS("input_tokens",e.measurement,e.source),{availability:"available",...e}}function Hx(e){if(!ba(e)||Object.keys(e).some(t=>!["value","measurement","source"].includes(t))||Object.keys(e).length!==3||!wa(e.value)||e.measurement!=="measured"||e.source!=="monotonic_clock")throw new Error("Latency observation is invalid or mislabeled.");return{availability:"available",...e}}function iS(e,t,r){let n=de[e].macroPhase;if(Di.includes(n))return n;if(r===0)throw new Error(`Cannot derive trace phase for ${e}.`);return iS(t[r-1],t,r-1)}function zx(e){return e.filter((t,r)=>e.indexOf(t)===r)}function sS(e,t,r,n){let i=Object.keys(e).filter(o=>!t.includes(o)),s=t.filter(o=>!Object.hasOwn(e,o));i.length&&n.push(`${r} has unknown fields: ${i.join(", ")}`),s.length&&n.push(`${r} lacks fields: ${s.join(", ")}`)}function Zb(e){return ba(e)&&Object.keys(e).length===1&&e.availability==="unavailable"}function Df(e){return e==="quick"||e==="plan"||e==="unselected"}function Wx(e){return typeof e=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(e)&&!Number.isNaN(Date.parse(e))}function oS(e){return typeof e=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}function wa(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function aS(e){return typeof e=="string"&&e.length>0}function ba(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qx(e){return qx("sha256").update(e).digest("hex")}import{createHash as Jx,randomUUID as Yx}from"node:crypto";function Xx(e){let t={check:e.check,stage:e.stage,errorType:e.errorType,path:e.path,symbol:e.symbol,messagePattern:e.messagePattern,rawMessage:"[redacted]"};return{issueId:Jx("sha256").update(JSON.stringify(t)).digest("hex"),occurrenceId:Yx(),canonical:t}}function Zx(e){return e.codeChanges<2?"debug":e.codeChanges===2?e.investigated?"retry":"investigate":"human_gate"}import{createHash as e2}from"node:crypto";function t2(e,t={}){if(e.profile!=="plan")throw new Error("Only Plan contract may render Markdown projection.");let r=t.path??s2(t.date,t.slug);lS(r);let n=i2(e,"Proposed");return{schemaVersion:1,path:r,status:"Proposed",contractDigest:e.digest,contentFingerprint:xf(n),markdown:n}}function r2(e){if(uS(e),e.status!=="Proposed")throw new Error("Only Proposed Plan projection may become Approved.");let t=e.markdown.replace(/^Status: Proposed$/m,"Status: Approved");return{...e,status:"Approved",contentFingerprint:xf(t),markdown:t}}function cS(e,t){if(uS(e),typeof t!="string")throw new Error("Observed Plan projection content must be text.");return xf(t)!==e.contentFingerprint}function n2(e,t,r){if(!cS(e,t))throw new Error("Plan projection reconciliation requires detected drift.");if(r==="regenerate")return{action:r,projection:e};if(r==="integrate")return{action:r,observedContent:t};throw new Error("Plan projection reconciliation action is invalid.")}function i2(e,t){let r=[`# ${o2(e.artifactId)}`,"",`Status: ${t}`,`Contract-Digest: ${e.digest}`,`Risk: ${e.risk}`,"","## Spec","","### Scope","",...Of(e.scope),"","### Non-goals","",...Of(e.nonGoals),"","### Acceptance criteria","",...e.acceptanceCriteria.map(n=>`- [${n.id}] ${n.description} (validation: ${n.validationIds.join(", ")})`),"","## Plan","",...e.tasks.map((n,i)=>`${i+1}. [${n.id}] ${n.description} (covers: ${n.criterionIds.join(", ")})`),"","## Validation","",...e.validations.map(n=>`- [${n.id}] ${n.description}${n.command?` \u2014 \`${n.command}\``:""}`),"","## Risks","",...e.risks.length?e.risks.map(n=>`- [${n.id}] ${n.description} Control: ${n.control}`):["- None identified."]];return e.guide&&r.push("","## Implementation Guide","",...Of(e.guide.content),"","Required because:",...e.guide.requiredBecause.map(n=>`- ${n.kind} (evidence: ${n.evidenceIds.join(", ")||"none"}; risks: ${n.riskIds.join(", ")||"none"})`)),`${r.join(`
219
+ `)}
220
+ `}function s2(e=new Date().toISOString().slice(0,10),t="change"){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))throw new Error("Plan projection date is invalid.");if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(t))throw new Error("Plan projection slug is invalid.");return`docs/dev-flow/${e}-${t}.md`}function lS(e){if(!e||e.startsWith("/")||e.startsWith("\\")||e.split(/[\\/]/).includes("..")||e.includes("\0")||!e.endsWith(".md"))throw new Error("Plan projection requires safe repository-relative Markdown path.")}function uS(e){if(!e||e.schemaVersion!==1||!["Proposed","Approved"].includes(e.status)||!/^[a-f0-9]{64}$/.test(e.contentFingerprint)||typeof e.contractDigest!="string"||!e.contractDigest.length)throw new Error("Plan projection record is invalid.");lS(e.path)}function Of(e){return e.length?e.map(t=>`- ${t}`):["- None."]}function o2(e){return e.replace(/^artifact[.:/-]?/,"").split(/[._:/-]+/).filter(Boolean).map(t=>t[0].toUpperCase()+t.slice(1)).join(" ")||"Change Plan"}function xf(e){return e2("sha256").update(e).digest("hex")}import{createHash as a2}from"node:crypto";var c2=2e3,Bi=32,l2=/\b(?:sk-[A-Za-z0-9_-]{8,}|(?:api[_-]?key|token|password|secret)\s*[:=]\s*\S+)\b/gi,u2=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,d2=/(?<!\d)(?:\+\d{8,15}|\d{3}[ .()-]\d{3}[ .()-]\d{4})(?!\d)/g,f2=/^(?:you decide|decide for me|choose for me|à toi de décider|décide(?:z)? pour moi|comme tu veux)$/i,p2=/^(?:next|continue|go ahead|shape|(?:passe|passer|avance|avancer).*(?:étape|etape|stage|shape|suite).*)$/i;function h2(e,t,r){if(Ui(e),e.design.activeQuestion)throw new Error("Initial Intake evaluation cannot replace an active question.");let n=e.intake??Lf({risk:e.risk,sourceRefs:["request"],freshnessRefs:["state:configSnapshot","state:policySnapshot"],...r?{capturedAt:r}:{}}),i=Bf(t.productInput);if(i.risk!==e.risk)throw new Error("INTAKE assessment risk must match task risk.");let s=t.resolvedDecisions.map(hS);if(s.some(m=>m.source==="user"&&m.provenanceRef!=="request"))throw new Error("Initial user decisions must be attributable to explicit request.");let o=t.contradictions.map(U).filter(Boolean),a=t.nextQuestion?Vf(t.nextQuestion,{...n,decisions:s,answeredDecisionKeys:s.map(m=>m.key)}):void 0,c={schemaVersion:1,risk:i.risk,provenance:i.provenance,technicalUnknowns:i.technicalUnknowns,...a?{activeQuestionId:a.id}:{},decisions:s,answeredDecisionKeys:Ir(s.map(m=>m.key)),invalidations:n.invalidations,contradictions:o,semanticComplete:t.semanticComplete,deterministicComplete:!1,checkpointDue:!1,semanticRetryCount:n.semanticRetryCount,metrics:{...mS(n.metrics,s,t),questionsAsked:a?1:0,distinctQuestions:a?1:0,zeroQuestionPath:!a}},l=fS(e.design,c,i,a),d=Ki(c,l);c.deterministicComplete=d.complete;let u={...e,intake:c,design:l};return Er(u),{state:fe(u,{type:a?"design.question_recorded":"context.updated",refs:a?[{kind:"decision",ref:dn(a.decisionKey)}]:[{kind:"context",ref:"state:intake"}],...r?{at:r}:{}}),completeness:d}}function Lf(e){let t=Bf({schemaVersion:1,...e.objective?{objective:e.objective}:{},...e.successSignal?{successSignal:e.successSignal}:{},risk:e.risk,provenance:{sourceRefs:e.sourceRefs??[],capturedAt:Kf(e.capturedAt),freshnessRefs:e.freshnessRefs??[]},technicalUnknowns:[]});return{schemaVersion:1,risk:t.risk,provenance:t.provenance,technicalUnknowns:t.technicalUnknowns,decisions:[],answeredDecisionKeys:[],invalidations:[],contradictions:[],semanticComplete:!1,deterministicComplete:!1,checkpointDue:!1,semanticRetryCount:0,metrics:$2()}}function m2(e,t,r){Ui(e);let n=e.intake??Lf({risk:e.risk,sourceRefs:["request"],freshnessRefs:["state:configSnapshot","state:policySnapshot"],...r?{capturedAt:r}:{}});if(e.design.activeQuestion)throw new Error("Active Design Question must be answered or cancelled before another question.");let i=Vf(t,n),s=!n.answeredDecisionKeys.includes(i.decisionKey),o={...e,intake:{...n,activeQuestionId:i.id,semanticComplete:!1,deterministicComplete:!1,checkpointDue:!1,semanticRetryCount:n.semanticRetryCount,metrics:{...n.metrics,questionsAsked:n.metrics.questionsAsked+1,distinctQuestions:n.metrics.distinctQuestions+(s?1:0),zeroQuestionPath:!1}},design:y2(e.design,i)};return Er(o),fe(o,{type:"design.question_recorded",refs:[{kind:"decision",ref:dn(i.decisionKey)}],...r?{at:r}:{}})}function g2(e,t,r,n){Ui(e);let i=e.intake,s=e.design.activeQuestion;if(!i?.activeQuestionId||!s||i.activeQuestionId!==s.id)throw new Error("No active Active Design Question exists.");let o=U(t);if(!o||f2.test(o)||p2.test(o))throw new Error(`Explicit answer required for decision ${s.decisionKey}.`);if(!Array.isArray(r.resolvedDecisions)||!Array.isArray(r.contradictions))throw new Error("Intake model evaluation is structurally invalid.");let a=Bf(r.productInput),c=r.resolvedDecisions.map(hS),l=c.find(k=>k.key==="risk"&&k.source==="user"),d=a.risk!==e.risk;if(d&&!l)throw new Error("INTAKE assessment risk change requires an explicit user decision.");let h=new Set(c.map(k=>k.key)).has(s.decisionKey),m;if(r.nextQuestion){let{activeQuestionId:k,..._}=i,q={..._,decisions:dS(i.decisions,c),answeredDecisionKeys:Ir([...i.answeredDecisionKeys,...c.map(Q=>Q.key)])};if(m=Vf(r.nextQuestion,q),!h&&m.decisionKey!==s.decisionKey)throw new Error(`Unresolved decision ${s.decisionKey} must remain active.`);h||(m={...m,clarificationCount:s.clarificationCount+1})}else if(!h)throw new Error(`Evaluation neither resolved nor clarified decision ${s.decisionKey}.`);let p=Ir([...i.answeredDecisionKeys,...c.map(k=>k.key)]),f=r.contradictions.map(U).filter(Boolean),g=mS(i.metrics,c,r),y=g.distinctQuestions>0&&g.distinctQuestions%5===0&&p.length>=g.distinctQuestions,w={schemaVersion:1,risk:a.risk,provenance:a.provenance,technicalUnknowns:a.technicalUnknowns,...m?{activeQuestionId:m.id}:{},decisions:dS(i.decisions,c),answeredDecisionKeys:p,invalidations:i.invalidations,contradictions:f,semanticComplete:r.semanticComplete,deterministicComplete:!1,checkpointDue:y,semanticRetryCount:i.semanticRetryCount,...m&&m.clarificationCount>=2&&!h?{blockedReason:"answer_required"}:{},metrics:g},b=fS(e.design,w,a,m),$=Ki(w,b);w.deterministicComplete=$.complete;let S={...e,...d?{risk:a.risk,routingDecisions:[]}:{},intake:w,design:b};Er(S);let I=fe(S,{type:"design.answer_recorded",refs:c.length?c.slice(0,16).map(k=>({kind:"decision",ref:dn(k.key)})):[{kind:"decision",ref:dn(s.decisionKey)}],...n?{at:n}:{}});return y&&(I=fe(I,{type:"intake.checkpoint",refs:[{kind:"context",ref:"state:intake"}],...n?{at:n}:{}})),{state:I,completeness:$,...y?{checkpoint:{...a.objective?{objective:a.objective}:{},...a.successSignal?{success:a.successSignal.description}:{},risk:a.risk,answeredDecisionKeys:p}}:{}}}function fS(e,t,r,n){let i=new Map(t.decisions.flatMap(m=>{let p=Ff(m.key);return p?[[p,m]]:[]})),s={sourceRefs:[...r.provenance.sourceRefs],freshnessRefs:[...r.provenance.freshnessRefs]},o={objective:r.objective,users_value:jf([...r.affectedUsers??[],r.motivation]),scope:jf(r.scopeBoundaries??[]),success:r.successSignal?`${r.successSignal.description} [${r.successSignal.observationMethod}]`:void 0,risks_constraints:jf([`risk:${r.risk}`,...r.determiningConstraints??[]])},a=e.productBaseline.dimensions.map(m=>{let p=i.get(m.key);if(p?.recommendationDisposition==="not_applicable")return{key:m.key,status:"not_applicable",notApplicableReason:p.value,provenance:s,dependencyNodeId:m.dependencyNodeId};let f=o[m.key]??p?.value;return{key:m.key,status:f?"resolved":"missing",...f?{value:f}:{},provenance:s,dependencyNodeId:m.dependencyNodeId}}),c=n?pS(n):void 0,l=a.every(m=>["resolved","not_applicable"].includes(m.status)),{digest:d,activeQuestion:u,...h}=e;return sa({...h,productBaseline:{schemaVersion:1,dimensions:a},...c?{activeQuestion:c}:{},semanticComplete:t.semanticComplete&&l&&!c&&!t.contradictions.length})}function y2(e,t){let{digest:r,activeQuestion:n,...i}=e;return sa({...i,activeQuestion:pS(t),semanticComplete:!1})}function pS(e){let t=Ff(e.decisionKey)??"scope";return{schemaVersion:1,id:e.id,decisionKey:e.decisionKey,kind:"product",owner:"intake",subjectIds:[`product:${t}`],prerequisiteIds:[],prompt:e.prompt,mode:"choice",options:e.options.map(r=>({id:r.id,label:r.label,consequences:[r.impact]})),recommendedOptionId:e.recommendedOptionId,recommendationBasis:e.recommendationBasis,confidence:e.recommendationConfidence,priorRole:"intaking",selectionReason:e.determiningImpact,directConsequences:e.options.map(r=>r.impact),freeFormAllowed:!0,clarificationCount:e.clarificationCount}}function Ff(e){return{objective:"objective",users:"users_value",users_value:"users_value",value:"users_value",scope:"scope",success:"success",success_signal:"success",risk:"risks_constraints",constraints:"risks_constraints",risks_constraints:"risks_constraints"}[e]}function jf(e){let t=e.filter(r=>!!r?.trim());return t.length?t.join("; "):void 0}function Ki(e,t){let r=[],n=[];for(let i of t.productBaseline.dimensions)["resolved","not_applicable"].includes(i.status)||r.push(i.key);return["low","medium","high","critical"].includes(e.risk)||r.push("risk"),e.activeQuestionId&&n.push(`active_question:${e.activeQuestionId}`),e.contradictions.length&&n.push("contradictions"),e.semanticComplete||n.push("semantic_incomplete"),e.technicalUnknowns.every(gS)||n.push("untyped_technical_unknown"),{complete:r.length===0&&n.length===0,missingDecisionKeys:Ir(r),reasons:n}}function v2(e,t){let r=e.intake;if(!r)throw new Error("Intake state is missing.");let n=Ki(r,e.design);if(!n.complete||!r.deterministicComplete){let i=[...n.missingDecisionKeys,...n.reasons];throw new Error(`INTAKE incomplete: ${i.join(", ")}.`)}return pa(e,"intake_complete",{observedFingerprint:`sha256:${Uf(r)}`,evidenceRefs:[t],provenance:"deterministic-check"})}function w2(e,t){Ui(e);let r=e.intake;if(!r)throw new Error("Intake state is missing.");let n=Ki(r,e.design);if(n.complete)return e;let i=e.design.activeQuestion?.decisionKey??n.missingDecisionKeys[0]??n.reasons[0]??"intake_context";return fe(e,{type:"advance.rejected",refs:[{kind:"decision",ref:dn(i)}],...t?{at:t}:{}})}function b2(e,t,r,n){if(!e.intake)throw new Error("Intake state is missing.");let i=Ir(t.map(U).filter(Boolean));if(!i.length||!fn(U(r)))throw new Error("Intake invalidation requires decision keys and reason.");let s=Kf(n),o=i.map(m=>({decisionKey:m,reason:U(r),at:s})),a=i.flatMap(m=>{let p=Ff(m);return p?[`product:${p}`]:[]}),c=a.length?lf(e.design,a,U(r),s):e.design,l=c.activeQuestion?.owner==="intake"?c.activeQuestion.id:void 0,{activeQuestionId:d,...u}=e.intake,h={...e,design:c,intake:{...u,...l?{activeQuestionId:l}:{},decisions:e.intake.decisions.filter(m=>!i.includes(m.key)),answeredDecisionKeys:e.intake.answeredDecisionKeys.filter(m=>!i.includes(m)),invalidations:[...e.intake.invalidations,...o].slice(-Bi),semanticComplete:!1,deterministicComplete:!1,checkpointDue:!1,semanticRetryCount:e.intake.semanticRetryCount,metrics:{...e.intake.metrics,lateReopenings:e.intake.metrics.lateReopenings+1}}};return Er(h),fe(h,{type:"intake.reopened",refs:i.slice(0,16).map(m=>({kind:"decision",ref:dn(m)})),at:s})}function S2(e,t){if(!e.intake||e.intake.semanticComplete||e.intake.deterministicComplete||!e.intake.invalidations.length)throw new Error("INTAKE reopen requires persisted product-context invalidation.");return pa(e,"intake_reopened",{observedFingerprint:`sha256:${Uf(e.intake.invalidations.at(-1))}`,evidenceRefs:[t],provenance:"deterministic-check"})}function _2(e){return e==="product"?"INTAKE":"SHAPE"}function k2(e){if(Ui(e),!e.intake)throw new Error("Intake state is missing.");if(e.intake.semanticRetryCount===0){let r={...e,intake:{...e.intake,semanticRetryCount:1}};return Er(r),{state:r,action:"retry_semantic"}}let t={...e,intake:{...e.intake,semanticComplete:!1,deterministicComplete:!1,blockedReason:"semantic_output_invalid"}};return Er(t),{state:t,action:"block"}}function Vf(e,t){if(e.schemaVersion!==1)throw new Error("Active Design Question schemaVersion must be 1.");let r=U(e.id),n=U(e.decisionKey),i=U(e.missingInformation),s=U(e.determiningImpact),o=U(e.prompt),a=U(e.recommendationBasis);if(![r,n,i,s,o,a].every(fn))throw new Error("Active Design Question requires id, decisionKey, missing information, determining impact, prompt, and recommendation basis.");if(t.answeredDecisionKeys.includes(n))throw new Error(`Decision ${n} was already answered.`);if(!Array.isArray(e.options)||e.options.length<2||e.options.length>3)throw new Error("Active Design Question requires 2\u20133 mutually exclusive options.");let c=e.options.map(l=>({id:U(l.id),label:U(l.label),impact:U(l.impact)}));if(c.some(l=>!l.id||!l.label||!l.impact)||new Set(c.map(l=>l.id)).size!==c.length)throw new Error("Active Design Question options must have unique IDs, labels, and impacts.");if(!c.some(l=>l.id===e.recommendedOptionId))throw new Error("Recommended option must reference one offered option.");if(c[0]?.id!==e.recommendedOptionId)throw new Error("Recommended option must be listed first.");if(!e.freeFormAllowed)throw new Error("Active Design Question must allow free-form input.");if(!["high","medium","low"].includes(e.recommendationConfidence))throw new Error("Active Design Question recommendation confidence is invalid.");if(!Number.isInteger(e.clarificationCount)||e.clarificationCount<0||e.clarificationCount>2)throw new Error("Active Design Question clarificationCount must be 0\u20132.");return{schemaVersion:1,id:r,decisionKey:n,missingInformation:i,determiningImpact:s,prompt:o,options:c,recommendedOptionId:U(e.recommendedOptionId),recommendationBasis:a,recommendationConfidence:e.recommendationConfidence,freeFormAllowed:!0,clarificationCount:e.clarificationCount}}function hS(e){let t={key:U(e.key),value:U(e.value),source:e.source,provenanceRef:U(e.provenanceRef),recommendationDisposition:e.recommendationDisposition,dependsOn:Ir((e.dependsOn??[]).map(U).filter(Boolean)).slice(0,Bi)};if(!t.key||!t.value||!t.provenanceRef)throw new Error("Normalized decision requires key, value, and provenance.");if(!["user","repository"].includes(t.source))throw new Error("Normalized decision source is invalid.");if(!["accepted","modified","not_applicable"].includes(t.recommendationDisposition))throw new Error("Recommendation disposition is invalid.");return t}function Bf(e){if(!e||e.schemaVersion!==1)throw new Error("INTAKE assessment schemaVersion must be 1.");let t=(e.technicalUnknowns??[]).map(n=>({key:U(n.key),kind:n.kind,description:U(n.description),owner:"shape"})).slice(0,Bi);if(!t.every(gS))throw new Error("Technical unknowns must be typed and owned by SHAPE.");let r={schemaVersion:1,...fn(U(e.objective))?{objective:U(e.objective)}:{},...e.successSignal?{successSignal:{description:U(e.successSignal.description),observationMethod:U(e.successSignal.observationMethod),...fn(U(e.successSignal.validator))?{validator:U(e.successSignal.validator)}:{},...e.successSignal.guardrails?.length?{guardrails:_a(e.successSignal.guardrails)}:{}}}:{},risk:e.risk,provenance:{sourceRefs:_a(e.provenance?.sourceRefs??[]),capturedAt:Kf(e.provenance?.capturedAt),freshnessRefs:_a(e.provenance?.freshnessRefs??[])},technicalUnknowns:t,...Nf("successValidator",e.successValidator),...Sa("successGuardrails",e.successGuardrails),...Sa("determiningConstraints",e.determiningConstraints),...Sa("affectedUsers",e.affectedUsers),...Nf("motivation",e.motivation),...Nf("urgency",e.urgency),...Sa("scopeBoundaries",e.scopeBoundaries)};if(!["low","medium","high","critical"].includes(r.risk))throw new Error("INTAKE assessment risk is invalid.");return r}function dS(e,t){let r=new Map(e.map(n=>[n.key,n]));for(let n of t)r.set(n.key,n);return[...r.values()].slice(-Bi)}function mS(e,t,r){return{...e,modelCalls:e.modelCalls+1,questionsAvoided:e.questionsAvoided+Math.max(0,r.questionsAvoided??0),recommendationsAccepted:e.recommendationsAccepted+t.filter(n=>n.recommendationDisposition==="accepted").length,recommendationsModified:e.recommendationsModified+t.filter(n=>n.recommendationDisposition==="modified").length,...r.inputTokens===void 0?{}:{inputTokens:(e.inputTokens??0)+qf(r.inputTokens)},...r.outputTokens===void 0?{}:{outputTokens:(e.outputTokens??0)+qf(r.outputTokens)},...r.latencyMs===void 0?{}:{latencyMs:(e.latencyMs??0)+qf(r.latencyMs)}}}function $2(){return{modelCalls:0,questionsAsked:0,questionsAvoided:0,distinctQuestions:0,recommendationsAccepted:0,recommendationsModified:0,zeroQuestionPath:!0,lateReopenings:0}}function Ui(e){if(Er(e),wt(e)!=="INTAKE")throw new Error("Active Design Questions may be changed only in INTAKE.")}function Er(e){let t=la(e);if(!t.valid)throw new Error(`Task state is invalid: ${JSON.stringify(t.errors.slice(0,3))}`)}function gS(e){return fn(e.key)&&["code","dependency","architecture","validation","operations"].includes(e.kind)&&fn(e.description)&&e.owner==="shape"}function U(e){return typeof e!="string"?"":e.replace(l2,"[REDACTED]").replace(u2,"[REDACTED_EMAIL]").replace(d2,"[REDACTED_PHONE]").replace(/[\u0000\r\n]+/g," ").trim().slice(0,c2)}function _a(e){return Ir(e.map(U).filter(Boolean)).slice(0,Bi)}function Nf(e,t){let r=U(t);return r?{[e]:r}:{}}function Sa(e,t){let r=_a(t??[]);return r.length?{[e]:r}:{}}function dn(e){return e.replace(/[^A-Za-z0-9._:/#@+~=-]/g,"-").replace(/^-+/,"").slice(0,400)||`sha256:${Uf(e)}`}function Kf(e){return e&&!Number.isNaN(Date.parse(e))?new Date(e).toISOString():new Date().toISOString()}function Ir(e){return[...new Set(e)]}function qf(e){if(!Number.isFinite(e)||e<0)throw new Error("Metric value must be non-negative.");return Math.round(e)}function fn(e){return typeof e=="string"&&e.length>0}function Uf(e){return a2("sha256").update(JSON.stringify(Mf(e))).digest("hex")}function Mf(e){return Array.isArray(e)?e.map(Mf):typeof e=="object"&&e!==null?Object.fromEntries(Object.entries(e).toSorted(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Mf(r)])):e}function E2(e){return e.policyRequired?{required:!0,reason:"policy"}:e.risk==="critical"?{required:!0,reason:"critical_risk"}:e.requested?{required:!0,reason:"requested"}:e.concurrent?{required:!0,reason:"concurrent"}:e.checkoutSafe?{required:!1,reason:"none"}:{required:!0,reason:"unsafe"}}import{existsSync as yS,readFileSync as vS}from"node:fs";import{fileURLToPath as I2}from"node:url";function P2(e){let t=I2(e),r=t+"/AGENTS.md",n=yS(r)?vS(r,"utf8").match(/npm run [\w:-]+|npm test/g)??[]:[],i=t+"/package.json",s=yS(i)?JSON.parse(vS(i,"utf8")).scripts??{}:{};return n.length?{source:"AGENTS.md",commands:[...n,...s.test?["npm test"]:[]]}:{source:"limited",commands:[]}}var wS=["design","discover","plan","debug","review"],R2=new Set(["validate"]);function bS(e){return wS.includes(e)}async function A2(e,t,r){if(!bS(e)||R2.has(e))throw new Error("Mutation and validation stages stay with the parent workflow; no delegation permitted.");return t(r)}var $S=`Usage: dev-flow <command|objective>
221
+
222
+ Commands:
223
+ init
224
+ resume <task-id>
225
+ status [task-id]
226
+ benchmark summary
227
+ config show [--explain]
228
+ config validate [--json]
229
+ project-profile inspect
230
+ project-profile view [--local]
231
+ project-profile validate [--local]
232
+ project-profile publish [--local]
233
+ project-profile session-view|session-save|session-clear
234
+ --help
235
+
236
+ Workflow:
237
+ dev-flow <objective>
238
+ dev-flow --benchmark <objective>
239
+ `;async function T2(e,t={}){let r=Rd(e);if(r.command==="help")return{command:"help",status:"ok",data:{text:$S}};if(r.command==="init")return Hd(t.init);if(x2(r))return D2(r,t);if(r.command==="config_show"||r.command==="config_validate"){let p=_S(t.configSources);return r.command==="config_show"?{command:r.command,status:"ok",data:r.explain?Pd(p):p.value}:{command:r.command,status:"valid",data:{valid:!0}}}if(r.command==="benchmark_summary")return{command:"benchmark_summary",status:"ok",data:await wl(t.workspaceRoot??process.cwd()).summary()};if(r.command==="status"){if(!r.taskId)return{command:"status",status:"read-only",data:{taskId:void 0}};let p=await va(t.workspaceRoot??process.cwd()).load(r.taskId);return{command:"status",status:p.status,data:{taskId:r.taskId,risk:p.risk,preparationProfile:p.shape?.preparationProfileChoice?.selectedProfile??"unselected",macroPhase:wt(p),benchmarkEnabled:p.benchmarkEnabled??!1}}}let n=r.command==="resume"?await M2(t.workspaceRoot??process.cwd(),r.taskId):void 0,i=_S(t.configSources),s=t.captureSnapshot??cl,o=ka(i.value.subscription)?i.value.subscription:{},a=await s({...t.appServer,config:{plan:typeof o.plan=="string"?o.plan:"auto",...typeof o.planOverride=="string"?{planOverride:o.planOverride}:{},...typeof o.multiplierOverride=="number"?{multiplierOverride:o.multiplierOverride}:{},...Array.isArray(o.modelAllowlist)?{modelAllowlist:o.modelAllowlist.filter(p=>typeof p=="string")}:{},...ka(o.quota)?{quota:{...typeof o.quota.warningPercent=="number"?{warningPercent:o.quota.warningPercent}:{},...typeof o.quota.criticalPercent=="number"?{criticalPercent:o.quota.criticalPercent}:{}}}:{}}}),c=t.nowEpochSeconds??Math.floor(Date.now()/1e3),l=N2(t),d=a.snapshot;if(l)if(d.quota.source==="app-server"&&d.quota.windowDurationMins===300&&d.quota.resetsAt!==void 0&&d.quota.resetsAt>c)try{await rf(l,{windowDurationMins:300,resetsAt:d.quota.resetsAt})}catch{d=j2(d,"quota_cache_write_failed")}else{let p=await tf(l,c);d=nf(d,p)}let u=q2.map(p=>Gn(d,p)),h=u.some(p=>p.model===null||p.effort===null),m=a.failure?.code==="app_server_permission_denied";return{command:r.command,status:m?"routing_permission_required":h?"routing_unavailable":a.available?"routed":"routed_with_warning",data:{...r.command==="run"?{objective:r.objective,benchmarkEnabled:r.flags.benchmark===!0}:{taskId:r.taskId,benchmarkEnabled:n?.benchmarkEnabled??!1},routingSnapshot:d,routingPolicyVersion:ir,routingDecisions:u,...a.failure?{routingFailure:a.failure}:{},...a.error?{warning:a.error}:{}}}}async function D2(e,t){let r=Yd(t.workspaceRoot??process.cwd());if(e.command==="project_profile_session_view")return{command:e.command,status:"ok",data:{state:await r.loadInitState(!0)??null}};if(e.command==="project_profile_session_clear")return{command:e.command,status:"ok",data:{cleared:await r.clearInitState()}};if(e.command==="project_profile_session_save"){let d=await SS(t.projectProfile),u=await r.saveInitState(ES(d));return{command:e.command,status:"saved",data:{state:u}}}if(e.command==="project_profile_inspect"){let d=await r.loadShared(!0),u=await r.loadLocal(!0);return{command:e.command,status:"ok",data:{shared:d??null,local:u??null,localIgnored:await r.isLocalIgnored()}}}if(e.command==="project_profile_view"){let d=e.local?await r.loadLocal(!1):await r.loadShared(!1);return{command:e.command,status:"ok",data:{local:e.local,yaml:Sr(d)}}}let n=await SS(t.projectProfile),i=O2(n);if(e.local){if(i.projections.length)throw new ye("Local project profile cannot publish shared projections.");let d=Ai(i.profile,await r.loadShared(!0));return e.command==="project_profile_publish"&&await r.publishLocal(d),{command:e.command,status:e.command==="project_profile_publish"?"published":"valid",data:{local:!0,path:r.localPath,yaml:Sr(d)}}}let s=await r.prepareShared(i.profile),o=ta(s,i.projections),a=await r.loadShared(!0);if(e.command==="project_profile_validate")return{command:e.command,status:"valid",data:{local:!1,path:r.sharedPath,contentDigest:s.contentDigest,revision:s.revision,diff:Jd(a,s),yaml:Sr(s),projectionPaths:o.map(({path:d})=>d)}};let c=await r.loadInitState(!0);if(c&&(c.status!=="awaiting_approval"||c.candidateContentDigest!==s.contentDigest))throw new E("profile_session_conflict","Project INIT session is not awaiting approval for this exact content digest.");let l=await r.publishShared(s,{projections:o,...t.projectProfile?.approvedAt?{approvedAt:t.projectProfile.approvedAt}:{}});return{command:e.command,status:"published",data:{local:!1,path:r.sharedPath,profileId:l.profileId,revision:l.revision,contentDigest:l.contentDigest,approval:l.approval}}}async function SS(e){if(e?.input!==void 0){if(Buffer.byteLength(e.input)>2e6)throw new ye("Project profile input exceeds 2000000 bytes.");return e.input}if(e?.readInput){let n=await e.readInput();if(Buffer.byteLength(n)>2e6)throw new ye("Project profile input exceeds 2000000 bytes.");return n}if(process.stdin.isTTY)throw new ye("project-profile validate/publish requires YAML or JSON on stdin.");let r="";for await(let n of process.stdin)if(r+=String(n),Buffer.byteLength(r)>2e6)throw new ye("Project profile input exceeds 2000000 bytes.");if(!r.trim())throw new ye("project-profile validate/publish requires YAML or JSON on stdin.");return r}function O2(e){let t=ES(e);if(ka(t)&&"profile"in t){let r=new Set(["profile","projections"]);if(Object.keys(t).some(i=>!r.has(i)))throw new ye("Project profile transaction contains unsupported fields.");if(t.projections!==void 0&&!Array.isArray(t.projections))throw new ye("Project profile projections are invalid.");let n=t.projections??[];if(n.some(i=>!ka(i)||typeof i.path!="string"||typeof i.content!="string"))throw new ye("Project profile projections are invalid.");return{profile:t.profile,projections:n}}return{profile:t,projections:[]}}function ES(e){try{return JSON.parse(e)}catch{try{return(0,kS.parse)(e)}catch{throw new ye("Project profile input is not valid YAML or JSON.")}}}function x2(e){return e.command.startsWith("project_profile_")}function j2(e,t){return e.warnings.includes(t)?e:{...e,warnings:[...e.warnings,t]}}function N2(e){if(e.quotaCachePath!==!1){if(typeof e.quotaCachePath=="string")return e.quotaCachePath;if(!e.captureSnapshot)return C2(process.cwd(),".codex","tasks","five-hour-quota-reset.json")}}var q2=[{stage:"design",risk:"medium",ambiguity:"medium"},{stage:"discover",risk:"medium",ambiguity:"medium"},{stage:"plan",risk:"medium",ambiguity:"medium"},{stage:"debug",risk:"medium",ambiguity:"medium"},{stage:"review",risk:"medium",ambiguity:"medium"}];function _S(e){return Id(e??Ed())}async function M2(e,t){try{return await va(e).load(t)}catch(r){if(r instanceof K&&r.code==="state_not_found")return;throw r}}function ka(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function L2(e=process.argv.slice(2)){T2(e).then(t=>{t.command==="help"?process.stdout.write($S):t.command!=="init"&&process.stdout.write(JSON.stringify(t)+`
240
+ `)},t=>{let r=t instanceof ye||F2(t)?t.exitCode:Ae.INTERNAL_ERROR;process.stderr.write((t instanceof Error?t.message:"Unexpected error.")+`
241
+ `),process.exitCode=r})}function F2(e){return typeof e=="object"&&e!==null&&"exitCode"in e&&typeof e.exitCode=="number"}import.meta.main&&L2();export{a1 as APP_SERVER_PROTOCOL_VERSION,Gs as AppServerClient,Ue as AppServerError,Ym as BENCHMARK_DIRECTORY,Ws as BenchmarkStore,cb as CORE_PROFILE_CATEGORIES,$i as ConfigValidationError,$d as DEFAULT_CONFIG,ow as DEFAULT_SUBSCRIPTION_CONFIG,bb as DEPENDENCY_NODE_KINDS,Ae as EXIT_CODES,na as GUARD_IDS,$S as HELP_TEXT,ua as HISTORY_LIMIT,da as HISTORY_REFERENCE_LIMIT,Nb as HISTORY_REFERENCE_TOTAL_CHARS,ye as InvocationError,eS as LIFECYCLE_METRICS,Yo as LOCAL_PROJECT_PROFILE_IGNORE_ENTRY,ob as LOCAL_PROJECT_PROFILE_PATH,Di as MACRO_PHASES,Un as MODEL_COST_MULTIPLIERS,sl as MODEL_COST_PROFILES,o1 as MODEL_IDS,HD as OPTIONAL_PROFILE_CATEGORIES,GD as PROJECT_DIAGRAM_ROOT,ab as PROJECT_INIT_STATE_PATH,Vi as PolicyError,E as ProjectProfileError,Zo as ProjectProfileStore,wS as ROUTED_STAGES,ir as ROUTING_POLICY_VERSION,sb as SHARED_PROJECT_PROFILE_PATH,Af as STATE_FILENAME,de as STATE_MACHINE,K as StateStoreError,x as StateValidationError,sf as TASK_STATUSES,ya as TaskStateStore,lx as addRoutingDecision,EO as applyDiscoveryEvaluation,nf as applyFiveHourResetFallback,h2 as applyInitialIntakeEvaluation,g2 as applyIntakeResponse,Nx as applyOwnedMarkdownPatch,CO as applyPlanningEvaluation,Dx as applyPolicy,r2 as approvePlanProjection,lb as approveProjectProfile,pt as assuranceSucceeded,ca as attestContractComplete,Pb as attestDiscoverySufficient,v2 as attestIntakeComplete,S2 as attestIntakeReopened,Bx as buildBaselineReport,Zw as buildRoutingPreview,Us as buildRoutingSnapshot,gb as buildStateMachineProjection,cl as captureRoutingSnapshot,Gn as chooseRoute,eg as classifyBenchmarkDeviations,xm as classifyQuotaPressure,fx as compareSnapshot,ul as compileAssuranceContract,sa as compileDesignState,jx as compileDomainSemanticPatches,cx as completeAssurance,zs as createAssuranceState,F1 as createBenchmarkRecord,wl as createBenchmarkStore,cf as createDesignState,XO as createGateDecision,pa as createGuardAttestation,Lf as createIntakeState,tS as createLifecycleMetricEvent,Fx as createMetricRunId,Yd as createProjectProfileStore,hf as createShapeState,WO as createState,va as createTaskStateStore,IO as createTechnicalDecision,ol as createUnavailableRoutingSnapshot,E2 as decideWorktree,A2 as delegateStage,bt as dependencyClosure,wt as deriveMacroPhase,uf as designComplete,cS as detectPlanProjectionDrift,Jd as diffProjectProfiles,P2 as discoverAssuranceCommands,Qt as evaluateContractCompleteness,Ni as evaluateDiscoveryCompleteness,JO as evaluateDiscoveryGuard,Ki as evaluateIntakeCompleteness,YO as evaluatePlanningGuard,Pd as explainConfig,Xx as fingerprintFailure,_t as guardStateFingerprint,nx as invalidateAssurance,lf as invalidateDesign,b2 as invalidateIntakeDecisions,bS as isDelegableStage,kb as isSourceFingerprintFresh,QO as isTaskTerminal,Ed as loadConfigSources,Li as loadStateV6,L2 as main,Zx as nextCorrectionAction,KO as parseGateIntent,Rd as parseInvocation,E1 as planAssuranceExecution,qi as preflightGate,Wd as prepareProjectProfile,tf as readFiveHourResetCache,n2 as reconcilePlanProjection,zD as reconcileProjectProfile,xi as reconcileShapeFreshness,DO as reconcileShapeResume,dl as recordAssuranceIssue,rx as recordAssuranceObservation,fl as recordCorrectionAttempt,fe as recordHistoryEvent,k2 as recordInvalidIntakeModelOutput,mf as recordShapeUsage,sx as recordTaskAssuranceIssue,ox as recordTaskCorrectionAttempt,w2 as rejectPrematureAdvance,VO as renderGateCard,BO as renderGateContract,t2 as renderPlanProjection,ub as renderProjectInitState,Sr as renderProjectProfile,ix as requestHumanObservation,RO as requestPreparationProfileChoice,pl as resolveAssuranceIssue,Id as resolveConfig,xx as resolveDomainDestinations,mO as resolveProductBaseline,TO as resolveShapeBudgetCheckpoint,Rb as resolveShapeBudgetCheckpointWithRouting,Mm as resolveSubscriptionMultiplier,qm as resolveSubscriptionPlan,ax as resolveTaskAssuranceIssue,PO as resolveTechnicalDecision,P1 as reviewRequiresEscalation,_2 as routeLateUnknown,Hd as runInit,T2 as runInvocation,hO as selectDesignFrontier,jm as selectFiveHourWindow,Nm as selectObservedQuotaWindow,AO as selectPreparationProfile,gO as setActiveDesignQuestion,m2 as setIntakeQuestionProjection,L1 as shouldOfferBenchmarkSurvey,tg as summarizeBenchmarkRecords,Tf as summarizeLifecycleTrace,dx as transition,Vx as tryCreateLifecycleMetricEvent,V1 as tryWriteBenchmarkRecord,ex as updateDesignState,ux as updateResumeContext,ZO as updateShapeState,sr as validateAssuranceContract,He as validateAssuranceState,rS as validateBaselineReport,Co as validateConfigSource,I1 as validateConsolidatedReviewResult,et as validateDependencyGraph,ut as validateDesignState,Ai as validateLocalProjectProfile,Xo as validateProjectInitState,Qd as validateProjectProfile,ta as validateProjectProfileProjections,nn as validateSchema,an as validateShapeState,rf as writeFiveHourResetCache};