fern-api 0.64.7 → 0.64.8

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 (2) hide show
  1. package/cli.cjs +5 -7
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -1704,7 +1704,7 @@ ${c.indent}`:""}${VBd(o)}:${l.indent?" ":""}`;return u=!1,s=!0,l.objectItem=void
1704
1704
  `}),r.replaceAll(/\n$/g,"")}function c5D(e){return e?Fh.green(R6.radioOn):R6.radioOff}var C4o=ci(aMe(),1);function nLp(e,t){return e=String(e),t=typeof t=="string"?t:"*",e.length===0?"":Array.from({length:e.length+1}).join(t)}var lAa=class extends X2{_run(t){this.done=t;let r=LW(this.rl),i=r.line.pipe((0,C4o.map)(this.filterInput.bind(this))),n=this.handleSubmitEvents(i);return n.success.forEach(this.onEnd.bind(this)),n.error.forEach(this.onError.bind(this)),r.keypress.pipe((0,C4o.takeUntil)(n.success)).forEach(this.onKeypress.bind(this)),this.render(),this}render(t){let r=this.getQuestion(),i="";r+=this.status==="answered"?this.getMaskedValue(this.answer):this.getMaskedValue(this.rl.line||""),t&&(i=`
1705
1705
  `+Fh.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?Fh.cyan(nLp(t,this.opt.mask)):Fh.italic.dim("[hidden]"):this.opt.mask?nLp(t,this.opt.mask):Fh.italic.dim("[input is hidden] ")}getSpinningValue(t){return this.getMaskedValue(t)}filterInput(t){return t||(this.opt.default==null?"":this.opt.default)}onEnd(t){this.status="answered",this.answer=t.value,this.render(),this.screen.done(),this.done(t.value)}onError(t){this.render(t.isValid)}onKeypress(){this.opt.default&&=void 0,this.render()}};var MUp=ci(Yec(),1),AUp=ci(aMe(),1);var OAa=class extends X2{_run(t){this.done=t,this.editorResult=new AUp.Subject;let r=LW(this.rl);this.lineSubscription=r.line.subscribe(this.startExternalEditor.bind(this));let i=this.opt.waitUserInput===void 0?!0:this.opt.waitUserInput,n=this.handleSubmitEvents(this.editorResult);return n.success.forEach(this.onEnd.bind(this)),n.error.forEach(this.onError.bind(this)),this.currentText=this.opt.default,this.opt.default=null,i?this.render():this.startExternalEditor(),this}render(t){let r="",i=this.getQuestion();i+=this.status==="answered"?Fh.dim("Received"):Fh.dim("Press <enter> to launch your preferred editor."),t&&(r=Fh.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),(0,MUp.editAsync)(this.currentText,this.endExternalEditor.bind(this),{postfix:this.opt.postfix??".txt"})}endExternalEditor(t,r){this.rl.resume(),t?this.editorResult.error(t):this.editorResult.next(r)}onEnd(t){this.editorResult.unsubscribe(),this.lineSubscription.unsubscribe(),this.answer=t.value,this.status="answered",this.render(),this.screen.done(),this.done(this.answer)}onError(t){this.render(t.isValid)}};var fVp=ci(oVp(),1);var cVp=ci(require("readline"),1),lVp=ci(sVp(),1),aGi=class{constructor(t){this.rl||=cVp.default.createInterface(S9D(t)),this.rl.resume(),this.onForceClose=this.onForceClose.bind(this),process.on("exit",this.onForceClose),this.rl.on("SIGINT",this.onForceClose)}onForceClose(){this.close(),process.kill(process.pid,"SIGINT"),console.log("")}close(){this.rl.removeListener("SIGINT",this.onForceClose),process.removeListener("exit",this.onForceClose),this.rl.output.unmute(),this.activePrompt&&typeof this.activePrompt.close=="function"&&this.activePrompt.close(),this.rl.output.end(),this.rl.pause(),this.rl.close()}};function S9D(e={}){e.skipTTYChecks=e.skipTTYChecks===void 0?!0:e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY){let n=new Error("Prompts can not be meaningfully rendered in non-TTY environments");throw n.isTtyError=!0,n}let r=new lVp.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var jAa=class extends aGi{constructor(t={}){super(t),this.log=(0,fVp.default)(this.writeLog.bind(this)),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return rAa(this.rl,this.bottomBar.split(`
1706
1706
  `).length),this}updateBottomBar(t){return rAa(this.rl,1),this.rl.output.unmute(),this.clean(),this.bottomBar=t,this.render(),this.rl.output.mute(),this}writeLog(t){return this.rl.output.unmute(),this.clean(),this.rl.output.write(this.enforceLF(t.toString())),this.render(),this.rl.output.mute(),this}enforceLF(t){return/[\n\r]$/.test(t)?t:t+`
1707
- `}write(t){let r=t.split(/\n/);this.height=r.length,this.rl.setPrompt(r.at(-1)),this.rl.output.rows===0&&this.rl.output.columns===0&&M4o(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var mVp=ci(_Vp(),1),PVp=ci(nks(),1),jVp=ci(gVp(),1),Uq=ci(aMe(),1),wVp=ci(fMa(),1);var r2o=ci(aMe(),1),OVp=ci(fMa(),1),i2o=function(e,t,r){return typeof e[t]!="function"?(0,r2o.of)(e):(0,r2o.from)((0,OVp.default)(e[t])(r).then(i=>(e[t]=i,e)))};var wAa={isPlainObject:mVp.default,set:jVp.default,get:PVp.default},Z3n=class extends aGi{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=wAa.isPlainObject(r)?{...r}:{},wAa.isPlainObject(t)&&(t=Object.values(t).every(n=>wAa.isPlainObject(n)&&n.name===void 0)?Object.entries(t).map(([n,a])=>({name:n,...a})):[t]);let i=Array.isArray(t)?(0,Uq.from)(t):t;return this.process=i.pipe((0,Uq.concatMap)(this.processQuestion.bind(this)),(0,Uq.publish)()),this.process.connect(),this.process.pipe((0,Uq.reduce)((n,a)=>(wAa.set(n,a.name,a.answer),n),this.answers)).toPromise(Promise).then(this.onCompletion.bind(this),this.onError.bind(this))}onCompletion(){return this.close(),this.answers}onError(t){return this.close(),Promise.reject(t)}processQuestion(t){return t={...t},(0,Uq.defer)(()=>(0,Uq.of)(t).pipe((0,Uq.concatMap)(this.setDefaultType.bind(this)),(0,Uq.concatMap)(this.filterIfRunnable.bind(this)),(0,Uq.concatMap)(()=>i2o(t,"message",this.answers)),(0,Uq.concatMap)(()=>i2o(t,"default",this.answers)),(0,Uq.concatMap)(()=>i2o(t,"choices",this.answers)),(0,Uq.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,Uq.defer)(()=>(0,Uq.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,Uq.defer)(()=>(0,Uq.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&wAa.get(this.answers,t.name)!==void 0)return(0,Uq.empty)();if(t.when===!1)return(0,Uq.empty)();if(typeof t.when!="function")return(0,Uq.of)(t);let{answers:r}=this;return(0,Uq.defer)(()=>(0,Uq.from)((0,wVp.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,Uq.filter)(i=>i!=null)))}};function SVp(e){let t=function(r,i){let n;try{n=new Z3n(t.prompts,e)}catch(u){return Promise.reject(u)}let a=n.run(r,i);return a.ui=n,a};return t.prompts={},t.registerPrompt=function(r,i){return t.prompts[r]=i,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",nAa),this.registerPrompt("input",Y$i),this.registerPrompt("number",aAa),this.registerPrompt("confirm",oAa),this.registerPrompt("rawlist",uAa),this.registerPrompt("expand",sAa),this.registerPrompt("checkbox",cAa),this.registerPrompt("password",lAa),this.registerPrompt("editor",OAa)},t.restoreDefaultPrompts(),t}var utc=SVp();function W9D(e,t){utc.registerPrompt(e,t)}function H9D(){utc.restoreDefaultPrompts()}var $9D={prompt:utc,ui:{BottomBar:jAa,Prompt:Z3n},createPromptModule:SVp,registerPrompt:W9D,restoreDefaultPrompts:H9D,Separator:qae},n2o=$9D;var zWp=ci(DVp()),bVD="4.2.1",CWt;(function(e){e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay"})(CWt||(CWt={}));function gVD(e,t){if(!e)throw new Error(t)}function OVD(e){return e?.replace(/\/+$/,"")}async function mVD(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(n=>setTimeout(n,t.retryDelay));try{return await e()}catch(n){if(r=n,!t.retryCheck(n))throw n}}throw r}function PVD(){return new Date().getTime()}function EWp(){return new Date().toISOString()}function xWp(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var zAa=String.fromCharCode,MWp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",g2o={};function jVD(e,t){if(!g2o[e]){g2o[e]={};for(let r=0;r<e.length;r++)g2o[e][e.charAt(r)]=r}return g2o[e][t]}var xAa={compressToBase64:function(e){if(e==null)return"";let t=xAa._compress(e,6,function(r){return MWp.charAt(r)});switch(t.length%4){default:case 0:return t;case 1:return t+"===";case 2:return t+"==";case 3:return t+"="}},decompressFromBase64:function(e){return e==null?"":e==""?null:xAa._decompress(e.length,32,function(t){return jVD(MWp,e.charAt(t))})},compress:function(e){return xAa._compress(e,16,function(t){return zAa(t)})},_compress:function(e,t,r){if(e==null)return"";let i={},n={},a=[],u,l,d="",s="",o="",c=2,b=3,g=2,O=0,m=0,P;for(P=0;P<e.length;P+=1)if(d=e.charAt(P),Object.prototype.hasOwnProperty.call(i,d)||(i[d]=b++,n[d]=!0),s=o+d,Object.prototype.hasOwnProperty.call(i,s))o=s;else{if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<g;u++)O=O<<1,m==t-1?(m=0,a.push(r(O)),O=0):m++;for(l=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}else{for(l=1,u=0;u<g;u++)O=O<<1|l,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=0;for(l=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}c--,c==0&&(c=Math.pow(2,g),g++),delete n[o]}else for(l=i[o],u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;c--,c==0&&(c=Math.pow(2,g),g++),i[s]=b++,o=String(d)}if(o!==""){if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<g;u++)O=O<<1,m==t-1?(m=0,a.push(r(O)),O=0):m++;for(l=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}else{for(l=1,u=0;u<g;u++)O=O<<1|l,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=0;for(l=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}c--,c==0&&(c=Math.pow(2,g),g++),delete n[o]}else for(l=i[o],u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;c--,c==0&&(c=Math.pow(2,g),g++)}for(l=2,u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;for(;;)if(O=O<<1,m==t-1){a.push(r(O));break}else m++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:xAa._decompress(e.length,32768,function(t){return e.charCodeAt(t)})},_decompress:function(e,t,r){let i=[],n=[],a={val:r(0),position:t,index:1},u=4,l=4,d=3,s="",o,c,b,g,O,m,P;for(o=0;o<3;o+=1)i[o]=o;for(b=0,O=Math.pow(2,2),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;P=zAa(b);break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;P=zAa(b);break;case 2:return""}for(i[3]=P,c=P,n.push(P);;){if(a.index>e)return"";for(b=0,O=Math.pow(2,d),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(P=b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=zAa(b),P=l-1,u--;break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=zAa(b),P=l-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,d),d++),i[P])s=i[P];else if(P===l)s=c+c.charAt(0);else return null;n.push(s),i[l++]=c+s.charAt(0),u--,c=s,u==0&&(u=Math.pow(2,d),d++)}}},$tc=class{constructor(){this.events={},this.events={}}on(t,r){return this.events[t]||(this.events[t]=[]),this.events[t].push(r),()=>{this.events[t]=this.events[t].filter(i=>i!==r)}}emit(t,r){for(let i of this.events[t]||[])i(r);for(let i of this.events["*"]||[])i(t,r)}};var O2o="0123456789abcdef",m2o=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length!==16)throw new TypeError("not 128-bit length");return new e(t)}static fromFieldsV7(t,r,i,n){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||!Number.isInteger(n)||t<0||r<0||i<0||n<0||t>0xffffffffffff||r>4095||i>1073741823||n>4294967295)throw new RangeError("invalid field value");let a=new Uint8Array(16);return a[0]=t/2**40,a[1]=t/2**32,a[2]=t/2**24,a[3]=t/2**16,a[4]=t/2**8,a[5]=t,a[6]=112|r>>>8,a[7]=r,a[8]=128|i>>>24,a[9]=i>>>16,a[10]=i>>>8,a[11]=i,a[12]=n>>>24,a[13]=n>>>16,a[14]=n>>>8,a[15]=n,new e(a)}static parse(t){let r;switch(t.length){case 32:r=/^[0-9a-f]{32}$/i.exec(t)?.[0];break;case 36:r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;case 38:r=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(t)?.slice(1,6).join("");break;case 45:r=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break}if(r){let i=new Uint8Array(16);for(let n=0;n<16;n+=4){let a=parseInt(r.substring(2*n,2*n+8),16);i[n+0]=a>>>24,i[n+1]=a>>>16,i[n+2]=a>>>8,i[n+3]=a}return new e(i)}else throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=O2o.charAt(this.bytes[r]>>>4),t+=O2o.charAt(this.bytes[r]&15),(r===3||r===5||r===7||r===9)&&(t+="-");return t}toHex(){let t="";for(let r=0;r<this.bytes.length;r++)t+=O2o.charAt(this.bytes[r]>>>4),t+=O2o.charAt(this.bytes[r]&15);return t}toJSON(){return this.toString()}getVariant(){let t=this.bytes[8]>>>4;if(t<0)throw new Error("unreachable");if(t<=7)return this.bytes.every(r=>r===0)?"NIL":"VAR_0";if(t<=11)return"VAR_10";if(t<=13)return"VAR_110";if(t<=15)return this.bytes.every(r=>r===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new e(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(let r=0;r<16;r++){let i=this.bytes[r]-t.bytes[r];if(i!==0)return Math.sign(i)}return 0}},Gtc=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??wVD()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let i=this.generateOrAbortCore(t,r);return i===void 0&&(this.timestamp=0,i=this.generateOrAbortCore(t,r)),i}generateOrAbortCore(t,r){if(!Number.isInteger(t)||t<1||t>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(t>this.timestamp)this.timestamp=t,this.resetCounter();else if(t+r>=this.timestamp)this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter());else return;return m2o.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=this.random.nextUint32()*1024+(this.random.nextUint32()&1023)}generateV4(){let t=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return t[6]=64|t[6]>>>4,t[8]=128|t[8]>>>2,m2o.ofInner(t)}},wVD=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),AWp,qWp=()=>SVD().toString(),SVD=()=>(AWp||(AWp=new Gtc)).generate(),P2o=class extends Error{constructor(t){super("HTTP error while fetching PostHog: "+t.status),this.response=t,this.name="PostHogFetchHttpError"}},RAa=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};function TWp(e){return typeof e=="object"&&(e instanceof P2o||e instanceof RAa)}var Qtc=class{constructor(t,r){this.flushPromise=null,this.disableGeoip=!0,this.historicalMigration=!1,this.disabled=!1,this.defaultOptIn=!0,this.pendingPromises={},this._events=new $tc,this._isInitialized=!1,gVD(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=OVD(r?.host||"https://us.i.posthog.com"),this.flushAt=r?.flushAt?Math.max(r?.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,r?.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,r?.maxQueueSize??1e3),this.flushInterval=r?.flushInterval??1e4,this.captureMode=r?.captureMode||"json",this.defaultOptIn=r?.defaultOptIn??!0,this._retryOptions={retryCount:r?.fetchRetryCount??3,retryDelay:r?.fetchRetryDelay??3e3,retryCheck:TWp},this.requestTimeout=r?.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r?.featureFlagsRequestTimeoutMs??3e3,this.disableGeoip=r?.disableGeoip??!0,this.disabled=r?.disabled??!1,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0}logMsgIfDebug(t){this.isDebug&&t()}wrap(t){if(this.disabled){this.logMsgIfDebug(()=>console.warn("[PostHog] The client is disabled"));return}if(this._isInitialized)return t();this._initPromise.then(()=>t())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(CWt.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(CWt.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(CWt.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(i,n)=>console.log("PostHog Debug",i,n));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}buildPayload(t){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(t){let r=qWp();return this.pendingPromises[r]=t,t.catch(()=>{}).finally(()=>{delete this.pendingPromises[r]}),t}identifyStateless(t,r,i){this.wrap(()=>{let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",n,i)})}captureStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({distinct_id:t,event:r,properties:i});this.enqueue("capture",a,n)})}aliasStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});this.enqueue("alias",a,n)})}groupIdentifyStateless(t,r,i,n,a,u){this.wrap(()=>{let l=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:i||{},...u||{}}});this.enqueue("capture",l,n)})}async getDecide(t,r={},i={},n={},a={}){await this._initPromise;let u=`${this.host}/decide/?v=3`,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify({token:this.apiKey,distinct_id:t,groups:r,person_properties:i,group_properties:n,...a})};return this.fetchWithRetry(u,l,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(d=>d.json()).catch(d=>{this._events.emit("error",d)})}async getFeatureFlagStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagsStateless(r,i,n,a,u);if(!l)return;let d=l[t];return d===void 0&&(d=!1),d}async getFeatureFlagPayloadStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagPayloadsStateless(r,i,n,a,u);if(!l)return;let d=l[t];return d===void 0?null:d}async getFeatureFlagPayloadsStateless(t,r={},i={},n={},a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a)).payloads}_parsePayload(t){try{return JSON.parse(t)}catch{return t}}async getFeatureFlagsStateless(t,r={},i={},n={},a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a)).flags}async getFeatureFlagsAndPayloadsStateless(t,r={},i={},n={},a){await this._initPromise;let u={};(a??this.disableGeoip)&&(u.geoip_disable=!0);let l=await this.getDecide(t,r,i,n,u),d=l?.featureFlags,s=l?.featureFlagPayloads,o=s;return s&&(o=Object.fromEntries(Object.entries(s).map(([c,b])=>[c,this._parsePayload(b)]))),{flags:d,payloads:o}}enqueue(t,r,i){this.wrap(()=>{if(this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");return}let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:EWp(),uuid:i?.uuid?i.uuid:qWp()};(i?.disableGeoip??this.disableGeoip)&&(n.properties||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId);let u=this.getPersistedProperty(CWt.Queue)||[];u.length>=this.maxQueueSize&&(u.shift(),this.logMsgIfDebug(()=>console.info("Queue is full, the oldest event is dropped."))),u.push({message:n}),this.setPersistedProperty(CWt.Queue,u),this._events.emit(t,n),u.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=xWp(()=>this.flushBackground(),this.flushInterval))})}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(()=>{})}async flush(){return this.flushPromise||(this.flushPromise=this._flush().finally(()=>{this.flushPromise=null}),this.addPendingPromise(this.flushPromise)),this.flushPromise}getCustomHeaders(){let t=this.getCustomUserAgent(),r={};return t&&t!==""&&(r["User-Agent"]=t),r}async _flush(){this.clearFlushTimer(),await this._initPromise;let t=this.getPersistedProperty(CWt.Queue)||[];if(!t.length)return[];let r=t.slice(0,this.maxBatchSize),i=r.map(s=>s.message),n=()=>{let s=this.getPersistedProperty(CWt.Queue)||[];this.setPersistedProperty(CWt.Queue,s.slice(r.length))},a={api_key:this.apiKey,batch:i,sent_at:EWp()};this.historicalMigration&&(a.historical_migration=!0);let u=JSON.stringify(a),l=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${PVD()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,d=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(xAa.compressToBase64(u))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:u};try{await this.fetchWithRetry(l,d)}catch(s){throw s instanceof RAa||n(),this._events.emit("error",s),s}return n(),this._events.emit("flush",i),i}async fetchWithRetry(t,r,i,n){var a;return(a=AbortSignal).timeout??(a.timeout=function(l){let d=new AbortController;return setTimeout(()=>d.abort(),l),d.signal}),await mVD(async()=>{let u=null;try{u=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(d){throw new RAa(d)}if(!(r.mode==="no-cors")&&(u.status<200||u.status>=400))throw new P2o(u);return u},{...this._retryOptions,...i})}async shutdown(t=3e4){await this._initPromise,this.clearFlushTimer();try{await Promise.all(Object.values(this.pendingPromises));let r=Date.now()+t;for(;(this.getPersistedProperty(CWt.Queue)||[]).length!==0;){await this.flush();let n=Date.now();if(r<n)break}}catch(r){if(!TWp(r))throw r;this.logMsgIfDebug(()=>console.error("Error while shutting down PostHog",r))}}},Jtc=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},Ktc=typeof fetch<"u"?fetch:typeof global.fetch<"u"?global.fetch:void 0;if(!Ktc){let e=DWp();Ktc=async(t,r)=>{let i=await e.request({url:t,headers:r.headers,method:r.method.toLowerCase(),data:r.body,signal:r.signal,validateStatus:()=>!0});return{status:i.status,text:async()=>i.data,json:async()=>i.data}}}var RWp=Ktc,DVD=1152921504606847e3,EVD=["is_not"],j2o=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},Z2=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},Ytc=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:u,...l}){this.debugMode=!1,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=i,this.host=a,this.poller=void 0,this.fetch=l.fetch||RWp,this.onError=l.onError,this.customHeaders=u,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let u,l;if(!this.loadedSuccessfullyOnce)return u;for(let d of this.featureFlags)if(t===d.key){l=d;break}if(l!==void 0)try{u=this.computeFlagLocally(l,r,i,n,a),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${u}`))}catch(d){d instanceof Z2?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${d}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return u}async computeFeatureFlagPayloadLocally(t,r){await this.loadFeatureFlags();let i;if(this.loadedSuccessfullyOnce){if(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]),i==null)return null;try{return JSON.parse(i)}catch{return i}}}async getAllFlagsAndPayloads(t,r={},i={},n={}){await this.loadFeatureFlags();let a={},u={},l=this.featureFlags.length==0;return this.featureFlags.map(async d=>{try{let s=this.computeFlagLocally(d,t,r,i,n);a[d.key]=s;let o=await this.computeFeatureFlagPayloadLocally(d.key,s);o&&(u[d.key]=o)}catch(s){s instanceof Z2||s instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${d.key}: ${s}`)),l=!0}}),{response:a,payloads:u,fallbackToDecide:l}}computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new Z2("Flag has experience continuity enabled");if(!t.active)return!1;let l=(t.filters||{}).aggregation_group_type_index;if(l!=null){let d=this.groupTypeMapping[String(l)];if(!d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${l} for feature flag ${t.key}`)),new Z2("Flag has unknown group type index");if(!(d in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let s=a[d];return this.matchFeatureFlagProperties(t,i[d],s)}else return this.matchFeatureFlagProperties(t,r,n)}matchFeatureFlagProperties(t,r,i){let n=t.filters||{},a=n.groups||[],u=!1,l,d=[...a].sort((s,o)=>{let c=!!s.variant,b=!!o.variant;return c&&b?0:c?-1:b?1:0});for(let s of d)try{if(this.isConditionMatch(t,r,s,i)){let o=s.variant,c=n.multivariate?.variants||[];o&&c.some(b=>b.key===o)?l=o:l=this.getMatchingVariant(t,r)||!0;break}}catch(o){if(o instanceof Z2)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new Z2("Can't determine if feature flag is enabled or not with given properties");return!1}isConditionMatch(t,r,i,n){let a=i.rollout_percentage,u=l=>{this.logMsgIfDebug(()=>console.warn(l))};if((i.properties||[]).length>0){for(let l of i.properties){let d=l.type,s=!1;if(d==="cohort"?s=FWp(l,n,this.cohorts,this.debugMode):s=NWp(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&CWp(t.key,r)>a/100)}getMatchingVariant(t,r){let i=CWp(t.key,r,"variant"),n=this.variantLookupTable(t).find(a=>i>=a.valueMin&&i<a.valueMax);if(n)return n.key}variantLookupTable(t){let r=[],i=0,n=0;return((t.filters||{}).multivariate?.variants||[]).forEach(l=>{n=i+l.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:l.key}),i=n}),r}async loadFeatureFlags(t=!1){(!this.loadedSuccessfullyOnce||t)&&await this._loadFeatureFlags()}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this._loadFeatureFlags(),this.pollingInterval);try{let t=await this._requestFeatureFlagDefinitions();if(t&&t.status===401)throw new j2o("Your personalApiKey is invalid. Are you sure you're not using your Project API key? More information: https://posthog.com/docs/api/overview");if(t&&t.status!==200)return;let r=await t.json();"flags"in r||this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`)),this.featureFlags=r.flags||[],this.featureFlagsByKey=this.featureFlags.reduce((i,n)=>(i[n.key]=n,i),{}),this.groupTypeMapping=r.group_type_mapping||{},this.cohorts=r.cohorts||[],this.loadedSuccessfullyOnce=!0}catch(t){t instanceof j2o&&this.onError?.(t)}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r={method:"GET",headers:{...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`}},i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=xWp(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}};function CWp(e,t,r=""){let i=(0,zWp.createHash)();return i.update(`${e}.${t}${r}`),parseInt(i.digest("hex").slice(0,15),16)/DVD}function NWp(e,t,r){let i=e.key,n=e.value,a=e.operator||"exact";if(i in t){if(a==="is_not_set")throw new Z2("Operator is_not_set is not supported")}else throw new Z2(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!EVD.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function l(s,o){return Array.isArray(s)?s.map(c=>String(c).toLowerCase()).includes(String(o).toLowerCase()):String(s).toLowerCase()===String(o).toLowerCase()}function d(s,o,c){if(c==="gt")return s>o;if(c==="gte")return s>=o;if(c==="lt")return s<o;if(c==="lte")return s<=o;throw new Error(`Invalid operator: ${c}`)}switch(a){case"exact":return l(n,u);case"is_not":return!l(n,u);case"is_set":return i in t;case"icontains":return String(u).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(u).toLowerCase().includes(String(n).toLowerCase());case"regex":return BWp(String(n))&&String(u).match(String(n))!==null;case"not_regex":return BWp(String(n))&&String(u).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let s=typeof n=="number"?n:null;if(typeof n=="string")try{s=parseFloat(n)}catch{}return s!=null&&u!=null?typeof u=="string"?d(u,String(n),a):d(u,s,a):d(String(u),String(n),a)}case"is_date_after":case"is_date_before":{let s=MVD(String(n));if(s==null&&(s=IWp(n)),s==null)throw new Z2(`Invalid date: ${n}`);let o=IWp(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new Z2(`Unknown operator: ${a}`)}}function FWp(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new Z2("can't match cohort without a given cohort property value");let a=r[n];return LWp(a,t,r,i)}function LWp(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let u=!1;if("values"in a[0]){for(let l of a)try{let d=LWp(l,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof Z2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new Z2("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let l of a)try{let d;l.type==="cohort"?d=FWp(l,t,r,i):d=NWp(l,t);let s=l.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof Z2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new Z2("can't match cohort without a given cohort property value");return n==="AND"}}function BWp(e){try{return new RegExp(e),!0}catch{return!1}}function IWp(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new Z2(`${e} is in an invalid date format`)}else throw new Z2(`The date provided ${e} must be a string, number, or date object`)}function MVD(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(r){if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let a=r.groups.interval;if(a=="h")i.setUTCHours(i.getUTCHours()-n);else if(a=="d")i.setUTCDate(i.getUTCDate()-n);else if(a=="w")i.setUTCDate(i.getUTCDate()-n*7);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else if(a=="y")i.setUTCFullYear(i.getUTCFullYear()-n);else return null;return i}else return null}var AVD=30*1e3,qVD=50*1e3,a7n=class extends Qtc{constructor(t,r={}){super(t,r),this._memoryStorage=new Jtc,this.options=r,r.personalApiKey&&(this.featureFlagsPoller=new Ytc({pollingInterval:typeof r.featureFlagsPollingInterval=="number"?r.featureFlagsPollingInterval:AVD,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:i=>{this._events.emit("error",i)},customHeaders:this.getCustomHeaders()})),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||qVD}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):RWp(t,r)}getLibraryId(){return"posthog-node"}getLibraryVersion(){return bVD}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture({distinctId:t,event:r,properties:i,groups:n,sendFeatureFlags:a,timestamp:u,disableGeoip:l,uuid:d}){let s=b=>{super.captureStateless(t,r,b,{timestamp:u,disableGeoip:l,uuid:d})},o=(b,g,O)=>super.getFeatureFlagsStateless(b,g,void 0,void 0,O),c=Promise.resolve().then(async()=>{if(a)return await o(t,n,l);if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let b={};for(let[g,O]of Object.entries(n||{}))b[g]=String(O);return await this.getAllFlags(t,{groups:b,disableGeoip:l,onlyEvaluateLocally:!0})}return{}}).then(b=>{let g={};if(b)for(let[m,P]of Object.entries(b))g[`$feature/${m}`]=P;let O=Object.keys(b||{}).filter(m=>b?.[m]!==!1);return O.length>0&&(g.$active_feature_flags=O),g}).catch(()=>({})).then(b=>{s({...b,...i,$groups:n})});this.addPendingPromise(c)}identify({distinctId:t,properties:r,disableGeoip:i}){let n=r?.$set||r;super.identifyStateless(t,{$set:n},{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:u,sendFeatureFlagEvents:l,personProperties:d,groupProperties:s}=i||{},o=this.addLocalPersonAndGroupProperties(r,n,d,s);d=o.allPersonProperties,s=o.allGroupProperties,u==null&&(u=!1),l==null&&(l=!0);let c=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),b=c!==void 0;!b&&!u&&(c=await super.getFeatureFlagStateless(t,r,n,d,s,a));let g=`${t}_${c}`;return l&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(g))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(g):this.distinctIdHasSentFlagCalls[r]=[g],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:c,locally_evaluated:b,[`$feature/${t}`]:c},groups:n,disableGeoip:a})),c}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:u}=n||{},{onlyEvaluateLocally:l,sendFeatureFlagEvents:d,personProperties:s,groupProperties:o}=n||{},c=this.addLocalPersonAndGroupProperties(r,a,s,o);s=c.allPersonProperties,o=c.allGroupProperties;let b;return i||(i=await this.getFeatureFlag(t,r,{...n,onlyEvaluateLocally:!0})),i&&(b=await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(t,i)),l==null&&(l=!1),d==null&&(d=!0),l==null&&(l=!1),!(b!==void 0)&&!l&&(b=await super.getFeatureFlagPayloadStateless(t,r,a,s,o,u)),b}async isFeatureEnabled(t,r,i){let n=await this.getFeatureFlag(t,r,i);if(n!==void 0)return!!n||!1}async getAllFlags(t,r){return(await this.getAllFlagsAndPayloads(t,r)).featureFlags}async getAllFlagsAndPayloads(t,r){let{groups:i,disableGeoip:n}=r||{},{onlyEvaluateLocally:a,personProperties:u,groupProperties:l}=r||{},d=this.addLocalPersonAndGroupProperties(t,i,u,l);u=d.allPersonProperties,l=d.allGroupProperties,a==null&&(a=!1);let s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,u,l),o={},c={},b=!0;if(s&&(o=s.response,c=s.payloads,b=s.fallbackToDecide),b&&!a){let g=await super.getFeatureFlagsAndPayloadsStateless(t,i,u,l,n);o={...o,...g.flags||{}},c={...c,...g.payloads||{}}}return{featureFlags:o,featureFlagPayloads:c}}groupIdentify({groupType:t,groupKey:r,properties:i,distinctId:n,disableGeoip:a}){super.groupIdentifyStateless(t,r,i,{disableGeoip:a},n)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}async shutdown(t){return this.featureFlagsPoller?.stopPoller(),super.shutdown(t)}addLocalPersonAndGroupProperties(t,r,i,n){let a={distinct_id:t,...i||{}},u={};if(r)for(let l of Object.keys(r))u[l]={$group_key:r[l],...n?.[l]||{}};return{allPersonProperties:a,allGroupProperties:u}}},Xtc=class e{constructor(t,r,i,n){this.posthog=t,this.posthogHost=r,this.organization=i,this.prefix=n,this.name="posthog-node",this.posthogHost=t.options.host??"https://us.i.posthog.com"}setupOnce(t,r){t(i=>{if(i.exception?.values===void 0||i.exception.values.length===0)return i;i.tags||(i.tags={});let n=r(),a=i.tags[e.POSTHOG_ID_TAG];if(a===void 0)return i;i.tags["PostHog Person URL"]=new URL(`/person/${a}`,this.posthogHost).toString();let u={$exception_message:i.exception.values[0]?.value,$exception_type:i.exception.values[0]?.type,$exception_personURL:i.tags["PostHog Person URL"],$sentry_event_id:i.event_id,$sentry_exception:i.exception,$sentry_exception_message:i.exception.values[0]?.value,$sentry_exception_type:i.exception.values[0]?.type,$sentry_tags:i.tags},l=n.getClient()?.getDsn()?.projectId;return this.organization!==void 0&&l!==void 0&&i.event_id!==void 0&&(u.$sentry_url=`${this.prefix??"https://sentry.io/organizations"}/${this.organization}/issues/?project=${l}&query=${i.event_id}`),this.posthog.capture({event:"$exception",distinctId:a,properties:u}),i})}};Xtc.POSTHOG_ID_TAG="posthog_distinct_id";var w2o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new a7n(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.64.7",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var NAa=class{async sendEvent(){}async identify(){}async flush(){}};var o7n=require("fs/promises"),HWp=require("os"),$Wp=require("path");var UWp=ci(require("crypto")),D2o=new Uint8Array(256),S2o=D2o.length;function Ztc(){return S2o>D2o.length-16&&(UWp.default.randomFillSync(D2o),S2o=0),D2o.slice(S2o,S2o+=16)}var WW=[];for(let e=0;e<256;++e)WW.push((e+256).toString(16).slice(1));function VWp(e,t=0){return WW[e[t+0]]+WW[e[t+1]]+WW[e[t+2]]+WW[e[t+3]]+"-"+WW[e[t+4]]+WW[e[t+5]]+"-"+WW[e[t+6]]+WW[e[t+7]]+"-"+WW[e[t+8]]+WW[e[t+9]]+"-"+WW[e[t+10]]+WW[e[t+11]]+WW[e[t+12]]+WW[e[t+13]]+WW[e[t+14]]+WW[e[t+15]]}var WWp=ci(require("crypto")),ktc={randomUUID:WWp.default.randomUUID};function TVD(e,t,r){if(ktc.randomUUID&&!t&&!e)return ktc.randomUUID();e=e||{};let i=e.random||(e.rng||Ztc)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){r=r||0;for(let n=0;n<16;++n)t[r+n]=i[n];return t}return VWp(i)}var zae=TVD;var CVD="id",BVD=".fern",FAa=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new a7n(r),this.userId=t==null?void 0:uJs(t)}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"0.64.7",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Vu(hl.of((0,HWp.homedir)()),Qa.of(BVD),Qa.of(CVD));await Sf(t)||(await(0,o7n.mkdir)((0,$Wp.dirname)(t),{recursive:!0}),await(0,o7n.writeFile)(t,zae())),this.persistedDistinctId=(await(0,o7n.readFile)(t)).toString()}return this.persistedDistinctId}};var erc;async function u7n(){return erc==null&&(erc=await IVD()),erc}async function IVD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new NAa;let r=await MRo();return r!=null?new FAa({token:r,posthogApiKey:e}):await JNn()!=null?new w2o({posthogApiKey:e}):new FAa({token:void 0,posthogApiKey:e})}catch{return new NAa}}function LAa(e,t){return function(){return e.apply(t,arguments)}}var{toString:zVD}=Object.prototype,{getPrototypeOf:rrc}=Object,M2o=(e=>t=>{let r=zVD.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),BWt=e=>(e=e.toLowerCase(),t=>M2o(t)===e),A2o=e=>t=>typeof t===e,{isArray:s7n}=Array,UAa=A2o("undefined");function xVD(e){return e!==null&&!UAa(e)&&e.constructor!==null&&!UAa(e.constructor)&&uMe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var QWp=BWt("ArrayBuffer");function RVD(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&QWp(e.buffer),t}var NVD=A2o("string"),uMe=A2o("function"),JWp=A2o("number"),q2o=e=>e!==null&&typeof e=="object",FVD=e=>e===!0||e===!1,E2o=e=>{if(M2o(e)!=="object")return!1;let t=rrc(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},LVD=BWt("Date"),UVD=BWt("File"),VVD=BWt("Blob"),WVD=BWt("FileList"),HVD=e=>q2o(e)&&uMe(e.pipe),$VD=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||uMe(e.append)&&((t=M2o(e))==="formdata"||t==="object"&&uMe(e.toString)&&e.toString()==="[object FormData]"))},GVD=BWt("URLSearchParams"),[QVD,JVD,KVD,YVD]=["ReadableStream","Request","Response","Headers"].map(BWt),XVD=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function VAa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),s7n(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{let a=r?Object.getOwnPropertyNames(e):Object.keys(e),u=a.length,l;for(i=0;i<u;i++)l=a[i],t.call(null,e[l],l,e)}}function KWp(e,t){t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var lGi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,YWp=e=>!UAa(e)&&e!==lGi;function trc(){let{caseless:e}=YWp(this)&&this||{},t={},r=(i,n)=>{let a=e&&KWp(t,n)||n;E2o(t[a])&&E2o(i)?t[a]=trc(t[a],i):E2o(i)?t[a]=trc({},i):s7n(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&VAa(arguments[i],r);return t}var ZVD=(e,t,r,{allOwnKeys:i}={})=>(VAa(t,(n,a)=>{r&&uMe(n)?e[a]=LAa(n,r):e[a]=n},{allOwnKeys:i}),e),kVD=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),eWD=(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},tWD=(e,t,r,i)=>{let n,a,u,l={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)u=n[a],(!i||i(u,e,t))&&!l[u]&&(t[u]=e[u],l[u]=!0);e=r!==!1&&rrc(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},rWD=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let i=e.indexOf(t,r);return i!==-1&&i===r},iWD=e=>{if(!e)return null;if(s7n(e))return e;let t=e.length;if(!JWp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},nWD=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&rrc(Uint8Array)),aWD=(e,t)=>{let i=(e&&e[Symbol.iterator]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},oWD=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},uWD=BWt("HTMLFormElement"),sWD=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),GWp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),cWD=BWt("RegExp"),XWp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};VAa(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},lWD=e=>{XWp(e,(t,r)=>{if(uMe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(uMe(i)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},fWD=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return s7n(e)?i(e):i(String(e).split(t)),r},dWD=()=>{},pWD=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function _WD(e){return!!(e&&uMe(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var hWD=e=>{let t=new Array(10),r=(i,n)=>{if(q2o(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=s7n(i)?[]:{};return VAa(i,(u,l)=>{let d=r(u,n+1);!UAa(d)&&(a[l]=d)}),t[n]=void 0,a}}return i};return r(e,0)},yWD=BWt("AsyncFunction"),vWD=e=>e&&(q2o(e)||uMe(e))&&uMe(e.then)&&uMe(e.catch),ZWp=((e,t)=>e?setImmediate:t?((r,i)=>(lGi.addEventListener("message",({source:n,data:a})=>{n===lGi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),lGi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",uMe(lGi.postMessage)),bWD=typeof queueMicrotask<"u"?queueMicrotask.bind(lGi):typeof process<"u"&&process.nextTick||ZWp,_s={isArray:s7n,isArrayBuffer:QWp,isBuffer:xVD,isFormData:$VD,isArrayBufferView:RVD,isString:NVD,isNumber:JWp,isBoolean:FVD,isObject:q2o,isPlainObject:E2o,isReadableStream:QVD,isRequest:JVD,isResponse:KVD,isHeaders:YVD,isUndefined:UAa,isDate:LVD,isFile:UVD,isBlob:VVD,isRegExp:cWD,isFunction:uMe,isStream:HVD,isURLSearchParams:GVD,isTypedArray:nWD,isFileList:WVD,forEach:VAa,merge:trc,extend:ZVD,trim:XVD,stripBOM:kVD,inherits:eWD,toFlatObject:tWD,kindOf:M2o,kindOfTest:BWt,endsWith:rWD,toArray:iWD,forEachEntry:aWD,matchAll:oWD,isHTMLForm:uWD,hasOwnProperty:GWp,hasOwnProp:GWp,reduceDescriptors:XWp,freezeMethods:lWD,toObjectSet:fWD,toCamelCase:sWD,noop:dWD,toFiniteNumber:pWD,findKey:KWp,global:lGi,isContextDefined:YWp,isSpecCompliantForm:_WD,toJSONObject:hWD,isAsyncFn:yWD,isThenable:vWD,setImmediate:ZWp,asap:bWD};function c7n(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}_s.inherits(c7n,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:_s.toJSONObject(this.config),code:this.code,status:this.status}}});var kWp=c7n.prototype,eHp={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{eHp[e]={value:e}});Object.defineProperties(c7n,eHp);Object.defineProperty(kWp,"isAxiosError",{value:!0});c7n.from=(e,t,r,i,n,a)=>{let u=Object.create(kWp);return _s.toFlatObject(e,u,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),c7n.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var Rp=c7n;var tHp=ci(swa(),1),T2o=tHp.default;function irc(e){return _s.isPlainObject(e)||_s.isArray(e)}function iHp(e){return _s.endsWith(e,"[]")?e.slice(0,-2):e}function rHp(e,t,r){return e?e.concat(t).map(function(n,a){return n=iHp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function gWD(e){return _s.isArray(e)&&!e.some(irc)}var OWD=_s.toFlatObject(_s,{},null,function(t){return/^is[A-Z]/.test(t)});function mWD(e,t,r){if(!_s.isObject(e))throw new TypeError("target must be an object");t=t||new(T2o||FormData),r=_s.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,P){return!_s.isUndefined(P[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&_s.isSpecCompliantForm(t);if(!_s.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(_s.isDate(O))return O.toISOString();if(!d&&_s.isBlob(O))throw new Rp("Blob is not supported. Use a Buffer instead.");return _s.isArrayBuffer(O)||_s.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,P){let E=O;if(O&&!P&&typeof O=="object"){if(_s.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(_s.isArray(O)&&gWD(O)||(_s.isFileList(O)||_s.endsWith(m,"[]"))&&(E=_s.toArray(O)))return m=iHp(m),E.forEach(function(M,D){!(_s.isUndefined(M)||M===null)&&t.append(u===!0?rHp([m],D,a):u===null?m:m+"[]",s(M))}),!1}return irc(O)?!0:(t.append(rHp(P,m,a),s(O)),!1)}let c=[],b=Object.assign(OWD,{defaultVisitor:o,convertValue:s,isVisitable:irc});function g(O,m){if(!_s.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),_s.forEach(O,function(E,q){(!(_s.isUndefined(E)||E===null)&&n.call(t,E,_s.isString(q)?q.trim():q,m,b))===!0&&g(E,m?m.concat(q):[q])}),c.pop()}}if(!_s.isObject(e))throw new TypeError("data must be an object");return g(e),t}var XDi=mWD;function nHp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function aHp(e,t){this._pairs=[],e&&XDi(e,this,t)}var oHp=aHp.prototype;oHp.append=function(t,r){this._pairs.push([t,r])};oHp.toString=function(t){let r=t?function(i){return t.call(this,i,nHp)}:nHp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var uHp=aHp;function PWD(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function fGi(e,t,r){if(!t)return e;let i=r&&r.encode||PWD;_s.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=_s.isURLSearchParams(t)?t.toString():new uHp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var nrc=class{constructor(){this.handlers=[]}use(t,r,i){return this.handlers.push({fulfilled:t,rejected:r,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){_s.forEach(this.handlers,function(i){i!==null&&t(i)})}},arc=nrc;var l7n={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var fHp=ci(require("crypto"),1);var sHp=ci(require("url"),1),cHp=sHp.default.URLSearchParams;var orc="abcdefghijklmnopqrstuvwxyz",lHp="0123456789",dHp={DIGIT:lHp,ALPHA:orc,ALPHA_DIGIT:orc+orc.toUpperCase()+lHp},jWD=(e=16,t=dHp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);fHp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},pHp={isNode:!0,classes:{URLSearchParams:cHp,FormData:T2o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:dHp,generateString:jWD,protocols:["http","https","file","data"]};var crc={};jo(crc,{hasBrowserEnv:()=>src,hasStandardBrowserEnv:()=>wWD,hasStandardBrowserWebWorkerEnv:()=>SWD,navigator:()=>urc,origin:()=>DWD});var src=typeof window<"u"&&typeof document<"u",urc=typeof navigator=="object"&&navigator||void 0,wWD=src&&(!urc||["ReactNative","NativeScript","NS"].indexOf(urc.product)<0),SWD=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",DWD=src&&window.location.href||"http://localhost";var cA={...crc,...pHp};function lrc(e,t){return XDi(e,new cA.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return cA.isNode&&_s.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function EWD(e){return _s.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function MWD(e){let t={},r=Object.keys(e),i,n=r.length,a;for(i=0;i<n;i++)a=r[i],t[a]=e[a];return t}function AWD(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let l=Number.isFinite(+u),d=a>=r.length;return u=!u&&_s.isArray(n)?n.length:u,d?(_s.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!_s.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&_s.isArray(n[u])&&(n[u]=MWD(n[u])),!l)}if(_s.isFormData(e)&&_s.isFunction(e.entries)){let r={};return _s.forEachEntry(e,(i,n)=>{t(EWD(i),n,r,0)}),r}return null}var C2o=AWD;function qWD(e,t,r){if(_s.isString(e))try{return(t||JSON.parse)(e),_s.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var frc={transitional:l7n,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=_s.isObject(t);if(a&&_s.isHTMLForm(t)&&(t=new FormData(t)),_s.isFormData(t))return n?JSON.stringify(C2o(t)):t;if(_s.isArrayBuffer(t)||_s.isBuffer(t)||_s.isStream(t)||_s.isFile(t)||_s.isBlob(t)||_s.isReadableStream(t))return t;if(_s.isArrayBufferView(t))return t.buffer;if(_s.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return lrc(t,this.formSerializer).toString();if((l=_s.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return XDi(l?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),qWD(t)):t}],transformResponse:[function(t){let r=this.transitional||frc.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(_s.isResponse(t)||_s.isReadableStream(t))return t;if(t&&_s.isString(t)&&(i&&!this.responseType||n)){let u=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(l){if(u)throw l.name==="SyntaxError"?Rp.from(l,Rp.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:cA.classes.FormData,Blob:cA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};_s.forEach(["delete","get","head","post","put","patch"],e=>{frc.headers[e]={}});var f7n=frc;var TWD=_s.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),_Hp=e=>{let t={},r,i,n;return e&&e.split(`
1707
+ `}write(t){let r=t.split(/\n/);this.height=r.length,this.rl.setPrompt(r.at(-1)),this.rl.output.rows===0&&this.rl.output.columns===0&&M4o(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var mVp=ci(_Vp(),1),PVp=ci(nks(),1),jVp=ci(gVp(),1),Uq=ci(aMe(),1),wVp=ci(fMa(),1);var r2o=ci(aMe(),1),OVp=ci(fMa(),1),i2o=function(e,t,r){return typeof e[t]!="function"?(0,r2o.of)(e):(0,r2o.from)((0,OVp.default)(e[t])(r).then(i=>(e[t]=i,e)))};var wAa={isPlainObject:mVp.default,set:jVp.default,get:PVp.default},Z3n=class extends aGi{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=wAa.isPlainObject(r)?{...r}:{},wAa.isPlainObject(t)&&(t=Object.values(t).every(n=>wAa.isPlainObject(n)&&n.name===void 0)?Object.entries(t).map(([n,a])=>({name:n,...a})):[t]);let i=Array.isArray(t)?(0,Uq.from)(t):t;return this.process=i.pipe((0,Uq.concatMap)(this.processQuestion.bind(this)),(0,Uq.publish)()),this.process.connect(),this.process.pipe((0,Uq.reduce)((n,a)=>(wAa.set(n,a.name,a.answer),n),this.answers)).toPromise(Promise).then(this.onCompletion.bind(this),this.onError.bind(this))}onCompletion(){return this.close(),this.answers}onError(t){return this.close(),Promise.reject(t)}processQuestion(t){return t={...t},(0,Uq.defer)(()=>(0,Uq.of)(t).pipe((0,Uq.concatMap)(this.setDefaultType.bind(this)),(0,Uq.concatMap)(this.filterIfRunnable.bind(this)),(0,Uq.concatMap)(()=>i2o(t,"message",this.answers)),(0,Uq.concatMap)(()=>i2o(t,"default",this.answers)),(0,Uq.concatMap)(()=>i2o(t,"choices",this.answers)),(0,Uq.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,Uq.defer)(()=>(0,Uq.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,Uq.defer)(()=>(0,Uq.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&wAa.get(this.answers,t.name)!==void 0)return(0,Uq.empty)();if(t.when===!1)return(0,Uq.empty)();if(typeof t.when!="function")return(0,Uq.of)(t);let{answers:r}=this;return(0,Uq.defer)(()=>(0,Uq.from)((0,wVp.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,Uq.filter)(i=>i!=null)))}};function SVp(e){let t=function(r,i){let n;try{n=new Z3n(t.prompts,e)}catch(u){return Promise.reject(u)}let a=n.run(r,i);return a.ui=n,a};return t.prompts={},t.registerPrompt=function(r,i){return t.prompts[r]=i,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",nAa),this.registerPrompt("input",Y$i),this.registerPrompt("number",aAa),this.registerPrompt("confirm",oAa),this.registerPrompt("rawlist",uAa),this.registerPrompt("expand",sAa),this.registerPrompt("checkbox",cAa),this.registerPrompt("password",lAa),this.registerPrompt("editor",OAa)},t.restoreDefaultPrompts(),t}var utc=SVp();function W9D(e,t){utc.registerPrompt(e,t)}function H9D(){utc.restoreDefaultPrompts()}var $9D={prompt:utc,ui:{BottomBar:jAa,Prompt:Z3n},createPromptModule:SVp,registerPrompt:W9D,restoreDefaultPrompts:H9D,Separator:qae},n2o=$9D;var zWp=ci(DVp()),bVD="4.2.1",CWt;(function(e){e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay"})(CWt||(CWt={}));function gVD(e,t){if(!e)throw new Error(t)}function OVD(e){return e?.replace(/\/+$/,"")}async function mVD(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(n=>setTimeout(n,t.retryDelay));try{return await e()}catch(n){if(r=n,!t.retryCheck(n))throw n}}throw r}function PVD(){return new Date().getTime()}function EWp(){return new Date().toISOString()}function xWp(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var zAa=String.fromCharCode,MWp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",g2o={};function jVD(e,t){if(!g2o[e]){g2o[e]={};for(let r=0;r<e.length;r++)g2o[e][e.charAt(r)]=r}return g2o[e][t]}var xAa={compressToBase64:function(e){if(e==null)return"";let t=xAa._compress(e,6,function(r){return MWp.charAt(r)});switch(t.length%4){default:case 0:return t;case 1:return t+"===";case 2:return t+"==";case 3:return t+"="}},decompressFromBase64:function(e){return e==null?"":e==""?null:xAa._decompress(e.length,32,function(t){return jVD(MWp,e.charAt(t))})},compress:function(e){return xAa._compress(e,16,function(t){return zAa(t)})},_compress:function(e,t,r){if(e==null)return"";let i={},n={},a=[],u,l,d="",s="",o="",c=2,b=3,g=2,O=0,m=0,P;for(P=0;P<e.length;P+=1)if(d=e.charAt(P),Object.prototype.hasOwnProperty.call(i,d)||(i[d]=b++,n[d]=!0),s=o+d,Object.prototype.hasOwnProperty.call(i,s))o=s;else{if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<g;u++)O=O<<1,m==t-1?(m=0,a.push(r(O)),O=0):m++;for(l=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}else{for(l=1,u=0;u<g;u++)O=O<<1|l,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=0;for(l=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}c--,c==0&&(c=Math.pow(2,g),g++),delete n[o]}else for(l=i[o],u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;c--,c==0&&(c=Math.pow(2,g),g++),i[s]=b++,o=String(d)}if(o!==""){if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<g;u++)O=O<<1,m==t-1?(m=0,a.push(r(O)),O=0):m++;for(l=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}else{for(l=1,u=0;u<g;u++)O=O<<1|l,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=0;for(l=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}c--,c==0&&(c=Math.pow(2,g),g++),delete n[o]}else for(l=i[o],u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;c--,c==0&&(c=Math.pow(2,g),g++)}for(l=2,u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;for(;;)if(O=O<<1,m==t-1){a.push(r(O));break}else m++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:xAa._decompress(e.length,32768,function(t){return e.charCodeAt(t)})},_decompress:function(e,t,r){let i=[],n=[],a={val:r(0),position:t,index:1},u=4,l=4,d=3,s="",o,c,b,g,O,m,P;for(o=0;o<3;o+=1)i[o]=o;for(b=0,O=Math.pow(2,2),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;P=zAa(b);break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;P=zAa(b);break;case 2:return""}for(i[3]=P,c=P,n.push(P);;){if(a.index>e)return"";for(b=0,O=Math.pow(2,d),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(P=b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=zAa(b),P=l-1,u--;break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=zAa(b),P=l-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,d),d++),i[P])s=i[P];else if(P===l)s=c+c.charAt(0);else return null;n.push(s),i[l++]=c+s.charAt(0),u--,c=s,u==0&&(u=Math.pow(2,d),d++)}}},$tc=class{constructor(){this.events={},this.events={}}on(t,r){return this.events[t]||(this.events[t]=[]),this.events[t].push(r),()=>{this.events[t]=this.events[t].filter(i=>i!==r)}}emit(t,r){for(let i of this.events[t]||[])i(r);for(let i of this.events["*"]||[])i(t,r)}};var O2o="0123456789abcdef",m2o=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length!==16)throw new TypeError("not 128-bit length");return new e(t)}static fromFieldsV7(t,r,i,n){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||!Number.isInteger(n)||t<0||r<0||i<0||n<0||t>0xffffffffffff||r>4095||i>1073741823||n>4294967295)throw new RangeError("invalid field value");let a=new Uint8Array(16);return a[0]=t/2**40,a[1]=t/2**32,a[2]=t/2**24,a[3]=t/2**16,a[4]=t/2**8,a[5]=t,a[6]=112|r>>>8,a[7]=r,a[8]=128|i>>>24,a[9]=i>>>16,a[10]=i>>>8,a[11]=i,a[12]=n>>>24,a[13]=n>>>16,a[14]=n>>>8,a[15]=n,new e(a)}static parse(t){let r;switch(t.length){case 32:r=/^[0-9a-f]{32}$/i.exec(t)?.[0];break;case 36:r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;case 38:r=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(t)?.slice(1,6).join("");break;case 45:r=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break}if(r){let i=new Uint8Array(16);for(let n=0;n<16;n+=4){let a=parseInt(r.substring(2*n,2*n+8),16);i[n+0]=a>>>24,i[n+1]=a>>>16,i[n+2]=a>>>8,i[n+3]=a}return new e(i)}else throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=O2o.charAt(this.bytes[r]>>>4),t+=O2o.charAt(this.bytes[r]&15),(r===3||r===5||r===7||r===9)&&(t+="-");return t}toHex(){let t="";for(let r=0;r<this.bytes.length;r++)t+=O2o.charAt(this.bytes[r]>>>4),t+=O2o.charAt(this.bytes[r]&15);return t}toJSON(){return this.toString()}getVariant(){let t=this.bytes[8]>>>4;if(t<0)throw new Error("unreachable");if(t<=7)return this.bytes.every(r=>r===0)?"NIL":"VAR_0";if(t<=11)return"VAR_10";if(t<=13)return"VAR_110";if(t<=15)return this.bytes.every(r=>r===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new e(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(let r=0;r<16;r++){let i=this.bytes[r]-t.bytes[r];if(i!==0)return Math.sign(i)}return 0}},Gtc=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??wVD()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let i=this.generateOrAbortCore(t,r);return i===void 0&&(this.timestamp=0,i=this.generateOrAbortCore(t,r)),i}generateOrAbortCore(t,r){if(!Number.isInteger(t)||t<1||t>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(t>this.timestamp)this.timestamp=t,this.resetCounter();else if(t+r>=this.timestamp)this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter());else return;return m2o.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=this.random.nextUint32()*1024+(this.random.nextUint32()&1023)}generateV4(){let t=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return t[6]=64|t[6]>>>4,t[8]=128|t[8]>>>2,m2o.ofInner(t)}},wVD=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),AWp,qWp=()=>SVD().toString(),SVD=()=>(AWp||(AWp=new Gtc)).generate(),P2o=class extends Error{constructor(t){super("HTTP error while fetching PostHog: "+t.status),this.response=t,this.name="PostHogFetchHttpError"}},RAa=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};function TWp(e){return typeof e=="object"&&(e instanceof P2o||e instanceof RAa)}var Qtc=class{constructor(t,r){this.flushPromise=null,this.disableGeoip=!0,this.historicalMigration=!1,this.disabled=!1,this.defaultOptIn=!0,this.pendingPromises={},this._events=new $tc,this._isInitialized=!1,gVD(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=OVD(r?.host||"https://us.i.posthog.com"),this.flushAt=r?.flushAt?Math.max(r?.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,r?.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,r?.maxQueueSize??1e3),this.flushInterval=r?.flushInterval??1e4,this.captureMode=r?.captureMode||"json",this.defaultOptIn=r?.defaultOptIn??!0,this._retryOptions={retryCount:r?.fetchRetryCount??3,retryDelay:r?.fetchRetryDelay??3e3,retryCheck:TWp},this.requestTimeout=r?.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r?.featureFlagsRequestTimeoutMs??3e3,this.disableGeoip=r?.disableGeoip??!0,this.disabled=r?.disabled??!1,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0}logMsgIfDebug(t){this.isDebug&&t()}wrap(t){if(this.disabled){this.logMsgIfDebug(()=>console.warn("[PostHog] The client is disabled"));return}if(this._isInitialized)return t();this._initPromise.then(()=>t())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(CWt.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(CWt.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(CWt.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(i,n)=>console.log("PostHog Debug",i,n));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}buildPayload(t){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(t){let r=qWp();return this.pendingPromises[r]=t,t.catch(()=>{}).finally(()=>{delete this.pendingPromises[r]}),t}identifyStateless(t,r,i){this.wrap(()=>{let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",n,i)})}captureStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({distinct_id:t,event:r,properties:i});this.enqueue("capture",a,n)})}aliasStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});this.enqueue("alias",a,n)})}groupIdentifyStateless(t,r,i,n,a,u){this.wrap(()=>{let l=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:i||{},...u||{}}});this.enqueue("capture",l,n)})}async getDecide(t,r={},i={},n={},a={}){await this._initPromise;let u=`${this.host}/decide/?v=3`,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify({token:this.apiKey,distinct_id:t,groups:r,person_properties:i,group_properties:n,...a})};return this.fetchWithRetry(u,l,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(d=>d.json()).catch(d=>{this._events.emit("error",d)})}async getFeatureFlagStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagsStateless(r,i,n,a,u);if(!l)return;let d=l[t];return d===void 0&&(d=!1),d}async getFeatureFlagPayloadStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagPayloadsStateless(r,i,n,a,u);if(!l)return;let d=l[t];return d===void 0?null:d}async getFeatureFlagPayloadsStateless(t,r={},i={},n={},a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a)).payloads}_parsePayload(t){try{return JSON.parse(t)}catch{return t}}async getFeatureFlagsStateless(t,r={},i={},n={},a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a)).flags}async getFeatureFlagsAndPayloadsStateless(t,r={},i={},n={},a){await this._initPromise;let u={};(a??this.disableGeoip)&&(u.geoip_disable=!0);let l=await this.getDecide(t,r,i,n,u),d=l?.featureFlags,s=l?.featureFlagPayloads,o=s;return s&&(o=Object.fromEntries(Object.entries(s).map(([c,b])=>[c,this._parsePayload(b)]))),{flags:d,payloads:o}}enqueue(t,r,i){this.wrap(()=>{if(this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");return}let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:EWp(),uuid:i?.uuid?i.uuid:qWp()};(i?.disableGeoip??this.disableGeoip)&&(n.properties||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId);let u=this.getPersistedProperty(CWt.Queue)||[];u.length>=this.maxQueueSize&&(u.shift(),this.logMsgIfDebug(()=>console.info("Queue is full, the oldest event is dropped."))),u.push({message:n}),this.setPersistedProperty(CWt.Queue,u),this._events.emit(t,n),u.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=xWp(()=>this.flushBackground(),this.flushInterval))})}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(()=>{})}async flush(){return this.flushPromise||(this.flushPromise=this._flush().finally(()=>{this.flushPromise=null}),this.addPendingPromise(this.flushPromise)),this.flushPromise}getCustomHeaders(){let t=this.getCustomUserAgent(),r={};return t&&t!==""&&(r["User-Agent"]=t),r}async _flush(){this.clearFlushTimer(),await this._initPromise;let t=this.getPersistedProperty(CWt.Queue)||[];if(!t.length)return[];let r=t.slice(0,this.maxBatchSize),i=r.map(s=>s.message),n=()=>{let s=this.getPersistedProperty(CWt.Queue)||[];this.setPersistedProperty(CWt.Queue,s.slice(r.length))},a={api_key:this.apiKey,batch:i,sent_at:EWp()};this.historicalMigration&&(a.historical_migration=!0);let u=JSON.stringify(a),l=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${PVD()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,d=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(xAa.compressToBase64(u))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:u};try{await this.fetchWithRetry(l,d)}catch(s){throw s instanceof RAa||n(),this._events.emit("error",s),s}return n(),this._events.emit("flush",i),i}async fetchWithRetry(t,r,i,n){var a;return(a=AbortSignal).timeout??(a.timeout=function(l){let d=new AbortController;return setTimeout(()=>d.abort(),l),d.signal}),await mVD(async()=>{let u=null;try{u=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(d){throw new RAa(d)}if(!(r.mode==="no-cors")&&(u.status<200||u.status>=400))throw new P2o(u);return u},{...this._retryOptions,...i})}async shutdown(t=3e4){await this._initPromise,this.clearFlushTimer();try{await Promise.all(Object.values(this.pendingPromises));let r=Date.now()+t;for(;(this.getPersistedProperty(CWt.Queue)||[]).length!==0;){await this.flush();let n=Date.now();if(r<n)break}}catch(r){if(!TWp(r))throw r;this.logMsgIfDebug(()=>console.error("Error while shutting down PostHog",r))}}},Jtc=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},Ktc=typeof fetch<"u"?fetch:typeof global.fetch<"u"?global.fetch:void 0;if(!Ktc){let e=DWp();Ktc=async(t,r)=>{let i=await e.request({url:t,headers:r.headers,method:r.method.toLowerCase(),data:r.body,signal:r.signal,validateStatus:()=>!0});return{status:i.status,text:async()=>i.data,json:async()=>i.data}}}var RWp=Ktc,DVD=1152921504606847e3,EVD=["is_not"],j2o=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},Z2=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},Ytc=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:u,...l}){this.debugMode=!1,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=i,this.host=a,this.poller=void 0,this.fetch=l.fetch||RWp,this.onError=l.onError,this.customHeaders=u,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let u,l;if(!this.loadedSuccessfullyOnce)return u;for(let d of this.featureFlags)if(t===d.key){l=d;break}if(l!==void 0)try{u=this.computeFlagLocally(l,r,i,n,a),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${u}`))}catch(d){d instanceof Z2?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${d}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return u}async computeFeatureFlagPayloadLocally(t,r){await this.loadFeatureFlags();let i;if(this.loadedSuccessfullyOnce){if(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]),i==null)return null;try{return JSON.parse(i)}catch{return i}}}async getAllFlagsAndPayloads(t,r={},i={},n={}){await this.loadFeatureFlags();let a={},u={},l=this.featureFlags.length==0;return this.featureFlags.map(async d=>{try{let s=this.computeFlagLocally(d,t,r,i,n);a[d.key]=s;let o=await this.computeFeatureFlagPayloadLocally(d.key,s);o&&(u[d.key]=o)}catch(s){s instanceof Z2||s instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${d.key}: ${s}`)),l=!0}}),{response:a,payloads:u,fallbackToDecide:l}}computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new Z2("Flag has experience continuity enabled");if(!t.active)return!1;let l=(t.filters||{}).aggregation_group_type_index;if(l!=null){let d=this.groupTypeMapping[String(l)];if(!d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${l} for feature flag ${t.key}`)),new Z2("Flag has unknown group type index");if(!(d in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let s=a[d];return this.matchFeatureFlagProperties(t,i[d],s)}else return this.matchFeatureFlagProperties(t,r,n)}matchFeatureFlagProperties(t,r,i){let n=t.filters||{},a=n.groups||[],u=!1,l,d=[...a].sort((s,o)=>{let c=!!s.variant,b=!!o.variant;return c&&b?0:c?-1:b?1:0});for(let s of d)try{if(this.isConditionMatch(t,r,s,i)){let o=s.variant,c=n.multivariate?.variants||[];o&&c.some(b=>b.key===o)?l=o:l=this.getMatchingVariant(t,r)||!0;break}}catch(o){if(o instanceof Z2)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new Z2("Can't determine if feature flag is enabled or not with given properties");return!1}isConditionMatch(t,r,i,n){let a=i.rollout_percentage,u=l=>{this.logMsgIfDebug(()=>console.warn(l))};if((i.properties||[]).length>0){for(let l of i.properties){let d=l.type,s=!1;if(d==="cohort"?s=FWp(l,n,this.cohorts,this.debugMode):s=NWp(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&CWp(t.key,r)>a/100)}getMatchingVariant(t,r){let i=CWp(t.key,r,"variant"),n=this.variantLookupTable(t).find(a=>i>=a.valueMin&&i<a.valueMax);if(n)return n.key}variantLookupTable(t){let r=[],i=0,n=0;return((t.filters||{}).multivariate?.variants||[]).forEach(l=>{n=i+l.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:l.key}),i=n}),r}async loadFeatureFlags(t=!1){(!this.loadedSuccessfullyOnce||t)&&await this._loadFeatureFlags()}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this._loadFeatureFlags(),this.pollingInterval);try{let t=await this._requestFeatureFlagDefinitions();if(t&&t.status===401)throw new j2o("Your personalApiKey is invalid. Are you sure you're not using your Project API key? More information: https://posthog.com/docs/api/overview");if(t&&t.status!==200)return;let r=await t.json();"flags"in r||this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`)),this.featureFlags=r.flags||[],this.featureFlagsByKey=this.featureFlags.reduce((i,n)=>(i[n.key]=n,i),{}),this.groupTypeMapping=r.group_type_mapping||{},this.cohorts=r.cohorts||[],this.loadedSuccessfullyOnce=!0}catch(t){t instanceof j2o&&this.onError?.(t)}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r={method:"GET",headers:{...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`}},i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=xWp(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}};function CWp(e,t,r=""){let i=(0,zWp.createHash)();return i.update(`${e}.${t}${r}`),parseInt(i.digest("hex").slice(0,15),16)/DVD}function NWp(e,t,r){let i=e.key,n=e.value,a=e.operator||"exact";if(i in t){if(a==="is_not_set")throw new Z2("Operator is_not_set is not supported")}else throw new Z2(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!EVD.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function l(s,o){return Array.isArray(s)?s.map(c=>String(c).toLowerCase()).includes(String(o).toLowerCase()):String(s).toLowerCase()===String(o).toLowerCase()}function d(s,o,c){if(c==="gt")return s>o;if(c==="gte")return s>=o;if(c==="lt")return s<o;if(c==="lte")return s<=o;throw new Error(`Invalid operator: ${c}`)}switch(a){case"exact":return l(n,u);case"is_not":return!l(n,u);case"is_set":return i in t;case"icontains":return String(u).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(u).toLowerCase().includes(String(n).toLowerCase());case"regex":return BWp(String(n))&&String(u).match(String(n))!==null;case"not_regex":return BWp(String(n))&&String(u).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let s=typeof n=="number"?n:null;if(typeof n=="string")try{s=parseFloat(n)}catch{}return s!=null&&u!=null?typeof u=="string"?d(u,String(n),a):d(u,s,a):d(String(u),String(n),a)}case"is_date_after":case"is_date_before":{let s=MVD(String(n));if(s==null&&(s=IWp(n)),s==null)throw new Z2(`Invalid date: ${n}`);let o=IWp(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new Z2(`Unknown operator: ${a}`)}}function FWp(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new Z2("can't match cohort without a given cohort property value");let a=r[n];return LWp(a,t,r,i)}function LWp(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let u=!1;if("values"in a[0]){for(let l of a)try{let d=LWp(l,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof Z2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new Z2("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let l of a)try{let d;l.type==="cohort"?d=FWp(l,t,r,i):d=NWp(l,t);let s=l.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof Z2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new Z2("can't match cohort without a given cohort property value");return n==="AND"}}function BWp(e){try{return new RegExp(e),!0}catch{return!1}}function IWp(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new Z2(`${e} is in an invalid date format`)}else throw new Z2(`The date provided ${e} must be a string, number, or date object`)}function MVD(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(r){if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let a=r.groups.interval;if(a=="h")i.setUTCHours(i.getUTCHours()-n);else if(a=="d")i.setUTCDate(i.getUTCDate()-n);else if(a=="w")i.setUTCDate(i.getUTCDate()-n*7);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else if(a=="y")i.setUTCFullYear(i.getUTCFullYear()-n);else return null;return i}else return null}var AVD=30*1e3,qVD=50*1e3,a7n=class extends Qtc{constructor(t,r={}){super(t,r),this._memoryStorage=new Jtc,this.options=r,r.personalApiKey&&(this.featureFlagsPoller=new Ytc({pollingInterval:typeof r.featureFlagsPollingInterval=="number"?r.featureFlagsPollingInterval:AVD,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:i=>{this._events.emit("error",i)},customHeaders:this.getCustomHeaders()})),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||qVD}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):RWp(t,r)}getLibraryId(){return"posthog-node"}getLibraryVersion(){return bVD}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture({distinctId:t,event:r,properties:i,groups:n,sendFeatureFlags:a,timestamp:u,disableGeoip:l,uuid:d}){let s=b=>{super.captureStateless(t,r,b,{timestamp:u,disableGeoip:l,uuid:d})},o=(b,g,O)=>super.getFeatureFlagsStateless(b,g,void 0,void 0,O),c=Promise.resolve().then(async()=>{if(a)return await o(t,n,l);if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let b={};for(let[g,O]of Object.entries(n||{}))b[g]=String(O);return await this.getAllFlags(t,{groups:b,disableGeoip:l,onlyEvaluateLocally:!0})}return{}}).then(b=>{let g={};if(b)for(let[m,P]of Object.entries(b))g[`$feature/${m}`]=P;let O=Object.keys(b||{}).filter(m=>b?.[m]!==!1);return O.length>0&&(g.$active_feature_flags=O),g}).catch(()=>({})).then(b=>{s({...b,...i,$groups:n})});this.addPendingPromise(c)}identify({distinctId:t,properties:r,disableGeoip:i}){let n=r?.$set||r;super.identifyStateless(t,{$set:n},{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:u,sendFeatureFlagEvents:l,personProperties:d,groupProperties:s}=i||{},o=this.addLocalPersonAndGroupProperties(r,n,d,s);d=o.allPersonProperties,s=o.allGroupProperties,u==null&&(u=!1),l==null&&(l=!0);let c=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),b=c!==void 0;!b&&!u&&(c=await super.getFeatureFlagStateless(t,r,n,d,s,a));let g=`${t}_${c}`;return l&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(g))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(g):this.distinctIdHasSentFlagCalls[r]=[g],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:c,locally_evaluated:b,[`$feature/${t}`]:c},groups:n,disableGeoip:a})),c}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:u}=n||{},{onlyEvaluateLocally:l,sendFeatureFlagEvents:d,personProperties:s,groupProperties:o}=n||{},c=this.addLocalPersonAndGroupProperties(r,a,s,o);s=c.allPersonProperties,o=c.allGroupProperties;let b;return i||(i=await this.getFeatureFlag(t,r,{...n,onlyEvaluateLocally:!0})),i&&(b=await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(t,i)),l==null&&(l=!1),d==null&&(d=!0),l==null&&(l=!1),!(b!==void 0)&&!l&&(b=await super.getFeatureFlagPayloadStateless(t,r,a,s,o,u)),b}async isFeatureEnabled(t,r,i){let n=await this.getFeatureFlag(t,r,i);if(n!==void 0)return!!n||!1}async getAllFlags(t,r){return(await this.getAllFlagsAndPayloads(t,r)).featureFlags}async getAllFlagsAndPayloads(t,r){let{groups:i,disableGeoip:n}=r||{},{onlyEvaluateLocally:a,personProperties:u,groupProperties:l}=r||{},d=this.addLocalPersonAndGroupProperties(t,i,u,l);u=d.allPersonProperties,l=d.allGroupProperties,a==null&&(a=!1);let s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,u,l),o={},c={},b=!0;if(s&&(o=s.response,c=s.payloads,b=s.fallbackToDecide),b&&!a){let g=await super.getFeatureFlagsAndPayloadsStateless(t,i,u,l,n);o={...o,...g.flags||{}},c={...c,...g.payloads||{}}}return{featureFlags:o,featureFlagPayloads:c}}groupIdentify({groupType:t,groupKey:r,properties:i,distinctId:n,disableGeoip:a}){super.groupIdentifyStateless(t,r,i,{disableGeoip:a},n)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}async shutdown(t){return this.featureFlagsPoller?.stopPoller(),super.shutdown(t)}addLocalPersonAndGroupProperties(t,r,i,n){let a={distinct_id:t,...i||{}},u={};if(r)for(let l of Object.keys(r))u[l]={$group_key:r[l],...n?.[l]||{}};return{allPersonProperties:a,allGroupProperties:u}}},Xtc=class e{constructor(t,r,i,n){this.posthog=t,this.posthogHost=r,this.organization=i,this.prefix=n,this.name="posthog-node",this.posthogHost=t.options.host??"https://us.i.posthog.com"}setupOnce(t,r){t(i=>{if(i.exception?.values===void 0||i.exception.values.length===0)return i;i.tags||(i.tags={});let n=r(),a=i.tags[e.POSTHOG_ID_TAG];if(a===void 0)return i;i.tags["PostHog Person URL"]=new URL(`/person/${a}`,this.posthogHost).toString();let u={$exception_message:i.exception.values[0]?.value,$exception_type:i.exception.values[0]?.type,$exception_personURL:i.tags["PostHog Person URL"],$sentry_event_id:i.event_id,$sentry_exception:i.exception,$sentry_exception_message:i.exception.values[0]?.value,$sentry_exception_type:i.exception.values[0]?.type,$sentry_tags:i.tags},l=n.getClient()?.getDsn()?.projectId;return this.organization!==void 0&&l!==void 0&&i.event_id!==void 0&&(u.$sentry_url=`${this.prefix??"https://sentry.io/organizations"}/${this.organization}/issues/?project=${l}&query=${i.event_id}`),this.posthog.capture({event:"$exception",distinctId:a,properties:u}),i})}};Xtc.POSTHOG_ID_TAG="posthog_distinct_id";var w2o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new a7n(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.64.8",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var NAa=class{async sendEvent(){}async identify(){}async flush(){}};var o7n=require("fs/promises"),HWp=require("os"),$Wp=require("path");var UWp=ci(require("crypto")),D2o=new Uint8Array(256),S2o=D2o.length;function Ztc(){return S2o>D2o.length-16&&(UWp.default.randomFillSync(D2o),S2o=0),D2o.slice(S2o,S2o+=16)}var WW=[];for(let e=0;e<256;++e)WW.push((e+256).toString(16).slice(1));function VWp(e,t=0){return WW[e[t+0]]+WW[e[t+1]]+WW[e[t+2]]+WW[e[t+3]]+"-"+WW[e[t+4]]+WW[e[t+5]]+"-"+WW[e[t+6]]+WW[e[t+7]]+"-"+WW[e[t+8]]+WW[e[t+9]]+"-"+WW[e[t+10]]+WW[e[t+11]]+WW[e[t+12]]+WW[e[t+13]]+WW[e[t+14]]+WW[e[t+15]]}var WWp=ci(require("crypto")),ktc={randomUUID:WWp.default.randomUUID};function TVD(e,t,r){if(ktc.randomUUID&&!t&&!e)return ktc.randomUUID();e=e||{};let i=e.random||(e.rng||Ztc)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){r=r||0;for(let n=0;n<16;++n)t[r+n]=i[n];return t}return VWp(i)}var zae=TVD;var CVD="id",BVD=".fern",FAa=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new a7n(r),this.userId=t==null?void 0:uJs(t)}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"0.64.8",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Vu(hl.of((0,HWp.homedir)()),Qa.of(BVD),Qa.of(CVD));await Sf(t)||(await(0,o7n.mkdir)((0,$Wp.dirname)(t),{recursive:!0}),await(0,o7n.writeFile)(t,zae())),this.persistedDistinctId=(await(0,o7n.readFile)(t)).toString()}return this.persistedDistinctId}};var erc;async function u7n(){return erc==null&&(erc=await IVD()),erc}async function IVD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new NAa;let r=await MRo();return r!=null?new FAa({token:r,posthogApiKey:e}):await JNn()!=null?new w2o({posthogApiKey:e}):new FAa({token:void 0,posthogApiKey:e})}catch{return new NAa}}function LAa(e,t){return function(){return e.apply(t,arguments)}}var{toString:zVD}=Object.prototype,{getPrototypeOf:rrc}=Object,M2o=(e=>t=>{let r=zVD.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),BWt=e=>(e=e.toLowerCase(),t=>M2o(t)===e),A2o=e=>t=>typeof t===e,{isArray:s7n}=Array,UAa=A2o("undefined");function xVD(e){return e!==null&&!UAa(e)&&e.constructor!==null&&!UAa(e.constructor)&&uMe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var QWp=BWt("ArrayBuffer");function RVD(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&QWp(e.buffer),t}var NVD=A2o("string"),uMe=A2o("function"),JWp=A2o("number"),q2o=e=>e!==null&&typeof e=="object",FVD=e=>e===!0||e===!1,E2o=e=>{if(M2o(e)!=="object")return!1;let t=rrc(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},LVD=BWt("Date"),UVD=BWt("File"),VVD=BWt("Blob"),WVD=BWt("FileList"),HVD=e=>q2o(e)&&uMe(e.pipe),$VD=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||uMe(e.append)&&((t=M2o(e))==="formdata"||t==="object"&&uMe(e.toString)&&e.toString()==="[object FormData]"))},GVD=BWt("URLSearchParams"),[QVD,JVD,KVD,YVD]=["ReadableStream","Request","Response","Headers"].map(BWt),XVD=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function VAa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),s7n(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{let a=r?Object.getOwnPropertyNames(e):Object.keys(e),u=a.length,l;for(i=0;i<u;i++)l=a[i],t.call(null,e[l],l,e)}}function KWp(e,t){t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var lGi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,YWp=e=>!UAa(e)&&e!==lGi;function trc(){let{caseless:e}=YWp(this)&&this||{},t={},r=(i,n)=>{let a=e&&KWp(t,n)||n;E2o(t[a])&&E2o(i)?t[a]=trc(t[a],i):E2o(i)?t[a]=trc({},i):s7n(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&VAa(arguments[i],r);return t}var ZVD=(e,t,r,{allOwnKeys:i}={})=>(VAa(t,(n,a)=>{r&&uMe(n)?e[a]=LAa(n,r):e[a]=n},{allOwnKeys:i}),e),kVD=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),eWD=(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},tWD=(e,t,r,i)=>{let n,a,u,l={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)u=n[a],(!i||i(u,e,t))&&!l[u]&&(t[u]=e[u],l[u]=!0);e=r!==!1&&rrc(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},rWD=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let i=e.indexOf(t,r);return i!==-1&&i===r},iWD=e=>{if(!e)return null;if(s7n(e))return e;let t=e.length;if(!JWp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},nWD=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&rrc(Uint8Array)),aWD=(e,t)=>{let i=(e&&e[Symbol.iterator]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},oWD=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},uWD=BWt("HTMLFormElement"),sWD=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),GWp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),cWD=BWt("RegExp"),XWp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};VAa(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},lWD=e=>{XWp(e,(t,r)=>{if(uMe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(uMe(i)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},fWD=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return s7n(e)?i(e):i(String(e).split(t)),r},dWD=()=>{},pWD=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function _WD(e){return!!(e&&uMe(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var hWD=e=>{let t=new Array(10),r=(i,n)=>{if(q2o(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=s7n(i)?[]:{};return VAa(i,(u,l)=>{let d=r(u,n+1);!UAa(d)&&(a[l]=d)}),t[n]=void 0,a}}return i};return r(e,0)},yWD=BWt("AsyncFunction"),vWD=e=>e&&(q2o(e)||uMe(e))&&uMe(e.then)&&uMe(e.catch),ZWp=((e,t)=>e?setImmediate:t?((r,i)=>(lGi.addEventListener("message",({source:n,data:a})=>{n===lGi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),lGi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",uMe(lGi.postMessage)),bWD=typeof queueMicrotask<"u"?queueMicrotask.bind(lGi):typeof process<"u"&&process.nextTick||ZWp,_s={isArray:s7n,isArrayBuffer:QWp,isBuffer:xVD,isFormData:$VD,isArrayBufferView:RVD,isString:NVD,isNumber:JWp,isBoolean:FVD,isObject:q2o,isPlainObject:E2o,isReadableStream:QVD,isRequest:JVD,isResponse:KVD,isHeaders:YVD,isUndefined:UAa,isDate:LVD,isFile:UVD,isBlob:VVD,isRegExp:cWD,isFunction:uMe,isStream:HVD,isURLSearchParams:GVD,isTypedArray:nWD,isFileList:WVD,forEach:VAa,merge:trc,extend:ZVD,trim:XVD,stripBOM:kVD,inherits:eWD,toFlatObject:tWD,kindOf:M2o,kindOfTest:BWt,endsWith:rWD,toArray:iWD,forEachEntry:aWD,matchAll:oWD,isHTMLForm:uWD,hasOwnProperty:GWp,hasOwnProp:GWp,reduceDescriptors:XWp,freezeMethods:lWD,toObjectSet:fWD,toCamelCase:sWD,noop:dWD,toFiniteNumber:pWD,findKey:KWp,global:lGi,isContextDefined:YWp,isSpecCompliantForm:_WD,toJSONObject:hWD,isAsyncFn:yWD,isThenable:vWD,setImmediate:ZWp,asap:bWD};function c7n(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}_s.inherits(c7n,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:_s.toJSONObject(this.config),code:this.code,status:this.status}}});var kWp=c7n.prototype,eHp={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{eHp[e]={value:e}});Object.defineProperties(c7n,eHp);Object.defineProperty(kWp,"isAxiosError",{value:!0});c7n.from=(e,t,r,i,n,a)=>{let u=Object.create(kWp);return _s.toFlatObject(e,u,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),c7n.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var Rp=c7n;var tHp=ci(swa(),1),T2o=tHp.default;function irc(e){return _s.isPlainObject(e)||_s.isArray(e)}function iHp(e){return _s.endsWith(e,"[]")?e.slice(0,-2):e}function rHp(e,t,r){return e?e.concat(t).map(function(n,a){return n=iHp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function gWD(e){return _s.isArray(e)&&!e.some(irc)}var OWD=_s.toFlatObject(_s,{},null,function(t){return/^is[A-Z]/.test(t)});function mWD(e,t,r){if(!_s.isObject(e))throw new TypeError("target must be an object");t=t||new(T2o||FormData),r=_s.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,P){return!_s.isUndefined(P[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&_s.isSpecCompliantForm(t);if(!_s.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(_s.isDate(O))return O.toISOString();if(!d&&_s.isBlob(O))throw new Rp("Blob is not supported. Use a Buffer instead.");return _s.isArrayBuffer(O)||_s.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,P){let E=O;if(O&&!P&&typeof O=="object"){if(_s.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(_s.isArray(O)&&gWD(O)||(_s.isFileList(O)||_s.endsWith(m,"[]"))&&(E=_s.toArray(O)))return m=iHp(m),E.forEach(function(M,D){!(_s.isUndefined(M)||M===null)&&t.append(u===!0?rHp([m],D,a):u===null?m:m+"[]",s(M))}),!1}return irc(O)?!0:(t.append(rHp(P,m,a),s(O)),!1)}let c=[],b=Object.assign(OWD,{defaultVisitor:o,convertValue:s,isVisitable:irc});function g(O,m){if(!_s.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),_s.forEach(O,function(E,q){(!(_s.isUndefined(E)||E===null)&&n.call(t,E,_s.isString(q)?q.trim():q,m,b))===!0&&g(E,m?m.concat(q):[q])}),c.pop()}}if(!_s.isObject(e))throw new TypeError("data must be an object");return g(e),t}var XDi=mWD;function nHp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function aHp(e,t){this._pairs=[],e&&XDi(e,this,t)}var oHp=aHp.prototype;oHp.append=function(t,r){this._pairs.push([t,r])};oHp.toString=function(t){let r=t?function(i){return t.call(this,i,nHp)}:nHp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var uHp=aHp;function PWD(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function fGi(e,t,r){if(!t)return e;let i=r&&r.encode||PWD;_s.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=_s.isURLSearchParams(t)?t.toString():new uHp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var nrc=class{constructor(){this.handlers=[]}use(t,r,i){return this.handlers.push({fulfilled:t,rejected:r,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){_s.forEach(this.handlers,function(i){i!==null&&t(i)})}},arc=nrc;var l7n={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var fHp=ci(require("crypto"),1);var sHp=ci(require("url"),1),cHp=sHp.default.URLSearchParams;var orc="abcdefghijklmnopqrstuvwxyz",lHp="0123456789",dHp={DIGIT:lHp,ALPHA:orc,ALPHA_DIGIT:orc+orc.toUpperCase()+lHp},jWD=(e=16,t=dHp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);fHp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},pHp={isNode:!0,classes:{URLSearchParams:cHp,FormData:T2o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:dHp,generateString:jWD,protocols:["http","https","file","data"]};var crc={};jo(crc,{hasBrowserEnv:()=>src,hasStandardBrowserEnv:()=>wWD,hasStandardBrowserWebWorkerEnv:()=>SWD,navigator:()=>urc,origin:()=>DWD});var src=typeof window<"u"&&typeof document<"u",urc=typeof navigator=="object"&&navigator||void 0,wWD=src&&(!urc||["ReactNative","NativeScript","NS"].indexOf(urc.product)<0),SWD=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",DWD=src&&window.location.href||"http://localhost";var cA={...crc,...pHp};function lrc(e,t){return XDi(e,new cA.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return cA.isNode&&_s.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function EWD(e){return _s.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function MWD(e){let t={},r=Object.keys(e),i,n=r.length,a;for(i=0;i<n;i++)a=r[i],t[a]=e[a];return t}function AWD(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let l=Number.isFinite(+u),d=a>=r.length;return u=!u&&_s.isArray(n)?n.length:u,d?(_s.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!_s.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&_s.isArray(n[u])&&(n[u]=MWD(n[u])),!l)}if(_s.isFormData(e)&&_s.isFunction(e.entries)){let r={};return _s.forEachEntry(e,(i,n)=>{t(EWD(i),n,r,0)}),r}return null}var C2o=AWD;function qWD(e,t,r){if(_s.isString(e))try{return(t||JSON.parse)(e),_s.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var frc={transitional:l7n,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=_s.isObject(t);if(a&&_s.isHTMLForm(t)&&(t=new FormData(t)),_s.isFormData(t))return n?JSON.stringify(C2o(t)):t;if(_s.isArrayBuffer(t)||_s.isBuffer(t)||_s.isStream(t)||_s.isFile(t)||_s.isBlob(t)||_s.isReadableStream(t))return t;if(_s.isArrayBufferView(t))return t.buffer;if(_s.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return lrc(t,this.formSerializer).toString();if((l=_s.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return XDi(l?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),qWD(t)):t}],transformResponse:[function(t){let r=this.transitional||frc.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(_s.isResponse(t)||_s.isReadableStream(t))return t;if(t&&_s.isString(t)&&(i&&!this.responseType||n)){let u=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(l){if(u)throw l.name==="SyntaxError"?Rp.from(l,Rp.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:cA.classes.FormData,Blob:cA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};_s.forEach(["delete","get","head","post","put","patch"],e=>{frc.headers[e]={}});var f7n=frc;var TWD=_s.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),_Hp=e=>{let t={},r,i,n;return e&&e.split(`
1708
1708
  `).forEach(function(u){n=u.indexOf(":"),r=u.substring(0,n).trim().toLowerCase(),i=u.substring(n+1).trim(),!(!r||t[r]&&TWD[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var hHp=Symbol("internals");function WAa(e){return e&&String(e).trim().toLowerCase()}function B2o(e){return e===!1||e==null?e:_s.isArray(e)?e.map(B2o):String(e)}function CWD(e){let t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,i;for(;i=r.exec(e);)t[i[1]]=i[2];return t}var BWD=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function drc(e,t,r,i,n){if(_s.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!_s.isString(t)){if(_s.isString(i))return t.indexOf(i)!==-1;if(_s.isRegExp(i))return i.test(t)}}function IWD(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function zWD(e,t){let r=_s.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+r,{value:function(n,a,u){return this[i].call(this,t,n,a,u)},configurable:!0})})}var d7n=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(l,d,s){let o=WAa(d);if(!o)throw new Error("header name must be a non-empty string");let c=_s.findKey(n,o);(!c||n[c]===void 0||s===!0||s===void 0&&n[c]!==!1)&&(n[c||d]=B2o(l))}let u=(l,d)=>_s.forEach(l,(s,o)=>a(s,o,d));if(_s.isPlainObject(t)||t instanceof this.constructor)u(t,r);else if(_s.isString(t)&&(t=t.trim())&&!BWD(t))u(_Hp(t),r);else if(_s.isHeaders(t))for(let[l,d]of t.entries())a(d,l,i);else t!=null&&a(r,t,i);return this}get(t,r){if(t=WAa(t),t){let i=_s.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return CWD(n);if(_s.isFunction(r))return r.call(this,n,i);if(_s.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=WAa(t),t){let i=_s.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||drc(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(u){if(u=WAa(u),u){let l=_s.findKey(i,u);l&&(!r||drc(i,i[l],l,r))&&(delete i[l],n=!0)}}return _s.isArray(t)?t.forEach(a):a(t),n}clear(t){let r=Object.keys(this),i=r.length,n=!1;for(;i--;){let a=r[i];(!t||drc(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return _s.forEach(this,(n,a)=>{let u=_s.findKey(i,a);if(u){r[u]=B2o(n),delete r[a];return}let l=t?IWD(a):String(a).trim();l!==a&&delete r[a],r[l]=B2o(n),i[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return _s.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&_s.isArray(i)?i.join(", "):i)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,r])=>t+": "+r).join(`
1709
1709
  `)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...r){let i=new this(t);return r.forEach(n=>i.set(n)),i}static accessor(t){let i=(this[hHp]=this[hHp]={accessors:{}}).accessors,n=this.prototype;function a(u){let l=WAa(u);i[l]||(zWD(n,u),i[l]=!0)}return _s.isArray(t)?t.forEach(a):a(t),this}};d7n.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);_s.reduceDescriptors(d7n.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});_s.freezeMethods(d7n);var yR=d7n;function HAa(e,t){let r=this||f7n,i=t||r,n=yR.from(i.headers),a=i.data;return _s.forEach(e,function(l){a=l.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function $Aa(e){return!!(e&&e.__CANCEL__)}function yHp(e,t,r){Rp.call(this,e??"canceled",Rp.ERR_CANCELED,t,r),this.name="CanceledError"}_s.inherits(yHp,Rp,{__CANCEL__:!0});var sMe=yHp;function Srr(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new Rp("Request failed with status code "+r.status,[Rp.ERR_BAD_REQUEST,Rp.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function prc(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function _rc(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function dGi(e,t,r){let i=!prc(t);return e&&i||r==!1?_rc(e,t):t}var CHp=ci(DAa(),1),BHp=ci(require("http"),1),IHp=ci(require("https"),1),zHp=ci(require("util"),1),xHp=ci(mtc(),1),rdi=ci(require("zlib"),1);var pGi="1.8.2";function GAa(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var xWD=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function hrc(e,t,r){let i=r&&r.Blob||cA.classes.Blob,n=GAa(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=xWD.exec(e);if(!a)throw new Rp("Invalid URL",Rp.ERR_INVALID_URL);let u=a[1],l=a[2],d=a[3],s=Buffer.from(decodeURIComponent(d),l?"base64":"utf8");if(t){if(!i)throw new Rp("Blob is not supported",Rp.ERR_NOT_SUPPORT);return new i([s],{type:u})}return s}throw new Rp("Unsupported protocol "+n,Rp.ERR_NOT_SUPPORT)}var _Gi=ci(require("stream"),1);var vHp=ci(require("stream"),1);var yrc=Symbol("internals"),vrc=class extends vHp.default.Transform{constructor(t){t=_s.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!_s.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[yrc]={timeWindow:t.timeWindow,chunkSize:t.chunkSize,maxRate:t.maxRate,minChunkSize:t.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null};this.on("newListener",i=>{i==="progress"&&(r.isCaptured||(r.isCaptured=!0))})}_read(t){let r=this[yrc];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[yrc],a=n.maxRate,u=this.readableHighWaterMark,l=n.timeWindow,d=1e3/l,s=a/d,o=n.minChunkSize!==!1?Math.max(n.minChunkSize,s*.01):0,c=(g,O)=>{let m=Buffer.byteLength(g);n.bytesSeen+=m,n.bytes+=m,n.isCaptured&&this.emit("progress",n.bytesSeen),this.push(g)?process.nextTick(O):n.onReadCallback=()=>{n.onReadCallback=null,process.nextTick(O)}},b=(g,O)=>{let m=Buffer.byteLength(g),P=null,E=u,q,M=0;if(a){let D=Date.now();(!n.ts||(M=D-n.ts)>=l)&&(n.ts=D,q=s-n.bytes,n.bytes=q<0?-q:0,M=0),q=s-n.bytes}if(a){if(q<=0)return setTimeout(()=>{O(null,g)},l-M);q<E&&(E=q)}E&&m>E&&m-E>o&&(P=g.subarray(E),g=g.subarray(0,E)),c(g,P?()=>{process.nextTick(O,null,P)}:O)};b(t,function g(O,m){if(O)return i(O);m?b(m,g):i(null)})}},brc=vrc;var RHp=require("events");var gHp=ci(require("util"),1),OHp=require("stream");var{asyncIterator:bHp}=Symbol,RWD=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[bHp]?yield*e[bHp]():yield e},I2o=RWD;var NWD=cA.ALPHABET.ALPHA_DIGIT+"-_",QAa=typeof TextEncoder=="function"?new TextEncoder:new gHp.default.TextEncoder,ZDi=`\r
1710
1710
  `,FWD=QAa.encode(ZDi),LWD=2,grc=class{constructor(t,r){let{escapeName:i}=this.constructor,n=_s.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${ZDi}`;n?r=QAa.encode(String(r).replace(/\r?\n|\r\n?/g,ZDi)):a+=`Content-Type: ${r.type||"application/octet-stream"}${ZDi}`,this.headers=QAa.encode(a+ZDi),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+LWD,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;_s.isTypedArray(t)?yield t:yield*I2o(t),yield FWD}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},UWD=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+cA.generateString(n,NWD)}=r||{};if(!_s.isFormData(e))throw TypeError("FormData instance required");if(a.length<1||a.length>70)throw Error("boundary must be 10-70 characters long");let u=QAa.encode("--"+a+ZDi),l=QAa.encode("--"+a+"--"+ZDi+ZDi),d=l.byteLength,s=Array.from(e.entries()).map(([c,b])=>{let g=new grc(c,b);return d+=g.size,g});d+=u.byteLength*s.length,d=_s.toFiniteNumber(d);let o={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(d)&&(o["Content-Length"]=d),t&&t(o),OHp.Readable.from(async function*(){for(let c of s)yield u,yield*c.encode();yield l}())},mHp=UWD;var PHp=ci(require("stream"),1),Orc=class extends PHp.default.Transform{__transform(t,r,i){this.push(t),i()}_transform(t,r,i){if(t.length!==0&&(this._transform=this.__transform,t[0]!==120)){let n=Buffer.alloc(2);n[0]=120,n[1]=156,this.push(n,r)}this.__transform(t,r,i)}},jHp=Orc;var VWD=(e,t)=>_s.isAsyncFn(e)?function(...r){let i=r.pop();e.apply(this,r).then(n=>{try{t?i(null,...t(n)):i(null,n)}catch(a){i(a)}},i)}:e,wHp=VWD;function WWD(e,t){e=e||10;let r=new Array(e),i=new Array(e),n=0,a=0,u;return t=t!==void 0?t:1e3,function(d){let s=Date.now(),o=i[a];u||(u=s),r[n]=d,i[n]=s;let c=a,b=0;for(;c!==n;)b+=r[c++],c=c%e;if(n=(n+1)%e,n===a&&(a=(a+1)%e),s-u<t)return;let g=o&&s-o;return g?Math.round(b*1e3/g):void 0}}var SHp=WWD;function HWD(e,t){let r=0,i=1e3/t,n,a,u=(s,o=Date.now())=>{r=o,n=null,a&&(clearTimeout(a),a=null),e.apply(null,s)};return[(...s)=>{let o=Date.now(),c=o-r;c>=i?u(s,o):(n=s,a||(a=setTimeout(()=>{a=null,u(n)},i-c)))},()=>n&&u(n)]}var DHp=HWD;var tdi=(e,t,r=3)=>{let i=0,n=SHp(50,250);return DHp(a=>{let u=a.loaded,l=a.lengthComputable?a.total:void 0,d=u-i,s=n(d),o=u<=l;i=u;let c={loaded:u,total:l,progress:l?u/l:void 0,bytes:d,rate:s||void 0,estimated:s&&l&&o?(l-u)/s:void 0,event:a,lengthComputable:l!=null,[t?"download":"upload"]:!0};e(c)},r)},p7n=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},_7n=e=>(...t)=>_s.asap(()=>e(...t));var EHp={flush:rdi.default.constants.Z_SYNC_FLUSH,finishFlush:rdi.default.constants.Z_SYNC_FLUSH},$WD={flush:rdi.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:rdi.default.constants.BROTLI_OPERATION_FLUSH},MHp=_s.isFunction(rdi.default.createBrotliDecompress),{http:GWD,https:QWD}=xHp.default,JWD=/https:?/,AHp=cA.protocols.map(e=>e+":"),qHp=(e,[t,r])=>(e.on("end",r).on("error",r),t);function KWD(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function NHp(e,t,r){let i=t;if(!i&&i!==!1){let n=CHp.default.getProxyForUrl(r);n&&(i=new URL(n))}if(i){if(i.username&&(i.auth=(i.username||"")+":"+(i.password||"")),i.auth){(i.auth.username||i.auth.password)&&(i.auth=(i.auth.username||"")+":"+(i.auth.password||""));let a=Buffer.from(i.auth,"utf8").toString("base64");e.headers["Proxy-Authorization"]="Basic "+a}e.headers.host=e.hostname+(e.port?":"+e.port:"");let n=i.hostname||i.host;e.hostname=n,e.host=n,e.port=i.port,e.path=r,i.protocol&&(e.protocol=i.protocol.includes(":")?i.protocol:`${i.protocol}:`)}e.beforeRedirects.proxy=function(a){NHp(a,t,a.href)}}var YWD=typeof process<"u"&&_s.kindOf(process)==="process",XWD=e=>new Promise((t,r)=>{let i,n,a=(d,s)=>{n||(n=!0,i&&i(d,s))},u=d=>{a(d),t(d)},l=d=>{a(d,!0),r(d)};e(u,l,d=>i=d).catch(l)}),ZWD=({address:e,family:t})=>{if(!_s.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},THp=(e,t)=>ZWD(_s.isObject(e)?e:{address:e,family:t}),FHp=YWD&&function(t){return XWD(async function(i,n,a){let{data:u,lookup:l,family:d}=t,{responseType:s,responseEncoding:o}=t,c=t.method.toUpperCase(),b,g=!1,O;if(l){let we=wHp(l,Qe=>_s.isArray(Qe)?Qe:[Qe]);l=(Qe,Dt,Ee)=>{we(Qe,Dt,(Te,zt,Pe)=>{if(Te)return Ee(Te);let at=_s.isArray(zt)?zt.map(it=>THp(it)):[THp(zt,Pe)];Dt.all?Ee(Te,at):Ee(Te,at[0].address,at[0].family)})}}let m=new RHp.EventEmitter,P=()=>{t.cancelToken&&t.cancelToken.unsubscribe(E),t.signal&&t.signal.removeEventListener("abort",E),m.removeAllListeners()};a((we,Qe)=>{b=!0,Qe&&(g=!0,P())});function E(we){m.emit("abort",!we||we.type?new sMe(null,t,O):we)}m.once("abort",n),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(E),t.signal&&(t.signal.aborted?E():t.signal.addEventListener("abort",E)));let q=dGi(t.baseURL,t.url,t.allowAbsoluteUrls),M=new URL(q,cA.hasBrowserEnv?cA.origin:void 0),D=M.protocol||AHp[0];if(D==="data:"){let we;if(c!=="GET")return Srr(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{we=hrc(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(Qe){throw Rp.from(Qe,Rp.ERR_BAD_REQUEST,t)}return s==="text"?(we=we.toString(o),(!o||o==="utf8")&&(we=_s.stripBOM(we))):s==="stream"&&(we=_Gi.default.Readable.from(we)),Srr(i,n,{data:we,status:200,statusText:"OK",headers:new yR,config:t})}if(AHp.indexOf(D)===-1)return n(new Rp("Unsupported protocol "+D,Rp.ERR_BAD_REQUEST,t));let T=yR.from(t.headers).normalize();T.set("User-Agent","axios/"+pGi,!1);let{onUploadProgress:x,onDownloadProgress:$}=t,I=t.maxRate,L,V;if(_s.isSpecCompliantForm(u)){let we=T.getContentType(/boundary=([-_\w\d]{10,70})/i);u=mHp(u,Qe=>{T.set(Qe)},{tag:`axios-${pGi}-boundary`,boundary:we&&we[1]||void 0})}else if(_s.isFormData(u)&&_s.isFunction(u.getHeaders)){if(T.set(u.getHeaders()),!T.hasContentLength())try{let we=await zHp.default.promisify(u.getLength).call(u);Number.isFinite(we)&&we>=0&&T.setContentLength(we)}catch{}}else if(_s.isBlob(u)||_s.isFile(u))u.size&&T.setContentType(u.type||"application/octet-stream"),T.setContentLength(u.size||0),u=_Gi.default.Readable.from(I2o(u));else if(u&&!_s.isStream(u)){if(!Buffer.isBuffer(u))if(_s.isArrayBuffer(u))u=Buffer.from(new Uint8Array(u));else if(_s.isString(u))u=Buffer.from(u,"utf-8");else return n(new Rp("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",Rp.ERR_BAD_REQUEST,t));if(T.setContentLength(u.length,!1),t.maxBodyLength>-1&&u.length>t.maxBodyLength)return n(new Rp("Request body larger than maxBodyLength limit",Rp.ERR_BAD_REQUEST,t))}let X=_s.toFiniteNumber(T.getContentLength());_s.isArray(I)?(L=I[0],V=I[1]):L=V=I,u&&(x||L)&&(_s.isStream(u)||(u=_Gi.default.Readable.from(u,{objectMode:!1})),u=_Gi.default.pipeline([u,new brc({maxRate:_s.toFiniteNumber(L)})],_s.noop),x&&u.on("progress",qHp(u,p7n(X,tdi(_7n(x),!1,3)))));let K;if(t.auth){let we=t.auth.username||"",Qe=t.auth.password||"";K=we+":"+Qe}if(!K&&M.username){let we=M.username,Qe=M.password;K=we+":"+Qe}K&&T.delete("authorization");let k;try{k=fGi(M.pathname+M.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(we){let Qe=new Error(we.message);return Qe.config=t,Qe.url=t.url,Qe.exists=!0,n(Qe)}T.set("Accept-Encoding","gzip, compress, deflate"+(MHp?", br":""),!1);let fe={path:k,method:c,headers:T.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:K,protocol:D,family:d,beforeRedirect:KWD,beforeRedirects:{}};!_s.isUndefined(l)&&(fe.lookup=l),t.socketPath?fe.socketPath=t.socketPath:(fe.hostname=M.hostname.startsWith("[")?M.hostname.slice(1,-1):M.hostname,fe.port=M.port,NHp(fe,t.proxy,D+"//"+M.hostname+(M.port?":"+M.port:"")+fe.path));let be,_e=JWD.test(fe.protocol);if(fe.agent=_e?t.httpsAgent:t.httpAgent,t.transport?be=t.transport:t.maxRedirects===0?be=_e?IHp.default:BHp.default:(t.maxRedirects&&(fe.maxRedirects=t.maxRedirects),t.beforeRedirect&&(fe.beforeRedirects.config=t.beforeRedirect),be=_e?QWD:GWD),t.maxBodyLength>-1?fe.maxBodyLength=t.maxBodyLength:fe.maxBodyLength=1/0,t.insecureHTTPParser&&(fe.insecureHTTPParser=t.insecureHTTPParser),O=be.request(fe,function(Qe){if(O.destroyed)return;let Dt=[Qe],Ee=+Qe.headers["content-length"];if($||V){let it=new brc({maxRate:_s.toFiniteNumber(V)});$&&it.on("progress",qHp(it,p7n(Ee,tdi(_7n($),!0,3)))),Dt.push(it)}let Te=Qe,zt=Qe.req||O;if(t.decompress!==!1&&Qe.headers["content-encoding"])switch((c==="HEAD"||Qe.statusCode===204)&&delete Qe.headers["content-encoding"],(Qe.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":Dt.push(rdi.default.createUnzip(EHp)),delete Qe.headers["content-encoding"];break;case"deflate":Dt.push(new jHp),Dt.push(rdi.default.createUnzip(EHp)),delete Qe.headers["content-encoding"];break;case"br":MHp&&(Dt.push(rdi.default.createBrotliDecompress($WD)),delete Qe.headers["content-encoding"])}Te=Dt.length>1?_Gi.default.pipeline(Dt,_s.noop):Dt[0];let Pe=_Gi.default.finished(Te,()=>{Pe(),P()}),at={status:Qe.statusCode,statusText:Qe.statusMessage,headers:new yR(Qe.headers),config:t,request:zt};if(s==="stream")at.data=Te,Srr(i,n,at);else{let it=[],ge=0;Te.on("data",function(bt){it.push(bt),ge+=bt.length,t.maxContentLength>-1&&ge>t.maxContentLength&&(g=!0,Te.destroy(),n(new Rp("maxContentLength size of "+t.maxContentLength+" exceeded",Rp.ERR_BAD_RESPONSE,t,zt)))}),Te.on("aborted",function(){if(g)return;let bt=new Rp("stream has been aborted",Rp.ERR_BAD_RESPONSE,t,zt);Te.destroy(bt),n(bt)}),Te.on("error",function(bt){O.destroyed||n(Rp.from(bt,null,t,zt))}),Te.on("end",function(){try{let bt=it.length===1?it[0]:Buffer.concat(it);s!=="arraybuffer"&&(bt=bt.toString(o),(!o||o==="utf8")&&(bt=_s.stripBOM(bt))),at.data=bt}catch(bt){return n(Rp.from(bt,null,t,at.request,at))}Srr(i,n,at)})}m.once("abort",it=>{Te.destroyed||(Te.emit("error",it),Te.destroy())})}),m.once("abort",we=>{n(we),O.destroy(we)}),O.on("error",function(Qe){n(Rp.from(Qe,null,t,O))}),O.on("socket",function(Qe){Qe.setKeepAlive(!0,1e3*60)}),t.timeout){let we=parseInt(t.timeout,10);if(Number.isNaN(we)){n(new Rp("error trying to parse `config.timeout` to int",Rp.ERR_BAD_OPTION_VALUE,t,O));return}O.setTimeout(we,function(){if(b)return;let Dt=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",Ee=t.transitional||l7n;t.timeoutErrorMessage&&(Dt=t.timeoutErrorMessage),n(new Rp(Dt,Ee.clarifyTimeoutError?Rp.ETIMEDOUT:Rp.ECONNABORTED,t,O)),E()})}if(_s.isStream(u)){let we=!1,Qe=!1;u.on("end",()=>{we=!0}),u.once("error",Dt=>{Qe=!0,O.destroy(Dt)}),u.on("close",()=>{!we&&!Qe&&E(new sMe("Request stream has been aborted",t,O))}),u.pipe(O)}else O.end(u)})};var LHp=cA.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,cA.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(cA.origin),cA.navigator&&/(msie|trident)/i.test(cA.navigator.userAgent)):()=>!0;var UHp=cA.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let u=[e+"="+encodeURIComponent(t)];_s.isNumber(r)&&u.push("expires="+new Date(r).toGMTString()),_s.isString(i)&&u.push("path="+i),_s.isString(n)&&u.push("domain="+n),a===!0&&u.push("secure"),document.cookie=u.join("; ")},read(e){let t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};var VHp=e=>e instanceof yR?{...e}:e;function IWt(e,t){t=t||{};let r={};function i(s,o,c,b){return _s.isPlainObject(s)&&_s.isPlainObject(o)?_s.merge.call({caseless:b},s,o):_s.isPlainObject(o)?_s.merge({},o):_s.isArray(o)?o.slice():o}function n(s,o,c,b){if(_s.isUndefined(o)){if(!_s.isUndefined(s))return i(void 0,s,c,b)}else return i(s,o,c,b)}function a(s,o){if(!_s.isUndefined(o))return i(void 0,o)}function u(s,o){if(_s.isUndefined(o)){if(!_s.isUndefined(s))return i(void 0,s)}else return i(void 0,o)}function l(s,o,c){if(c in t)return i(s,o);if(c in e)return i(void 0,s)}let d={url:a,method:a,data:a,baseURL:u,transformRequest:u,transformResponse:u,paramsSerializer:u,timeout:u,timeoutMessage:u,withCredentials:u,withXSRFToken:u,adapter:u,responseType:u,xsrfCookieName:u,xsrfHeaderName:u,onUploadProgress:u,onDownloadProgress:u,decompress:u,maxContentLength:u,maxBodyLength:u,beforeRedirect:u,transport:u,httpAgent:u,httpsAgent:u,cancelToken:u,socketPath:u,responseEncoding:u,validateStatus:l,headers:(s,o,c)=>n(VHp(s),VHp(o),c,!0)};return _s.forEach(Object.keys(Object.assign({},e,t)),function(o){let c=d[o]||n,b=c(e[o],t[o],o);_s.isUndefined(b)&&c!==l||(r[o]=b)}),r}var z2o=e=>{let t=IWt({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:u,auth:l}=t;t.headers=u=yR.from(u),t.url=fGi(dGi(t.baseURL,t.url),e.params,e.paramsSerializer),l&&u.set("Authorization","Basic "+btoa((l.username||"")+":"+(l.password?unescape(encodeURIComponent(l.password)):"")));let d;if(_s.isFormData(r)){if(cA.hasStandardBrowserEnv||cA.hasStandardBrowserWebWorkerEnv)u.setContentType(void 0);else if((d=u.getContentType())!==!1){let[s,...o]=d?d.split(";").map(c=>c.trim()).filter(Boolean):[];u.setContentType([s||"multipart/form-data",...o].join("; "))}}if(cA.hasStandardBrowserEnv&&(i&&_s.isFunction(i)&&(i=i(t)),i||i!==!1&&LHp(t.url))){let s=n&&a&&UHp.read(a);s&&u.set(n,s)}return t};var kWD=typeof XMLHttpRequest<"u",WHp=kWD&&function(e){return new Promise(function(r,i){let n=z2o(e),a=n.data,u=yR.from(n.headers).normalize(),{responseType:l,onUploadProgress:d,onDownloadProgress:s}=n,o,c,b,g,O;function m(){g&&g(),O&&O(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let P=new XMLHttpRequest;P.open(n.method.toUpperCase(),n.url,!0),P.timeout=n.timeout;function E(){if(!P)return;let M=yR.from("getAllResponseHeaders"in P&&P.getAllResponseHeaders()),T={data:!l||l==="text"||l==="json"?P.responseText:P.response,status:P.status,statusText:P.statusText,headers:M,config:e,request:P};Srr(function($){r($),m()},function($){i($),m()},T),P=null}"onloadend"in P?P.onloadend=E:P.onreadystatechange=function(){!P||P.readyState!==4||P.status===0&&!(P.responseURL&&P.responseURL.indexOf("file:")===0)||setTimeout(E)},P.onabort=function(){P&&(i(new Rp("Request aborted",Rp.ECONNABORTED,e,P)),P=null)},P.onerror=function(){i(new Rp("Network Error",Rp.ERR_NETWORK,e,P)),P=null},P.ontimeout=function(){let D=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",T=n.transitional||l7n;n.timeoutErrorMessage&&(D=n.timeoutErrorMessage),i(new Rp(D,T.clarifyTimeoutError?Rp.ETIMEDOUT:Rp.ECONNABORTED,e,P)),P=null},a===void 0&&u.setContentType(null),"setRequestHeader"in P&&_s.forEach(u.toJSON(),function(D,T){P.setRequestHeader(T,D)}),_s.isUndefined(n.withCredentials)||(P.withCredentials=!!n.withCredentials),l&&l!=="json"&&(P.responseType=n.responseType),s&&([b,O]=tdi(s,!0),P.addEventListener("progress",b)),d&&P.upload&&([c,g]=tdi(d),P.upload.addEventListener("progress",c),P.upload.addEventListener("loadend",g)),(n.cancelToken||n.signal)&&(o=M=>{P&&(i(!M||M.type?new sMe(null,e,P):M),P.abort(),P=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));let q=GAa(n.url);if(q&&cA.protocols.indexOf(q)===-1){i(new Rp("Unsupported protocol "+q+":",Rp.ERR_BAD_REQUEST,e));return}P.send(a||null)})};var eHD=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let i=new AbortController,n,a=function(s){if(!n){n=!0,l();let o=s instanceof Error?s:this.reason;i.abort(o instanceof Rp?o:new sMe(o instanceof Error?o.message:o))}},u=t&&setTimeout(()=>{u=null,a(new Rp(`timeout ${t} of ms exceeded`,Rp.ETIMEDOUT))},t),l=()=>{e&&(u&&clearTimeout(u),u=null,e.forEach(s=>{s.unsubscribe?s.unsubscribe(a):s.removeEventListener("abort",a)}),e=null)};e.forEach(s=>s.addEventListener("abort",a));let{signal:d}=i;return d.unsubscribe=()=>_s.asap(l),d}},HHp=eHD;var tHD=function*(e,t){let r=e.byteLength;if(!t||r<t){yield e;return}let i=0,n;for(;i<r;)n=i+t,yield e.slice(i,n),i=n},rHD=async function*(e,t){for await(let r of iHD(e))yield*tHD(r,t)},iHD=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}let t=e.getReader();try{for(;;){let{done:r,value:i}=await t.read();if(r)break;yield i}}finally{await t.cancel()}},mrc=(e,t,r,i)=>{let n=rHD(e,t),a=0,u,l=d=>{u||(u=!0,i&&i(d))};return new ReadableStream({async pull(d){try{let{done:s,value:o}=await n.next();if(s){l(),d.close();return}let c=o.byteLength;if(r){let b=a+=c;r(b)}d.enqueue(new Uint8Array(o))}catch(s){throw l(s),s}},cancel(d){return l(d),n.return()}},{highWaterMark:2})};var R2o=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",GHp=R2o&&typeof ReadableStream=="function",nHD=R2o&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),QHp=(e,...t)=>{try{return!!e(...t)}catch{return!1}},aHD=GHp&&QHp(()=>{let e=!1,t=new Request(cA.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),$Hp=64*1024,Prc=GHp&&QHp(()=>_s.isReadableStream(new Response("").body)),x2o={stream:Prc&&(e=>e.body)};R2o&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!x2o[t]&&(x2o[t]=_s.isFunction(e[t])?r=>r[t]():(r,i)=>{throw new Rp(`Response type '${t}' is not supported`,Rp.ERR_NOT_SUPPORT,i)})})})(new Response);var oHD=async e=>{if(e==null)return 0;if(_s.isBlob(e))return e.size;if(_s.isSpecCompliantForm(e))return(await new Request(cA.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(_s.isArrayBufferView(e)||_s.isArrayBuffer(e))return e.byteLength;if(_s.isURLSearchParams(e)&&(e=e+""),_s.isString(e))return(await nHD(e)).byteLength},uHD=async(e,t)=>{let r=_s.toFiniteNumber(e.getContentLength());return r??oHD(t)},JHp=R2o&&(async e=>{let{url:t,method:r,data:i,signal:n,cancelToken:a,timeout:u,onDownloadProgress:l,onUploadProgress:d,responseType:s,headers:o,withCredentials:c="same-origin",fetchOptions:b}=z2o(e);s=s?(s+"").toLowerCase():"text";let g=HHp([n,a&&a.toAbortSignal()],u),O,m=g&&g.unsubscribe&&(()=>{g.unsubscribe()}),P;try{if(d&&aHD&&r!=="get"&&r!=="head"&&(P=await uHD(o,i))!==0){let T=new Request(t,{method:"POST",body:i,duplex:"half"}),x;if(_s.isFormData(i)&&(x=T.headers.get("content-type"))&&o.setContentType(x),T.body){let[$,I]=p7n(P,tdi(_7n(d)));i=mrc(T.body,$Hp,$,I)}}_s.isString(c)||(c=c?"include":"omit");let E="credentials"in Request.prototype;O=new Request(t,{...b,signal:g,method:r.toUpperCase(),headers:o.normalize().toJSON(),body:i,duplex:"half",credentials:E?c:void 0});let q=await fetch(O),M=Prc&&(s==="stream"||s==="response");if(Prc&&(l||M&&m)){let T={};["status","statusText","headers"].forEach(L=>{T[L]=q[L]});let x=_s.toFiniteNumber(q.headers.get("content-length")),[$,I]=l&&p7n(x,tdi(_7n(l),!0))||[];q=new Response(mrc(q.body,$Hp,$,()=>{I&&I(),m&&m()}),T)}s=s||"text";let D=await x2o[_s.findKey(x2o,s)||"text"](q,e);return!M&&m&&m(),await new Promise((T,x)=>{Srr(T,x,{data:D,headers:yR.from(q.headers),status:q.status,statusText:q.statusText,config:e,request:O})})}catch(E){throw m&&m(),E&&E.name==="TypeError"&&/fetch/i.test(E.message)?Object.assign(new Rp("Network Error",Rp.ERR_NETWORK,e,O),{cause:E.cause||E}):Rp.from(E,E&&E.code,e,O)}});var jrc={http:FHp,xhr:WHp,fetch:JHp};_s.forEach(jrc,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var KHp=e=>`- ${e}`,sHD=e=>_s.isFunction(e)||e===null||e===!1,N2o={getAdapter:e=>{e=_s.isArray(e)?e:[e];let{length:t}=e,r,i,n={};for(let a=0;a<t;a++){r=e[a];let u;if(i=r,!sHD(r)&&(i=jrc[(u=String(r)).toLowerCase()],i===void 0))throw new Rp(`Unknown adapter '${u}'`);if(i)break;n[u||"#"+a]=i}if(!i){let a=Object.entries(n).map(([l,d])=>`adapter ${l} `+(d===!1?"is not supported by the environment":"is not available in the build")),u=t?a.length>1?`since :
@@ -1943,7 +1943,7 @@ ${M}${q}${D}${Hd_.default.cursorHide}`});var wIa=ci(B1i(),1);function dpc(e,t){i
1943
1943
  Run ${Gs.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
1944
1944
  Run ${Gs.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),y7n(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function jpc({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!_p_(e))return;let n=t??"",a=e.filter(l=>l.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let u=a.sort((l,d)=>l.generatorName.localeCompare(d.generatorName)||l.currentVersion.localeCompare(d.currentVersion));for(let l of u)n+=`
1945
1945
  ${await ZgE(l.generatorName)} (${l.apiName!=null?"API: "+l.apiName+", ":""}Group: ${l.generatorGroup}) `+Gs.dim(l.currentVersion)+Gs.reset(" \u2192 ")+Gs.green(l.latestVersion);return n+=`
1946
- `,i?y7n(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function ZgE(e){let r=await new pp_.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new Error(`Generator ${e} not found`);return r.body.displayName}async function kgE({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await yp_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=C1i(o.name,c),g=await Ckt({generatorName:b,cliVersion:e.environment.packageVersion,currentGeneratorVersion:o.version,channel:n,includeMajor:a,context:c});g!=null&&(l.versions[s][o.name]={previousVersion:o.version,latestVersion:g})},generatorFilter:r,groupFilter:i}),l}let u={type:"multiApi",versions:{}};return await yp_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(l,d,s,o)=>{if(l==null)return;u.versions[l]==null&&(u.versions[l]={}),u.versions[l][d]==null&&(u.versions[l][d]={});let c=C1i(s.name,o),b=await Ckt({generatorName:c,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:o});b!=null&&(u.versions[l][d][s.name]={previousVersion:s.version,latestVersion:b})},generatorFilter:r,groupFilter:i}),u}async function yp_({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async u=>{let l=await rWt({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(l==null||l.groups==null)){for(let d of l.groups)if(!(n!=null&&d.groupName!==n))for(let s of d.generators)i!=null&&s.name!==i||await r(a.workspaceName,d.groupName,s,u)}})}))}function vp_(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[u,l]of Object.entries(a)){r.debug(`Checking if ${u} in group ${n} has an upgrade available...`);let d=Gae(l.latestVersion,l.previousVersion);r.debug(`Latest version: ${l.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:u,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:l.previousVersion,latestVersion:l.latestVersion})}return i}async function FHo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await kgE({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(l.type==="multiApi")for(let[d,s]of Object.entries(l.versions))u.push(...vp_(s,d,t.logger));else u.push(...vp_(l.versions,void 0,t.logger))}return u}var CIa=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText||"",u=`${n} ${a}`.trim(),l=u?`status code ${u}`:"an unknown error";super(`Request failed with ${l}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var K2n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var Y2n=e=>e!==null&&typeof e=="object";var BIa=(...e)=>{for(let t of e)if((!Y2n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return Dpc({},...e)},wpc=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,u]of n.entries())i&&u==="undefined"||u===void 0?r.delete(a):r.set(a,u);return r};function LHo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:Dpc(e[r]??[],t[r]??[])}var Spc=(e={},t={})=>({beforeRequest:LHo(e,t,"beforeRequest"),beforeRetry:LHo(e,t,"beforeRetry"),afterResponse:LHo(e,t,"afterResponse"),beforeError:LHo(e,t,"beforeError")}),Dpc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(Y2n(n)){for(let[a,u]of Object.entries(n))Y2n(u)&&a in t&&(u=Dpc(t[a],u)),t={...t,[a]:u};Y2n(n.hooks)&&(i=Spc(i,n.hooks),t.hooks=i),Y2n(n.headers)&&(r=wpc(r,n.headers),t.headers=r)}return t};var bp_=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",i=typeof globalThis.Request=="function";if(r&&i)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return e&&!t})(),gp_=typeof globalThis.AbortController=="function",Op_=typeof globalThis.ReadableStream=="function",mp_=typeof globalThis.FormData=="function",UHo=["get","post","put","patch","head","delete"],eOE=()=>{};eOE();var Pp_={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},VHo=2147483647,WHo=Symbol("stop"),jp_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},wp_={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0};var Dp_=e=>UHo.includes(e)?e.toUpperCase():e,tOE=["get","put","head","delete","options","trace"],rOE=[408,413,429,500,502,503,504],iOE=[413,429,503],Sp_={limit:2,methods:tOE,statusCodes:rOE,afterStatusCodes:iOE,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},Ep_=(e={})=>{if(typeof e=="number")return{...Sp_,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Sp_,...e}};async function Epc(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new K2n(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function Mpc(e,{signal:t}){return new Promise((r,i)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),i(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e)})}var Mp_=(e,t)=>{let r={};for(let i in t)!(i in wp_)&&!(i in jp_)&&!(i in e)&&(r[i]=t[i]);return r};var IIa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>VHo)throw new RangeError(`The \`timeout\` option cannot be greater than ${VHo}`);await Promise.resolve();let l=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(l.clone()));s instanceof globalThis.Response&&(l=s)}if(i._decorateResponse(l),!l.ok&&i._options.throwHttpErrors){let d=new CIa(l,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Op_)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return i._stream(l.clone(),i._options.onDownloadProgress)}return l},u=i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n();for(let[l,d]of Object.entries(Pp_))u[l]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let o=(await u).clone();if(l==="json"){if(o.status===204||(await o.clone().arrayBuffer()).byteLength===0)return"";if(r.parseJson)return r.parseJson(await o.text())}return o[l]()};return u}request;abortController;_retryCount=0;_input;_options;constructor(t,r={}){if(this._input=t,this._options={...r,headers:wpc(this._input.headers,r.headers),hooks:Spc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:Dp_(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:Ep_(r.retry),throwHttpErrors:r.throwHttpErrors!==!1,timeout:r.timeout??1e4,fetch:r.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(gp_){this.abortController=new globalThis.AbortController;let i=this._options.signal??this._input.signal;i?.addEventListener("abort",()=>{this.abortController.abort(i.reason)}),this._options.signal=this.abortController.signal}if(bp_&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=this._options.stringifyJson?.(this._options.json)??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(mp_&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof K2n)throw t;if(t instanceof CIa){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let i=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(i&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(i)*1e3;Number.isNaN(n)?n=Date.parse(i)-Date.now():n>=Date.parse("2024-01-01")&&(n-=Date.now());let a=this._options.retry.maxRetryAfter??n;return n<a?n:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let i=Math.min(this._calculateRetryDelay(r),VHo);if(this._retryCount<1)throw r;await Mpc(i,{signal:this._options.signal});for(let n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===WHo)return;return this._retry(t)}}async _fetch(){for(let i of this._options.hooks.beforeRequest){let n=await i(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}let t=Mp_(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):Epc(r,t,this.abortController,this._options)}_stream(t,r){let i=Number(t.headers.get("content-length"))||0,n=0;return t.status===204?(r&&r({percent:1,totalBytes:i,transferredBytes:n},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){let u=t.body.getReader();r&&r({percent:0,transferredBytes:0,totalBytes:i},new Uint8Array);async function l(){let{done:d,value:s}=await u.read();if(d){a.close();return}if(r){n+=s.byteLength;let o=i===0?0:n/i;r({percent:o,transferredBytes:n,totalBytes:i},s)}a.enqueue(s),await l()}await l()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}};var Apc=e=>{let t=(r,i)=>IIa.create(r,BIa(e,i));for(let r of UHo)t[r]=(i,n)=>IIa.create(i,BIa(e,n,{method:r}));return t.create=r=>Apc(BIa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),Apc(BIa(e,r))),t.stop=WHo,t},nOE=Apc(),Ap_=nOE;var Zp_=ci(Xp_(),1);function Ipc(e){let t=(0,Zp_.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var G__=ci($__(),1),Q__=ci(B1i(),1),Jpc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},Kpc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function Ypc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??Ipc(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,G__.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,l&&(d.authorization=`${l.type} ${l.token}`);let s;try{s=await Ap_(u,{headers:d,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new Jpc(e):c}if(t.allVersions)return s;let o=new Kpc(e,r);if(s["dist-tags"][r]){let{time:c}=s;s=s.versions[s["dist-tags"][r]],s.time=c}else if(r){let c=!!s.versions[r];if(i&&!c)for(let[g,O]of Object.entries(s.versions))O.deprecated&&delete s.versions[g];if(!c){let g=Object.keys(s.versions);if(r=Q__.default.maxSatisfying(g,r),!r)throw o}let{time:b}=s;if(s=s.versions[r],s.time=b,!s)throw o}return s}async function LIa(e,t){let{version:r}=await Ypc(e.toLowerCase(),t);return r}async function PMi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:LIa(e.packageName,{version:t?"prerelease":"latest"})}var J__=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],t$o=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=M0.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new NHo(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),u=this.getCliName();(n==null||a==null||u==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:u}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.64.7"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Gs.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new w9}failWithoutThrowing(t,r){this.didSucceed=!1,IHo({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await u7n()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await hp_({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1946
+ `,i?y7n(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function ZgE(e){let r=await new pp_.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new Error(`Generator ${e} not found`);return r.body.displayName}async function kgE({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await yp_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=C1i(o.name,c),g=await Ckt({generatorName:b,cliVersion:e.environment.packageVersion,currentGeneratorVersion:o.version,channel:n,includeMajor:a,context:c});g!=null&&(l.versions[s][o.name]={previousVersion:o.version,latestVersion:g})},generatorFilter:r,groupFilter:i}),l}let u={type:"multiApi",versions:{}};return await yp_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(l,d,s,o)=>{if(l==null)return;u.versions[l]==null&&(u.versions[l]={}),u.versions[l][d]==null&&(u.versions[l][d]={});let c=C1i(s.name,o),b=await Ckt({generatorName:c,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:o});b!=null&&(u.versions[l][d][s.name]={previousVersion:s.version,latestVersion:b})},generatorFilter:r,groupFilter:i}),u}async function yp_({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async u=>{let l=await rWt({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(l==null||l.groups==null)){for(let d of l.groups)if(!(n!=null&&d.groupName!==n))for(let s of d.generators)i!=null&&s.name!==i||await r(a.workspaceName,d.groupName,s,u)}})}))}function vp_(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[u,l]of Object.entries(a)){r.debug(`Checking if ${u} in group ${n} has an upgrade available...`);let d=Gae(l.latestVersion,l.previousVersion);r.debug(`Latest version: ${l.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:u,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:l.previousVersion,latestVersion:l.latestVersion})}return i}async function FHo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await kgE({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(l.type==="multiApi")for(let[d,s]of Object.entries(l.versions))u.push(...vp_(s,d,t.logger));else u.push(...vp_(l.versions,void 0,t.logger))}return u}var CIa=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText||"",u=`${n} ${a}`.trim(),l=u?`status code ${u}`:"an unknown error";super(`Request failed with ${l}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var K2n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var Y2n=e=>e!==null&&typeof e=="object";var BIa=(...e)=>{for(let t of e)if((!Y2n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return Dpc({},...e)},wpc=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,u]of n.entries())i&&u==="undefined"||u===void 0?r.delete(a):r.set(a,u);return r};function LHo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:Dpc(e[r]??[],t[r]??[])}var Spc=(e={},t={})=>({beforeRequest:LHo(e,t,"beforeRequest"),beforeRetry:LHo(e,t,"beforeRetry"),afterResponse:LHo(e,t,"afterResponse"),beforeError:LHo(e,t,"beforeError")}),Dpc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(Y2n(n)){for(let[a,u]of Object.entries(n))Y2n(u)&&a in t&&(u=Dpc(t[a],u)),t={...t,[a]:u};Y2n(n.hooks)&&(i=Spc(i,n.hooks),t.hooks=i),Y2n(n.headers)&&(r=wpc(r,n.headers),t.headers=r)}return t};var bp_=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",i=typeof globalThis.Request=="function";if(r&&i)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return e&&!t})(),gp_=typeof globalThis.AbortController=="function",Op_=typeof globalThis.ReadableStream=="function",mp_=typeof globalThis.FormData=="function",UHo=["get","post","put","patch","head","delete"],eOE=()=>{};eOE();var Pp_={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},VHo=2147483647,WHo=Symbol("stop"),jp_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},wp_={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0};var Dp_=e=>UHo.includes(e)?e.toUpperCase():e,tOE=["get","put","head","delete","options","trace"],rOE=[408,413,429,500,502,503,504],iOE=[413,429,503],Sp_={limit:2,methods:tOE,statusCodes:rOE,afterStatusCodes:iOE,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},Ep_=(e={})=>{if(typeof e=="number")return{...Sp_,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Sp_,...e}};async function Epc(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new K2n(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function Mpc(e,{signal:t}){return new Promise((r,i)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),i(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e)})}var Mp_=(e,t)=>{let r={};for(let i in t)!(i in wp_)&&!(i in jp_)&&!(i in e)&&(r[i]=t[i]);return r};var IIa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>VHo)throw new RangeError(`The \`timeout\` option cannot be greater than ${VHo}`);await Promise.resolve();let l=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(l.clone()));s instanceof globalThis.Response&&(l=s)}if(i._decorateResponse(l),!l.ok&&i._options.throwHttpErrors){let d=new CIa(l,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Op_)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return i._stream(l.clone(),i._options.onDownloadProgress)}return l},u=i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n();for(let[l,d]of Object.entries(Pp_))u[l]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let o=(await u).clone();if(l==="json"){if(o.status===204||(await o.clone().arrayBuffer()).byteLength===0)return"";if(r.parseJson)return r.parseJson(await o.text())}return o[l]()};return u}request;abortController;_retryCount=0;_input;_options;constructor(t,r={}){if(this._input=t,this._options={...r,headers:wpc(this._input.headers,r.headers),hooks:Spc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:Dp_(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:Ep_(r.retry),throwHttpErrors:r.throwHttpErrors!==!1,timeout:r.timeout??1e4,fetch:r.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(gp_){this.abortController=new globalThis.AbortController;let i=this._options.signal??this._input.signal;i?.addEventListener("abort",()=>{this.abortController.abort(i.reason)}),this._options.signal=this.abortController.signal}if(bp_&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=this._options.stringifyJson?.(this._options.json)??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(mp_&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof K2n)throw t;if(t instanceof CIa){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let i=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(i&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(i)*1e3;Number.isNaN(n)?n=Date.parse(i)-Date.now():n>=Date.parse("2024-01-01")&&(n-=Date.now());let a=this._options.retry.maxRetryAfter??n;return n<a?n:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let i=Math.min(this._calculateRetryDelay(r),VHo);if(this._retryCount<1)throw r;await Mpc(i,{signal:this._options.signal});for(let n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===WHo)return;return this._retry(t)}}async _fetch(){for(let i of this._options.hooks.beforeRequest){let n=await i(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}let t=Mp_(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):Epc(r,t,this.abortController,this._options)}_stream(t,r){let i=Number(t.headers.get("content-length"))||0,n=0;return t.status===204?(r&&r({percent:1,totalBytes:i,transferredBytes:n},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){let u=t.body.getReader();r&&r({percent:0,transferredBytes:0,totalBytes:i},new Uint8Array);async function l(){let{done:d,value:s}=await u.read();if(d){a.close();return}if(r){n+=s.byteLength;let o=i===0?0:n/i;r({percent:o,transferredBytes:n,totalBytes:i},s)}a.enqueue(s),await l()}await l()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}};var Apc=e=>{let t=(r,i)=>IIa.create(r,BIa(e,i));for(let r of UHo)t[r]=(i,n)=>IIa.create(i,BIa(e,n,{method:r}));return t.create=r=>Apc(BIa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),Apc(BIa(e,r))),t.stop=WHo,t},nOE=Apc(),Ap_=nOE;var Zp_=ci(Xp_(),1);function Ipc(e){let t=(0,Zp_.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var G__=ci($__(),1),Q__=ci(B1i(),1),Jpc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},Kpc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function Ypc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??Ipc(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,G__.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,l&&(d.authorization=`${l.type} ${l.token}`);let s;try{s=await Ap_(u,{headers:d,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new Jpc(e):c}if(t.allVersions)return s;let o=new Kpc(e,r);if(s["dist-tags"][r]){let{time:c}=s;s=s.versions[s["dist-tags"][r]],s.time=c}else if(r){let c=!!s.versions[r];if(i&&!c)for(let[g,O]of Object.entries(s.versions))O.deprecated&&delete s.versions[g];if(!c){let g=Object.keys(s.versions);if(r=Q__.default.maxSatisfying(g,r),!r)throw o}let{time:b}=s;if(s=s.versions[r],s.time=b,!s)throw o}return s}async function LIa(e,t){let{version:r}=await Ypc(e.toLowerCase(),t);return r}async function PMi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:LIa(e.packageName,{version:t?"prerelease":"latest"})}var J__=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],t$o=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=M0.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new NHo(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),u=this.getCliName();(n==null||a==null||u==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:u}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.64.8"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Gs.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new w9}failWithoutThrowing(t,r){this.didSucceed=!1,IHo({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await u7n()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await hp_({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1947
1947
  `)||(r+=`
1948
1948
  `),this.stderr.info(r))}catch{}}async exitIfFailed(){this.didSucceed||await this.exit()}exitProgram({code:t}={}){process.exit(t??(this.didSucceed?0:1))}longestWorkspaceName;registerWorkspaces(t){let r=j3s(t.map(i=>i.type==="docs"?"docs":i.workspaceName??"api"),i=>i.length);r!=null&&(this.longestWorkspaceName=r)}project;registerProject(t){this.project=t}runTask(t){return this.runTaskWithInit(this.constructTaskInit(),t)}addTask(){return this.addTaskWithInit(this.constructTaskInit())}async runTaskForWorkspace(t,r){await this.runTaskWithInit(this.constructTaskInitForWorkspace(t),r)}addTaskWithInit(t){let r=new SIa(t);return this.ttyAwareLogger.registerTask(r),r}USE_NODE_18_OR_ABOVE_MESSAGE="The Fern CLI requires Node 18+ or above.";async runTaskWithInit(t,r){let i=this.addTaskWithInit(t).start(),n;try{n=await r(i)}catch(a){throw a.message.includes("globalThis")?(i.logger.error(this.USE_NODE_18_OR_ABOVE_MESSAGE),i.failWithoutThrowing()):i.failWithoutThrowing(void 0,a),new w9}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await u7n()).sendEvent(t)}logger=KXt((t,...r)=>this.log(t,...r));stderr=KXt((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=K__(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?K__(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=J__[this.numTasks++%J__.length],u=Gs.hex(a)(n);return{...this.constructTaskInit(),logPrefix:u}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===AB.Failure&&(this.didSucceed=!1)},instrumentPostHogEvent:async t=>{await this.instrumentPostHogEvent(t)},shouldBufferLogs:!1}}log(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}])}logStderr(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}],{stderr:!0})}logImmediately(t,{stderr:r=!1}={}){let i=t.filter(n=>Kwi.indexOf(n.level)>=Kwi.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===M0.Debug,stderr:r})}_suppressUpgradeMessage=!1;suppressUpgradeMessage(){this._suppressUpgradeMessage=!0}_isUpgradeAvailable;async isUpgradeAvailable({includePreReleases:t=!1}={}){if(this._isUpgradeAvailable==null){this.logger.debug(`Checking if ${this.environment.packageName} upgrade is available...`);let r=await PMi({cliEnvironment:this.environment,includePreReleases:t}),i=Gae(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await FHo({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){return await opc({message:t,default:r})}async getInput(t){return await upc({message:t.message,default:t.default})}};function K__(e){return`[${e}]:`}var zI_=require("fs/promises");function OFe({breadcrumbs:e=[],title:t,subtitle:r}){let i=[];return e.length>0&&i.push(Gs.blue(e.join(" -> "))),i.push(t),r!=null&&i.push(Gs.dim(r)),i.join(`
1949
1949
  `)}var SM_=require("fs/promises");var fHt=class{generatorsConfiguration;workspaceName;cliVersion;absoluteFilePath;changelog;constructor({generatorsConfiguration:t,workspaceName:r,cliVersion:i,absoluteFilePath:n,changelog:a}){this.generatorsConfiguration=t,this.workspaceName=r,this.cliVersion=i,this.absoluteFilePath=n,this.changelog=a}};var EMe=class extends fHt{definition;sources;type="fern";constructor({definition:t,sources:r,...i}){super(i),this.definition=t,this.sources=r??[]}async getDefinition(){return this.definition}async toFernWorkspace(){return this}getSources(){return this.sources}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};var UIa=class{context;constructor(t){this.context=t}};var r$o=class e{files={};directories={};getAllFiles(){let t={},r=(i,n)=>{for(let[u,l]of Object.entries(i.files)){let d=n!=null?yy.of(`${n}${PVt}${u}`):yy.of(u);t[d]=l}let a=Object.keys(i.directories).sort();for(let u of a){let l=n!=null?`${n}${PVt}${u}`:u,d=i.directories[u];r(d,l)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split(PVt))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[yy.of(t[0])]??={};let[r,...i]=t;if(r==null)throw new Error(`Internal error; cannot add file with path: ${t}`);return this.directories[r]||(this.directories[r]=new e),this.directories[r].getOrCreateFileRecursive(i)}};var vJi=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new r$o,this.rootApiFile={name:"api","error-discrimination":{strategy:"status-code"}}}setDisplayName({displayName:t}){this.rootApiFile["display-name"]=t}addNavigation({navigation:t}){this.packageMarkerFile.navigation=t}setServiceInfo(t,{auth:r,"base-path":i,"display-name":n,docs:a}){let u=this.getOrCreateFile(t);u.service==null&&(u.service={auth:!1,"base-path":"",endpoints:{}}),r!=null&&(u.service.auth=r),i!=null&&(u.service["base-path"]=i),n!=null&&(u.service["display-name"]=n),a!=null&&(u.docs=a)}addAudience(t){this.rootApiFile.audiences==null&&(this.rootApiFile.audiences=[]),this.rootApiFile.audiences.push(t)}setAuth(t){this.rootApiFile.auth=t}addAuthScheme({name:t,schema:r}){this.rootApiFile["auth-schemes"]==null&&(this.rootApiFile["auth-schemes"]={}),this.rootApiFile["auth-schemes"][t]==null&&(this.rootApiFile["auth-schemes"][t]=r)}setDefaultEnvironment(t){this.rootApiFile["default-environment"]=t}setDefaultUrl(t){this.rootApiFile["default-url"]=t}setBasePath(t){this.basePath=t}setApiVersion(t){this.rootApiFile.version=t}getEnvironmentType(){let t=Object.entries(this.rootApiFile.environments??{})[0];if(t!=null)return Jkt(t[1],{singleBaseUrl:()=>"single",multipleBaseUrls:()=>"multi"})}addEnvironment({name:t,schema:r}){this.rootApiFile.environments==null&&(this.rootApiFile.environments={}),this.rootApiFile.environments[t]=r}getGlobalHeaderNames(){let t=Object.keys(this.rootApiFile.headers??{});if(this.rootApiFile["auth-schemes"]!=null)for(let i of Object.values(this.rootApiFile["auth-schemes"]))Y__(i)&&t.push(i.header);let r=this.getVersionHeader();return r!=null&&t.push(r),new Set(t)}getAuthHeaderName(){if(this.rootApiFile["auth-schemes"]!=null){for(let t of Object.values(this.rootApiFile["auth-schemes"]))if(Y__(t))return t.header;return"Authorization"}}addGlobalHeader({name:t,schema:r}){let i=this.getVersionHeader();i!=null&&i===t||(this.rootApiFile.headers==null&&(this.rootApiFile.headers={}),this.rootApiFile.headers[t]=r)}addIdempotencyHeader({name:t,schema:r}){this.rootApiFile["idempotency-headers"]==null&&(this.rootApiFile["idempotency-headers"]={}),this.rootApiFile["idempotency-headers"][t]=r}addVariable({name:t,schema:r}){this.rootApiFile.variables==null&&(this.rootApiFile.variables={}),this.rootApiFile.variables[t]=r}addImport({file:t,fileToImport:r,alias:i}){if(t===r)return;let n=i??T_((Nxe(r)+"/"+sWi(r,{stripExtension:!0})).replaceAll("__package__","root"));if(t===yy.of(n3))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[n]=Fjo(Nxe(vzn.of(`/${t}`)),vzn.of(`/${r}`)),n;let a=this.getOrCreateFile(t);return a.imports==null&&(a.imports={}),a.imports[n]=Fjo(Nxe(vzn.of(`/${t}`)),vzn.of(`/${r}`)),n}addType(t,{name:r,schema:i}){if(t===yy.of(n3))return;let n=this.getOrCreateFile(t);n.types==null&&(n.types={}),n.types[r]=i}addTypeExample(t,r,i){let n=this.getOrCreateFile(t);n.types==null&&(n.types={});let a=n.types[r];a!=null&&(typeof a=="string"?n.types[r]={type:a,examples:[i]}:(a.examples==null&&(a.examples=[]),a.examples.push(i)))}addError(t,{name:r,schema:i}){let n=this.getOrCreateFile(t);n.errors==null&&(n.errors={}),n.errors[r]==null?n.errors[r]=i:n.errors[r]?.type!==i.type&&(n.errors[r]={"status-code":i["status-code"],type:"unknown"})}addErrorExample(t,{name:r,example:i}){let n=this.getOrCreateFile(t);if(n.errors==null)return;let a=n.errors[r];if(a==null)return;a.examples==null&&(a.examples=[]),(a.examples.some(l=>mEe(l,i))??!1)||a.examples?.push(i)}addEndpoint(t,{name:r,schema:i,source:n}){let a=this.getOrCreateFile(t);a.service==null&&(a.service={auth:!1,"base-path":"",endpoints:{}}),n!=null&&(a.service.source=n),a.service.endpoints[r]=i}addWebhook(t,{name:r,schema:i}){let n=this.getOrCreateFile(t);n.webhooks==null&&(n.webhooks={}),n.webhooks[r]=i}addChannel(t,{channel:r}){let i=this.getOrCreateFile(t);i.channel=r;let n=this.basePath;n!=null&&(i.channel.path=WN(n,r.path))}addChannelExample(t,{example:r}){let i=this.getOrCreateFile(t);i.channel==null&&(i.channel={path:"",auth:!1}),i.channel.messages==null&&(i.channel.messages={}),i.channel.examples==null&&(i.channel.examples=[]),i.channel.examples.push(r)}addChannelMessage(t,{messageId:r,message:i}){let n=this.getOrCreateFile(t);n.channel==null&&(n.channel={path:"",auth:!1}),n.channel.messages==null&&(n.channel.messages={}),n.channel.messages[r]=i}build(){let t=this.root.getAllFiles(),r=this.basePath;if(r!=null){this.packageMarkerFile.service!=null&&(this.packageMarkerFile.service={...this.packageMarkerFile.service,endpoints:Object.fromEntries(Object.entries(this.packageMarkerFile.service.endpoints).map(([n,a])=>[n,{...a,path:WN(r,a.path)}]))});for(let n of Object.values(t))n.service!=null&&(n.service={...n.service,endpoints:Object.fromEntries(Object.entries(n.service.endpoints).map(([a,u])=>[a,{...u,path:WN(r,u.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===zS?this.packageMarkerFile:this.root.getOrCreateFile(t)}getVersionHeader(){if(this.rootApiFile.version!=null)return typeof this.rootApiFile.version.header=="string"?this.rootApiFile.version.header:this.rootApiFile.version.header.value}};function Y__(e){return e?.header!=null}var Qae={openapi:e=>({...e,type:"openapi",_visit:function(t){return Qae._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return Qae._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"openapi":return t.openapi(e);case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var i8n={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return i8n._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var aL={basic:e=>({...e,type:"basic",_visit:function(t){return aL._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return aL._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return aL._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return aL._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return aL._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"basic":return t.basic(e);case"bearer":return t.bearer(e);case"header":return t.header(e);case"query":return t.query(e);case"oauth":return t.oauth(e);default:return t._other(e)}}};var vO={primitive:e=>({value:e,type:"primitive",_visit:function(t){return vO._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return vO._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return vO._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return vO._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return vO._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return vO._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return vO._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return vO._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e.value);case"object":return t.object(e);case"array":return t.array(e.value);case"map":return t.map(e.value);case"enum":return t.enum(e.value);case"literal":return t.literal(e.value);case"oneOf":return t.oneOf(e.value);case"unknown":return t.unknown(e.value);default:return t._other(e)}}};var w_={int:e=>({value:e,type:"int",_visit:function(t){return w_._visit(this,t)}}),int64:e=>({value:e,type:"int64",_visit:function(t){return w_._visit(this,t)}}),uint:e=>({value:e,type:"uint",_visit:function(t){return w_._visit(this,t)}}),uint64:e=>({value:e,type:"uint64",_visit:function(t){return w_._visit(this,t)}}),float:e=>({value:e,type:"float",_visit:function(t){return w_._visit(this,t)}}),double:e=>({value:e,type:"double",_visit:function(t){return w_._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return w_._visit(this,t)}}),datetime:e=>({value:e,type:"datetime",_visit:function(t){return w_._visit(this,t)}}),date:e=>({value:e,type:"date",_visit:function(t){return w_._visit(this,t)}}),base64:e=>({value:e,type:"base64",_visit:function(t){return w_._visit(this,t)}}),boolean:e=>({value:e,type:"boolean",_visit:function(t){return w_._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e.value);case"int64":return t.int64(e.value);case"uint":return t.uint(e.value);case"uint64":return t.uint64(e.value);case"float":return t.float(e.value);case"double":return t.double(e.value);case"string":return t.string(e.value);case"datetime":return t.datetime(e.value);case"date":return t.date(e.value);case"base64":return t.base64(e.value);case"boolean":return t.boolean(e.value);default:return t._other(e)}}};var n8n={boolean:e=>({value:e,type:"boolean",_visit:function(t){return n8n._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return n8n._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"boolean":return t.boolean(e.value);case"string":return t.string(e.value);default:return t._other(e)}}};var jMi={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return jMi._visit(this,t)}}),undiscriminated:e=>({value:e,type:"undiscriminated",_visit:function(t){return jMi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e.value);case"undiscriminated":return t.undiscriminated(e.value);default:return t._other(e)}}};var eH={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated",_visit:(e,t)=>{switch(e){case eH.GenerallyAvailable:return t.generallyAvailable();case eH.Beta:return t.beta();case eH.Deprecated:return t.deprecated();default:return t._other()}}};var mFe={cursor:e=>({...e,type:"cursor",_visit:function(t){return mFe._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return mFe._visit(this,t)}}),custom:e=>({...e,type:"custom",_visit:function(t){return mFe._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"cursor":return t.cursor(e);case"offset":return t.offset(e);case"custom":return t.custom(e);default:return t._other(e)}}};var $di={language:e=>({...e,type:"language",_visit:function(t){return $di._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return $di._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"language":return t.language(e);case"sdk":return t.sdk(e);default:return t._other(e)}}};var tH={Curl:"curl",Python:"python",Javascript:"javascript",Typescript:"typescript",Go:"go",Ruby:"ruby",Csharp:"csharp",Java:"java",Js:"js",Node:"node",Ts:"ts",Nodets:"nodets",Golang:"golang",Dotnet:"dotnet",Jvm:"jvm",_visit:(e,t)=>{switch(e){case tH.Curl:return t.curl();case tH.Python:return t.python();case tH.Javascript:return t.javascript();case tH.Typescript:return t.typescript();case tH.Go:return t.go();case tH.Ruby:return t.ruby();case tH.Csharp:return t.csharp();case tH.Java:return t.java();case tH.Js:return t.js();case tH.Node:return t.node();case tH.Ts:return t.ts();case tH.Nodets:return t.nodets();case tH.Golang:return t.golang();case tH.Dotnet:return t.dotnet();case tH.Jvm:return t.jvm();default:return t._other()}}};var dHt={unknown:e=>({value:e,type:"unknown",_visit:function(t){return dHt._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return dHt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"unknown":return t.unknown(e.value);case"full":return t.full(e);default:return t._other(e)}}};var pHt={withStreaming:e=>({...e,type:"withStreaming",_visit:function(t){return pHt._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit:function(t){return pHt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"withStreaming":return t.withStreaming(e);case"withoutStreaming":return t.withoutStreaming(e.value);default:return t._other(e)}}};var rH={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE",_visit:(e,t)=>{switch(e){case rH.Get:return t.get();case rH.Post:return t.post();case rH.Put:return t.put();case rH.Patch:return t.patch();case rH.Delete:return t.delete();case rH.Head:return t.head();case rH.Options:return t.options();case rH.Trace:return t.trace();default:return t._other()}}};var wMi={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return wMi._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return wMi._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return wMi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);default:return t._other(e)}}};var Gdi={file:e=>({...e,type:"file",_visit:function(t){return Gdi._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return Gdi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e.value);default:return t._other(e)}}};var fJ={file:e=>({...e,type:"file",_visit:function(t){return fJ._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return fJ._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return fJ._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return fJ._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return fJ._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return fJ._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return fJ._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var Fy={primitive:e=>({...e,type:"primitive",_visit:function(t){return Fy._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Fy._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Fy._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Fy._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Fy._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Fy._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Fy._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Fy._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Fy._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Fy._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Fy._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e);case"object":return t.object(e);case"array":return t.array(e);case"map":return t.map(e);case"optional":return t.optional(e);case"enum":return t.enum(e);case"reference":return t.reference(e);case"literal":return t.literal(e);case"oneOf":return t.oneOf(e.value);case"nullable":return t.nullable(e);case"unknown":return t.unknown(e);default:return t._other(e)}}};var Xj={int:e=>({...e,type:"int",_visit:function(t){return Xj._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return Xj._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return Xj._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return Xj._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return Xj._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return Xj._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return Xj._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return Xj._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return Xj._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return Xj._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return Xj._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e);case"int64":return t.int64(e);case"uint":return t.uint();case"uint64":return t.uint64();case"float":return t.float();case"double":return t.double(e);case"string":return t.string(e);case"datetime":return t.datetime();case"date":return t.date();case"base64":return t.base64();case"boolean":return t.boolean(e);default:return t._other(e)}}};var vz={boolean:e=>({value:e,type:"boolean",_visit:function(t){return vz._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return vz._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"boolean":return t.boolean(e.value);case"string":return t.string(e.value);default:return t._other(e)}}};var Qdi={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return Qdi._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return Qdi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undiscriminated":return t.undiscriminated(e);default:return t._other(e)}}};var MMe={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return MMe._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return MMe._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return MMe._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);default:return t._other(e)}}};var bC={file:e=>({...e,type:"file",_visit:function(t){return bC._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return bC._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return bC._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return bC._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return bC._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return bC._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return bC._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var xl={primitive:e=>({...e,type:"primitive",_visit:function(t){return xl._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return xl._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return xl._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return xl._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return xl._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return xl._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return xl._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return xl._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return xl._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return xl._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return xl._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e);case"object":return t.object(e);case"array":return t.array(e);case"map":return t.map(e);case"optional":return t.optional(e);case"enum":return t.enum(e);case"reference":return t.reference(e);case"literal":return t.literal(e);case"oneOf":return t.oneOf(e.value);case"nullable":return t.nullable(e);case"unknown":return t.unknown(e);default:return t._other(e)}}};var ak={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return ak._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return ak._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undiscriminated":return t.undiscriminated(e);default:return t._other(e)}}};var up={int:e=>({...e,type:"int",_visit:function(t){return up._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return up._visit(this,t)}}),uint:e=>({...e,type:"uint",_visit:function(t){return up._visit(this,t)}}),uint64:e=>({...e,type:"uint64",_visit:function(t){return up._visit(this,t)}}),float:e=>({...e,type:"float",_visit:function(t){return up._visit(this,t)}}),double:e=>({...e,type:"double",_visit:function(t){return up._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return up._visit(this,t)}}),datetime:e=>({...e,type:"datetime",_visit:function(t){return up._visit(this,t)}}),date:e=>({...e,type:"date",_visit:function(t){return up._visit(this,t)}}),base64:e=>({...e,type:"base64",_visit:function(t){return up._visit(this,t)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return up._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e);case"int64":return t.int64(e);case"uint":return t.uint(e);case"uint64":return t.uint64(e);case"float":return t.float(e);case"double":return t.double(e);case"string":return t.string(e);case"datetime":return t.datetime(e);case"date":return t.date(e);case"base64":return t.base64(e);case"boolean":return t.boolean(e);default:return t._other(e)}}};var Ev={};jo(Ev,{AllOfPropertyConflict:()=>E8n,ArraySchema:()=>bGo,ArraySchemaWithExample:()=>GGo,Availability:()=>d$o,Base64WithExample:()=>UGo,BasicSecurityScheme:()=>h$o,BearerSecurityScheme:()=>y$o,BooleanSchema:()=>dGo,BooleanWithExample:()=>VGo,BytesResponse:()=>b8n,CasingOverrides:()=>g$o,CommonProperty:()=>DGo,CommonPropertyWithExample:()=>tQo,CursorPagination:()=>K$o,CustomCodeSample:()=>Q$o,CustomCodeSampleLanguage:()=>H$o,CustomCodeSampleSdk:()=>G$o,CustomPagination:()=>X$o,DateWithExample:()=>LGo,DatetimeWithExample:()=>FGo,DiscriminatedOneOfSchema:()=>wGo,DiscriminatedOneOfSchemaWithExample:()=>kGo,DoubleSchema:()=>lGo,DoubleWithExample:()=>RGo,Encoding:()=>f$o,Endpoint:()=>Z$o,EndpointExample:()=>P8n,EndpointResponseExample:()=>W$o,EndpointSdkName:()=>dir,EndpointWithExample:()=>Dh_,EnumSchema:()=>s8n,EnumSchemaWithExample:()=>HGo,EnumValue:()=>EMi,ErrorExample:()=>N$o,FernExample:()=>L$o,FileResponse:()=>y8n,FileSchema:()=>T$o,FloatWithExample:()=>xGo,FullEndpointExample:()=>J$o,FullExample:()=>Hq,FullObjectExample:()=>D$o,FullOneOfExample:()=>M$o,GlobalHeader:()=>_Go,Header:()=>AMi,HeaderExample:()=>m8n,HeaderSecurityScheme:()=>v$o,HeaderWithExample:()=>CMi,HttpEndpointServer:()=>g8n,HttpError:()=>F$o,HttpErrorWithExample:()=>TGo,HttpMethod:()=>f8n,IdempotencyHeader:()=>hGo,Int64WithExample:()=>BGo,IntSchema:()=>sGo,IntWithExample:()=>CGo,JsonRequest:()=>z$o,JsonRequestWithExample:()=>MGo,JsonResponse:()=>v8n,JsonResponseWithExample:()=>q8n,KeyValuePair:()=>E$o,LiteralExample:()=>S$o,LiteralSchema:()=>D8n,LiteralSchemaValue:()=>yGo,LongSchema:()=>cGo,MapSchema:()=>gGo,MapSchemaWithExample:()=>QGo,MultipartRequest:()=>h8n,MultipartRequestProperty:()=>I$o,MultipartRequestPropertyEncoding:()=>B$o,MultipartSchema:()=>C$o,NamedFullExample:()=>_ir,Namespace:()=>O$o,NamespaceId:()=>w$o,NullableSchema:()=>mGo,NullableSchemaWithExample:()=>KGo,OauthSecurityScheme:()=>P$o,ObjectProperty:()=>jGo,ObjectPropertyConflictInfo:()=>M8n,ObjectPropertyWithExample:()=>ZGo,ObjectSchema:()=>vGo,ObjectSchemaWithExample:()=>YGo,OctetStreamRequest:()=>_8n,OffsetPagination:()=>Y$o,OneOfSchema:()=>PGo,OneOfSchemaWithExample:()=>XGo,OpenApiIntermediateRepresentation:()=>wh_,OpenApiSource:()=>u$o,OptionalSchema:()=>OGo,OptionalSchemaWithExample:()=>JGo,Pagination:()=>j8n,PathParameter:()=>d8n,PathParameterExample:()=>U$o,PathParameterWithExample:()=>EGo,PrimitiveExample:()=>l8n,PrimitiveSchema:()=>TMi,PrimitiveSchemaValue:()=>pGo,PrimitiveSchemaValueWithExample:()=>WGo,PrimitiveSchemaWithExample:()=>T8n,PropertyKey:()=>c8n,ProtobufEncoding:()=>l$o,ProtobufSource:()=>s$o,QueryParameter:()=>p8n,QueryParameterExample:()=>O8n,QueryParameterWithExample:()=>A8n,QuerySecurityScheme:()=>b$o,ReferencedSchema:()=>pir,Request:()=>x$o,RequestWithExample:()=>AGo,Response:()=>R$o,ResponseWithExample:()=>qGo,Schema:()=>Om,SchemaId:()=>ok,SchemaWithExample:()=>_A,Schemas:()=>uGo,SdkGroup:()=>m$o,SdkGroupInfo:()=>A$o,SdkGroupName:()=>MMi,SecurityScheme:()=>j$o,SecuritySchemeId:()=>_$o,Server:()=>$Ia,Source:()=>c$o,StatusCode:()=>fir,StreamingResponseExample:()=>V$o,StringSchema:()=>fGo,StringSchemaWithExample:()=>NGo,SupportedSdkLanguage:()=>$$o,Tag:()=>p$o,TagId:()=>uk,Tags:()=>q$o,TextResponse:()=>qMi,Uint64WithExample:()=>zGo,UintWithExample:()=>IGo,UnDiscriminatedOneOfSchema:()=>SGo,UnDiscriminatedOneOfSchemaWithExample:()=>eQo,UnknownSchemaWithExample:()=>$Go,Webhook:()=>k$o,WebhookExampleCall:()=>S8n,WebhookHttpMethod:()=>w8n,WebhookWithExample:()=>Eh_,WebsocketChannel:()=>oGo,WebsocketHandshake:()=>eGo,WebsocketHandshakeWithExample:()=>Sh_,WebsocketMessageExample:()=>nGo,WebsocketMessageOrigin:()=>tGo,WebsocketMessageSchema:()=>rGo,WebsocketServer:()=>iGo,WebsocketSessionExample:()=>aGo,WithAvailability:()=>Ah,WithDescription:()=>gf,WithEncoding:()=>Jae,WithInline:()=>GE,WithName:()=>C0,WithNamespace:()=>t0,WithSdkGroupName:()=>om,WithSource:()=>Jh,WithStatusCode:()=>PFe,WithTitle:()=>am,commons:()=>t_c,example:()=>r_c,finalIr:()=>i_c,parseIr:()=>n_c});var t_c={};jo(t_c,{BasicSecurityScheme:()=>h$o,BearerSecurityScheme:()=>y$o,Encoding:()=>f$o,HeaderSecurityScheme:()=>v$o,Namespace:()=>O$o,NamespaceId:()=>w$o,OauthSecurityScheme:()=>P$o,OpenApiSource:()=>u$o,ProtobufEncoding:()=>l$o,ProtobufSource:()=>s$o,QuerySecurityScheme:()=>b$o,SchemaId:()=>ok,SdkGroup:()=>m$o,SdkGroupName:()=>MMi,SecurityScheme:()=>j$o,SecuritySchemeId:()=>_$o,Server:()=>$Ia,Source:()=>c$o,StatusCode:()=>fir,Tag:()=>p$o,TagId:()=>uk,WithAvailability:()=>Ah,WithDescription:()=>gf,WithEncoding:()=>Jae,WithInline:()=>GE,WithName:()=>C0,WithNamespace:()=>t0,WithSdkGroupName:()=>om,WithSource:()=>Jh,WithStatusCode:()=>PFe,WithTitle:()=>am});var At={};jo(At,{JsonError:()=>a8n,ParseError:()=>o8n,any:()=>fh_,bigint:()=>Z__,boolean:()=>dh_,booleanLiteral:()=>lh_,date:()=>k__,discriminant:()=>mh_,enum_:()=>n$o,getObjectLikeUtils:()=>_Ht,getObjectUtils:()=>bJi,getSchemaUtils:()=>Wq,isProperty:()=>DMi,lazy:()=>eh_,lazyObject:()=>uh_,list:()=>o$o,number:()=>ph_,object:()=>a$o,objectWithoutOptionalProperties:()=>oh_,optional:()=>Xpc,property:()=>rh_,record:()=>vh_,set:()=>bh_,string:()=>_h_,stringLiteral:()=>ch_,transform:()=>Zpc,undiscriminatedUnion:()=>Oh_,union:()=>jh_,unknown:()=>hh_,withParsedProperties:()=>e_c});var Mj={BIGINT:"bigint",DATE:"date",ENUM:"enum",LIST:"list",STRING_LITERAL:"stringLiteral",BOOLEAN_LITERAL:"booleanLiteral",OBJECT:"object",ANY:"any",BOOLEAN:"boolean",NUMBER:"number",STRING:"string",UNKNOWN:"unknown",RECORD:"record",SET:"set",UNION:"union",UNDISCRIMINATED_UNION:"undiscriminatedUnion",OPTIONAL:"optional"};function pA(e,t){return`Expected ${t}. Received ${cmE(e)}.`}function cmE(e){if(Array.isArray(e))return"list";if(e===null)return"null";if(e instanceof BigInt)return"BigInt";switch(typeof e){case"string":return`"${e}"`;case"bigint":case"number":case"boolean":case"undefined":return`${e}`}return typeof e}function oL(e){return{...e,json:X__(e.json),parse:X__(e.parse)}}function X__(e){return(t,r)=>{let i=e(t,r),{skipValidation:n=!1}=r??{};return!i.ok&&n?(console.warn(["Failed to validate.",...i.errors.map(a=>" - "+(a.path.length>0?`${a.path.join(".")}: ${a.message}`:a.message))].join(`
@@ -1957,7 +1957,7 @@ plugins:
1957
1957
  - enum_type=string
1958
1958
  - default_response=false
1959
1959
  - source_root=${e}
1960
- `}async function zFe({context:e,specs:t,relativePathToDependency:r}){let i=new XXo({context:e}),n=t.filter(l=>l.type==="openapi").map(l=>({...l,relativePathToDependency:r})),a=t.filter(l=>l.type==="protobuf"),u=await Promise.all(a.map(async l=>NHE({generator:i,protobufSpec:l,relativePathToDependency:r})));return[...n,...u]}async function NHE({generator:e,protobufSpec:t,relativePathToDependency:r}){return{type:"openapi",absoluteFilepath:await e.generate({absoluteFilepathToProtobufRoot:t.absoluteFilepathToProtobufRoot,absoluteFilepathToProtobufTarget:t.absoluteFilepathToProtobufTarget,relativeFilepathToProtobufRoot:t.relativeFilepathToProtobufRoot,local:t.generateLocally}),absoluteFilepathToOverrides:t.absoluteFilepathToOverrides,settings:t.settings,source:{type:"protobuf",relativePathToDependency:r,root:t.absoluteFilepathToProtobufRoot,file:t.absoluteFilepathToProtobufTarget}}}var kC_=require("fs"),B9n=require("fs/promises");var eB_=require("os"),tB_=ci(require("path"),1),rB_=require("stream/promises"),iB_=ci(ako(),1),nB_=ci(dne(),1);var RPc=ci(e$i(),1);var xP;(function(e){e.FILE_READ="FILE_READ",e.FILE_PARSE="FILE_PARSE",e.FILE_MISSING="FILE_MISSING",e.STRUCTURE_VALIDATION="STRUCTURE_VALIDATION",e.JSONSCHEMA_VALIDATION="JSONSCHEMA_VALIDATION",e.DEPENDENCY_NOT_LISTED="DEPENDENCY_NOT_LISTED",e.FAILED_TO_LOAD_DEPENDENCY="FAILED_TO_LOAD_DEPENDENCY",e.EXPORTING_PACKAGE_MARKER_OTHER_KEYS="EXPORTING_PACKAGE_MARKER_OTHER_KEYS",e.EXPORT_PACKAGE_HAS_DEFINITIONS="EXPORT_PACKAGE_HAS_DEFINITIONS",e.MISCONFIGURED_DIRECTORY="MISCONFIGURED_DIRECTORY"})(xP||(xP={}));var _QE=Mfi();async function aB_({dependencyName:e,dependenciesConfiguration:t,context:r,rootApiFile:i,cliVersion:n,settings:a,loadAPIWorkspace:u}){let l,d={type:xP.FAILED_TO_LOAD_DEPENDENCY,dependencyName:e},s=t.dependencies[e];return s==null?d={type:xP.DEPENDENCY_NOT_LISTED,dependencyName:e}:await r.runInteractiveTask({name:`Download ${mQE(s)}`},async o=>{switch(s.type){case"version":l=await gQE({context:o,dependency:s,cliVersion:n,settings:a,loadAPIWorkspace:u});return;case"local":l=await bQE({context:o,dependency:s,cliVersion:n,settings:a,loadAPIWorkspace:u});return;default:mo(s)}}),l!=null?{didSucceed:!0,definition:l}:{didSucceed:!1,failure:d}}var oB_="dependencies";var hQE="metadata.json",yQE=".fern";function vQE(e){return Vu(hl.of((0,eB_.homedir)()),Qa.of(yQE),Qa.of(oB_),Qa.of(e.organization),Qa.of(e.apiName),Qa.of(e.version))}async function bQE({dependency:e,context:t,cliVersion:r,settings:i,loadAPIWorkspace:n}){if(n==null){t.failWithoutThrowing("Failed to load api definition");return}t.logger.info("Parsing...");let a=await n({absolutePathToWorkspace:e.absoluteFilepath,context:t,cliVersion:r,workspaceName:void 0});if(!a.didSucceed){t.failWithoutThrowing("Failed to load api definition",a.failures);return}t.logger.info("Modifying source filepath ...");let u=await a.workspace.getDefinition({context:t,relativePathToDependency:Qa.of(e.path)},i);return t.logger.info("Loaded..."),u}async function gQE({dependency:e,context:t,cliVersion:r,settings:i,loadAPIWorkspace:n}){let a=vQE(e),u=Vu(a,Qa.of(oB_)),l=Vu(a,Qa.of(hQE)),d;if(!await Sf(u)||!await Sf(l)){t.logger.info("Downloading manifest...");let c=await _QE.definitionRegistry.get(RPc.FernFiddle.OrganizationId(e.organization),RPc.FernFiddle.ApiId(e.apiName),e.version);if(!c.ok){c.error._visit({orgDoesNotExistError:()=>{t.failWithoutThrowing("Organization does not exist")},apiDoesNotExistError:()=>{t.failWithoutThrowing("API does not exist")},versionDoesNotExistError:()=>{t.failWithoutThrowing("Version does not exist")},_other:m=>{t.failWithoutThrowing("Failed to download API manifest",m)}});return}let b=c.body.yamlSchemaVersion!=null?parseInt(c.body.yamlSchemaVersion):void 0,g=sJi(r),O=sJi(c.body.cliVersion);if(b!=null){if(b>1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a higher version of fern. Upgrade this workspace to ${c.body.cliVersion}`);return}else if(b<1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a lower version of fern. Upgrade it to ${r}`);return}}else if(g.major!==O.major||g.minor!==O.minor){t.failWithoutThrowing(`CLI version is ${c.body.cliVersion}. Expected ${g.major}.${g.minor}.x (to match current workspace).`);return}t.logger.info("Downloading..."),t.logger.debug("Remote URL: "+c.body.definitionS3DownloadUrl),await(0,B9n.mkdir)(u,{recursive:!0});try{await OQE({s3PreSignedReadUrl:c.body.definitionS3DownloadUrl,absolutePathToLocalOutput:u})}catch(m){t.failWithoutThrowing("Failed to download API",m);return}d=c.body,await(0,B9n.writeFile)(l,JSON.stringify(d))}else d=JSON.parse((await(0,B9n.readFile)(l)).toString());if(t.logger.info("Parsing..."),n==null){t.failWithoutThrowing("Failed to load API");return}let s=await n({absolutePathToWorkspace:u,context:t,cliVersion:d.cliVersion,workspaceName:void 0});if(!s.didSucceed){t.failWithoutThrowing("Failed to parse dependency after downloading",s.failures);return}if(s.workspace.type==="oss"){t.failWithoutThrowing("Dependency must be a fern workspace.");return}return await s.workspace.getDefinition({context:t},i)}async function OQE({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}){let r=await rF.get(e,{responseType:"stream"}),i=await nB_.default.dir(),n=tB_.default.join(i.path,"api.tgz");await(0,rB_.pipeline)(r.data,(0,kC_.createWriteStream)(n)),await(0,iB_.extract)({file:n,cwd:t})}function mQE(e){switch(e.type){case"version":return`@${e.organization}/${e.apiName}`;case"local":return`${e.path}`;default:mo(e)}}var gB_=ci(dB_(),1);function oko(e,t){for(let[r,i]of r3(e))jQE({relativeFilepath:r,failure:i,logger:t})}function jQE({relativeFilepath:e,failure:t,logger:r}){switch(t.type){case xP.MISCONFIGURED_DIRECTORY:r.error("Misconfigured fern directory: please see the docs at https://buildwithfern.com/learn/api-definition/introduction/what-is-the-fern-folder");break;case xP.FILE_READ:r.error("Failed to open file: "+e);break;case xP.FILE_MISSING:r.error("Missing file: "+e);break;case xP.FILE_PARSE:t.error instanceof bSa?r.error(OFe({title:`Failed to parse ${e}: ${t.error.reason}`,subtitle:t.error.mark.snippet})):r.error("Failed to parse file: "+e);break;case xP.STRUCTURE_VALIDATION:for(let i of t.error.issues)for(let{title:n,subtitle:a}of wQE(i))r.error(OFe({title:n,subtitle:a,breadcrumbs:[e,...i.path]}));break;case xP.FAILED_TO_LOAD_DEPENDENCY:r.error("Failed to load dependency: "+t.dependencyName);break;case xP.DEPENDENCY_NOT_LISTED:r.error(`Dependency is not listed in ${GOo}: `+t.dependencyName);break;case xP.EXPORT_PACKAGE_HAS_DEFINITIONS:r.error("Exported package contains API definitions: "+t.pathToPackage);break;case xP.EXPORTING_PACKAGE_MARKER_OTHER_KEYS:r.error(`${t.pathOfPackageMarker} has an export so it cannot define other keys.`);break;case xP.JSONSCHEMA_VALIDATION:t.error.error!=null&&r.error(OFe({title:t.error.error.message??"Unknown error",breadcrumbs:[e,...t.error.error.instancePath.split("/").filter(i=>i!=="")]}));for(let i of t.error.allErrors)i!==t.error.error&&r.debug(OFe({title:i.message??"Unknown error",breadcrumbs:[e,...i.instancePath.split("/").filter(n=>n!=="")]}));break;default:mo(t)}}function wQE(e){switch(e.code){case Jl.invalid_type:return[{title:"Incorrect type",subtitle:`Expected ${Gs.underline(e.expected)} but received ${Gs.underline(e.received)}`}];case Jl.unrecognized_keys:return e.keys.map(t=>({title:"Unexpected key",subtitle:`Encountered unexpected key ${Gs.underline(t)}`}));case Jl.invalid_enum_value:return[{title:"Unrecognized value",subtitle:`Allowed values: ${e.options.map(t=>Gs.underline(t)).join(", ")}`}];case Jl.invalid_union:case Jl.invalid_arguments:case Jl.invalid_return_type:case Jl.invalid_date:case Jl.invalid_string:case Jl.too_small:case Jl.too_big:case Jl.invalid_intersection_types:case Jl.not_multiple_of:case Jl.custom:default:return[{title:e.message}]}}var pB_=require("fs/promises");async function _B_(e,t){let r=[];for(let i of await Vxe(e,t))r.push(await SQE({relativeFilepath:xq(e,i),absoluteFilepath:i}));return r}async function SQE({relativeFilepath:e,absoluteFilepath:t}){return{relativeFilepath:e,absoluteFilepath:t,fileContents:(await(0,pB_.readFile)(t)).toString()}}async function hB_(e){let t={},r={};function i(n){try{t[n.relativeFilepath]={defaultUrl:void 0,contents:qd.load(n.fileContents,{schema:qd.CORE_SCHEMA}),rawContents:n.fileContents}}catch(a){r[n.relativeFilepath]={type:xP.FILE_PARSE,error:a}}}return await Promise.all(e.map(i)),Object.keys(r).length>0?{didSucceed:!1,failures:r}:{didSucceed:!0,files:t}}async function yB_({dependenciesConfiguration:e,structuralValidationResult:t,context:r,cliVersion:i,settings:n,loadAPIWorkspace:a}){let u={},l={},d={};return await Promise.all(r3(t.packageMarkers).map(async([s,o])=>{if(o.contents.export==null)u[s]=o;else{let{export:c,...b}=o.contents;if(pZ(b)>0)d[s]={type:xP.EXPORTING_PACKAGE_MARKER_OTHER_KEYS,pathOfPackageMarker:s};else{let g=Ud(s);if(fVt(t.namedDefinitionFiles).some(m=>m!==s&&m.startsWith(g)))d[s]={type:xP.EXPORT_PACKAGE_HAS_DEFINITIONS,pathToPackage:g};else{let m=await aB_({dependencyName:typeof o.contents.export=="string"?o.contents.export:o.contents.export.dependency,dependenciesConfiguration:e,context:r,rootApiFile:t.rootApiFile.contents,cliVersion:i,settings:n,loadAPIWorkspace:a});m.didSucceed?l[Ud(s)]={definition:m.definition,url:typeof o.contents.export=="object"?o.contents.export.url:void 0}:d[s]=m.failure}}}})),pZ(d)>0?{didSucceed:!1,failures:d}:{didSucceed:!0,packageMarkers:u,importedDefinitions:l}}var vB_=ci(require("path"),1);var LPc={};jo(LPc,{additionalProperties:()=>AQE,default:()=>TQE,definitions:()=>qQE,properties:()=>EQE,required:()=>MQE,type:()=>DQE});var DQE="object",EQE={docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"default-url":{oneOf:[{type:"string"},{type:"null"}]},"default-environment":{oneOf:[{type:"string"},{type:"null"}]},environments:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/environments.EnvironmentSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/auth.ApiAuthSchema"},{type:"null"}]},"auth-schemes":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/auth.AuthSchemeDeclarationSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},name:{type:"string"},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},"error-discrimination":{oneOf:[{$ref:"#/definitions/file.ErrorDiscriminationSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},errors:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"idempotency-headers":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},variables:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/variables.VariableDeclarationSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"null"}]},product:{oneOf:[{$ref:"#/definitions/products.ProductDeclarationSchema"},{type:"null"}]},version:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},MQE=["name"],AQE=!1,qQE={"environments.SingleBaseUrlEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},url:{type:"string"}},required:["url"],additionalProperties:!1},"environments.MultipleBaseUrlsEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},urls:{type:"object",additionalProperties:{type:"string"}}},required:["urls"],additionalProperties:!1},"environments.EnvironmentSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/environments.SingleBaseUrlEnvironmentSchema"},{$ref:"#/definitions/environments.MultipleBaseUrlsEnvironmentSchema"}]},"auth.AuthSchemeReferenceSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{type:"string"}},required:["scheme"],additionalProperties:!1},"auth.AnyAuthItem":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"}]},"auth.AnyAuthSchemesSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},any:{type:"array",items:{$ref:"#/definitions/auth.AnyAuthItem"}}},required:["any"],additionalProperties:!1},"auth.ApiAuthSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"},{$ref:"#/definitions/auth.AnyAuthSchemesSchema"}]},"auth.OAuthAccessTokenRequestPropertiesSchema":{type:"object",properties:{"client-id":{oneOf:[{type:"string"},{type:"null"}]},"client-secret":{oneOf:[{type:"string"},{type:"null"}]},scopes:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthAccessTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthGetTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthRefreshTokenRequestPropertiesSchema":{type:"object",properties:{"refresh-token":{type:"string"}},required:["refresh-token"],additionalProperties:!1},"auth.OAuthRefreshTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthRefreshTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"oauth"},type:{const:"client-credentials"},scopes:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"client-id-env":{oneOf:[{type:"string"},{type:"null"}]},"client-secret-env":{oneOf:[{type:"string"},{type:"null"}]},"token-prefix":{oneOf:[{type:"string"},{type:"null"}]},"token-header":{oneOf:[{type:"string"},{type:"null"}]},"get-token":{$ref:"#/definitions/auth.OAuthGetTokenEndpointSchema"},"refresh-token":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenEndpointSchema"},{type:"null"}]}},required:["scheme","type","get-token"],additionalProperties:!1},"auth.HeaderAuthSchemeSchema":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},header:{type:"string"},type:{oneOf:[{type:"string"},{type:"null"}]},prefix:{oneOf:[{type:"string"},{type:"null"}]}},required:["header"],additionalProperties:!1},"auth.AuthVariable":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.BasicAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"basic"},username:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]},password:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.BearerAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"bearer"},token:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.AuthSchemeDeclarationSchema":{anyOf:[{$ref:"#/definitions/auth.OAuthSchemeSchema"},{$ref:"#/definitions/auth.HeaderAuthSchemeSchema"},{$ref:"#/definitions/auth.BasicAuthSchemeSchema"},{$ref:"#/definitions/auth.BearerAuthSchemeSchema"}]},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"file.PropertyBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"property"},"property-name":{type:"string"}},required:["strategy","property-name"],additionalProperties:!1},"file.StatusCodeBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"status-code"}},required:["strategy"],additionalProperties:!1},"file.ErrorDiscriminationSchema":{anyOf:[{$ref:"#/definitions/file.PropertyBasedErrorDiscrimination"},{$ref:"#/definitions/file.StatusCodeBasedErrorDiscrimination"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"variables.VariableDeclarationDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"variables.VariableDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/variables.VariableDeclarationDetailed"}]},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"versioning.VersionValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionValue":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionValueDetailed"}]},"versioning.VersionDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionDeclarationHeaderObjectSchema"}]},"versioning.VersionDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/versioning.VersionValue"}},header:{$ref:"#/definitions/versioning.VersionDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1},"products.ProductValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},versions:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"products.ProductValue":{anyOf:[{type:"string"},{$ref:"#/definitions/products.ProductValueDetailed"}]},"products.ProductDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"products.ProductDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/products.ProductDeclarationHeaderObjectSchema"}]},"products.ProductDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/products.ProductValue"}},header:{$ref:"#/definitions/products.ProductDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1}},TQE={type:DQE,properties:EQE,required:MQE,additionalProperties:AQE,definitions:qQE};var UPc={};jo(UPc,{additionalProperties:()=>IQE,default:()=>xQE,definitions:()=>zQE,properties:()=>BQE,type:()=>CQE});var CQE="object",BQE={docs:{oneOf:[{type:"string"},{type:"null"}]},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]}},IQE=!1,zQE={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{type:"boolean"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1}},xQE={type:CQE,properties:BQE,additionalProperties:IQE,definitions:zQE};var VPc={};jo(VPc,{additionalProperties:()=>FQE,default:()=>UQE,definitions:()=>LQE,properties:()=>NQE,type:()=>RQE});var RQE="object",NQE={imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},navigation:{oneOf:[{$ref:"#/definitions/file.Navigation"},{type:"null"}]},export:{oneOf:[{$ref:"#/definitions/file.Export"},{type:"null"}]}},FQE=!1,LQE={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{type:"boolean"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1},"file.Navigation":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"file.ExportDetailed":{type:"object",properties:{dependency:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]}},required:["dependency"],additionalProperties:!1},"file.Export":{anyOf:[{type:"string"},{$ref:"#/definitions/file.ExportDetailed"}]}},UQE={type:RQE,properties:NQE,additionalProperties:FQE,definitions:LQE};function bB_({files:e,absolutePathToDefinition:t}){let r,i={},n={},a={};for(let[u,l]of r3(e)){let d=l.contents,s=o=>{a[u]={type:xP.JSONSCHEMA_VALIDATION,error:o}};if(u===n3){let o=vVt(d,LPc);if(o.success){let c=JN.serialization.RootApiFileSchema.parseOrThrow(d);r={defaultUrl:c["default-url"],contents:c,rawContents:l.rawContents}}else s(o)}else if(vB_.default.basename(u)===zS){let o=vVt(d,VPc);if(o.success){let c=JN.serialization.PackageMarkerFileSchema.parseOrThrow(d);n[u]={defaultUrl:typeof c.export=="object"?c.export.url:void 0,contents:c,rawContents:l.rawContents}}else s(o)}else{let o=vVt(d,UPc);if(o.success){let c=JN.serialization.DefinitionFileSchema.parseOrThrow(d);i[u]={defaultUrl:void 0,contents:c,rawContents:l.rawContents,absoluteFilePath:Vu(t,u)}}else s(o)}}return r==null?{didSucceed:!1,failures:{[Qa.of(n3)]:{type:xP.FILE_MISSING},...a}}:Object.keys(a).length>0?{didSucceed:!1,failures:a}:{didSucceed:!0,namedDefinitionFiles:i,rootApiFile:r,packageMarkers:n}}var Vir=class extends fHt{type="fern";context;fernWorkspaces={};loadAPIWorkspace;constructor({context:t,loadAPIWorkspace:r,...i}){super(i),this.context=t,this.loadAPIWorkspace=r}async getDefinition({context:t},r){return(await this.toFernWorkspace({context:t},r)).definition}async toFernWorkspace({context:t},r){let i=(0,gB_.default)(r??{}),n=this.fernWorkspaces[i];if(n==null){let a=t||this.context,u=Vu(this.absoluteFilePath,Qa.of(v9)),l=await U2s({absolutePathToWorkspace:this.absoluteFilePath,context:a}),d=await _B_(u,"{yml,yaml}"),s=await hB_(d);if(!s.didSucceed)return oko(s.failures,a.logger),a.failAndThrow();let o=bB_({files:s.files,absolutePathToDefinition:u});if(!o.didSucceed)return oko(o.failures,a.logger),a.failAndThrow();let c=await yB_({dependenciesConfiguration:l,structuralValidationResult:o,context:a,cliVersion:this.cliVersion,settings:r,loadAPIWorkspace:this.loadAPIWorkspace});if(!c.didSucceed)return oko(c.failures,a.logger),a.failAndThrow();let b={absoluteFilePath:u,rootApiFile:o.rootApiFile,namedDefinitionFiles:o.namedDefinitionFiles,packageMarkers:c.packageMarkers,importedDefinitions:c.importedDefinitions};r?.auth!=null&&(b={...b,rootApiFile:{...b.rootApiFile,contents:{...b.rootApiFile.contents,auth:r?.auth}}}),n=new EMe({absoluteFilePath:this.absoluteFilePath,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:l,workspaceName:this.workspaceName,definition:b,cliVersion:this.cliVersion,sources:[]}),this.fernWorkspaces[i]=n}return n}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};var yb=class e{breadcrumbs=[];context;static STRING=Ws.TypeReference.primitive({v1:"STRING",v2:Ws.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Ws.TypeReference.container(Ws.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}};var OB_={[hy.GenerationLanguage.PHP]:new Set(["abstract","and","as","break","callable","case","catch","class","clone","const","continue","declare","default","do","echo","else","elseif","enddeclare","endfor","endforeach","endif","endswitch","endwhile","extends","final","finally","fn","for","foreach","function","global","goto","list","if","implements","include","include_once","instanceof","insteadof","interface","match","namespace","new","or","parent","Parent","print","private","protected","public","readonly","require","require_once","return","static","switch","throw","trait","try","use","var","while","xor","yield"].flatMap(e=>[e,iz(e)])),[hy.GenerationLanguage.TYPESCRIPT]:new Set(["any","as","boolean","break","case","catch","class","const","constructor","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","let","module","new","null","number","of","package","private","protected","public","require","return","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","Date","Error","File","Object","Record"]),[hy.GenerationLanguage.JAVA]:new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","false","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","true","try","void","volatile","while"]),[hy.GenerationLanguage.PYTHON]:new Set(["False","None","True","and","as","assert","async","","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","float","int","complex","bool","uuid","list","set","map","long","self","all"]),[hy.GenerationLanguage.GO]:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[hy.GenerationLanguage.RUBY]:new Set(["__ENCODING__","__LINE__","__FILE__","alias","and","begin","break","case","class","def","defined","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield","Object","JSON","Date","DateTime"]),[hy.GenerationLanguage.CSHARP]:new Set(["abstract","as","base","bool","break","byte","case","catch","char","checked","class","const","continue","decimal","default","delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","goto","if","implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","operator","out","override","params","private","protected","public","readonly","ref","return","sbyte","sealed","short","sizeof","stackalloc","static","string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","ushort","using","virtual","void","volatile","while","add","and","alias","ascending","args","async","","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","managed","nameof","nint","not","notnull","nuint","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value","var","when","where","with","yield"]),[hy.GenerationLanguage.SWIFT]:new Set([])};var VQE=["go","ruby"];function NMe({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let u=c=>({unsafeName:c,safeName:WQE({name:c,keywords:HQE({generationLanguage:e,keywords:t})})}),l=T_(n),d=iz(l),s=qVi(n),o=DVi(l);return r&&(!QQE(o)&&(e==null||VQE.includes(e))&&(l=o.map((c,b)=>{if(b>0){let g=uko(c);if(g!=null)return g;if(sko(c))return c.toUpperCase()}return c}).join(""),d=o.map((c,b)=>{let g=uko(c);return g??(sko(c)?c.toUpperCase():b===0?iz(c):c)}).join("")),s=n.split(" ").map(c=>c.split(/(\d+)/).map(qVi).join("")).join("_")),{originalName:n,camelCase:u(a?.casingOverrides?.camel??l),snakeCase:u(a?.casingOverrides?.snake??s),screamingSnakeCase:u(a?.casingOverrides?.["screaming-snake"]??s.toUpperCase()),pascalCase:u(a?.casingOverrides?.pascal??d)}},generateNameAndWireValue:({name:n,wireValue:a,opts:u})=>({name:i.generateName(n,u),wireValue:a})};return i}function WQE({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":GQE(e)?"_"+e:e}function HQE({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return OB_[e]}var $QE=/^[0-9]/;function GQE(e){return $QE.test(e)}function QQE(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=uko(i)!=null||sko(i),a=uko(t)!=null||sko(t);return n&&a})}function uko(e){return KQE.get(e.toUpperCase())}function sko(e){return JQE.has(e.toUpperCase())}var JQE=new Set(["ACL","API","ASCII","CPU","CSS","DNS","EOF","GUID","HTML","HTTP","HTTPS","ID","IP","JSON","LHS","QPS","RAM","RHS","RPC","SAML","SCIM","SLA","SMTP","SQL","SSH","SSO","TCP","TLS","TTL","UDP","UI","UID","UUID","URI","URL","UTF8","VM","XML","XMPP","XSRF","XSS"]),KQE=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);var PB_=require("fs/promises");var WPc=class{_map;_path;_lastScalar;_fragments;_count;constructor(){this._map={},this._path=[],this._lastScalar="",this._fragments=[],this._count=0}get map(){return this._map}resolveNode(t,r){if(t.path==="."&&(r="."),!this._map[r]){let{line:i,position:n,lineStart:a}=t;this._map[r]={line:i,position:n,lineStart:a}}t.children&&t.children.length>0&&t.children.forEach(i=>{this.resolveNode(i,(r==="."?"":r)+"."+i.path)})}iterFragments(t,r){for(let i=this._fragments.length-1;i>=0;i--){if(!this._fragments[i].path.startsWith(t)||this._fragments[i].path===t)continue;let n=this._fragments.pop();r(n)}}handleState(t,r){if(t==="close"){let i=r.result,n=r.kind,a=this._path.join(".");if(n==="scalar"){this._path.pop(),this._lastScalar=`${i}`;let{line:u,position:l,lineStart:d}=r;this._path.length===0?this._map["."+i]={line:u,position:l,lineStart:d}:this._fragments.push({path:this._path.join(".")+"."+i,line:u,position:l,lineStart:d})}else if(n==="mapping"){let u={path:a,children:[],line:0,position:0,lineStart:0},l=0;this.iterFragments(a,d=>{l++,!((!d.children||d.children.length===0)&&l%2===1)&&(this._path.length===1?this.resolveNode(d,d.path):(u.children.push({...d,path:d.path.slice(a.length+1)}),u.line=d.line,u.position=d.position,u.lineStart=d.lineStart))}),u.children&&u.children.length>0&&this._fragments.push(u),this._path.pop()}else if(n==="sequence"){let u={path:a,children:[],line:0,position:0,lineStart:0},l=new Set,d=i.length;this.iterFragments(a,s=>{l.has(s.position)||(d--,l.add(s.position),this._path.length===1?this.resolveNode(s,`${a}.${d}`):(u.children.push({...s,path:d.toString()}),u.line=s.line,u.position=s.position,u.lineStart=s.lineStart))}),u.children&&u.children.length>0&&this._fragments.push(u),this._path.pop()}else this._path.pop()}if(t==="open"){if(this._count===0){let{line:i,position:n,lineStart:a}=r;this._map["."]={line:i,position:n,lineStart:a}}this._path.push(this._lastScalar),this._count++}}listen(){return this.handleState.bind(this)}lookup(t){let r=t instanceof Array?t.map(n=>`${n}`).join("."):`${t}`;r.startsWith(".")||(r="."+r),r.startsWith("..")&&(r=r.slice(1)),r=r.replace(/\[/g,".").replace(/\]/g,"");let i=this._map[r];if(i)return{line:i.line+1,column:i.position-i.lineStart+1,position:i.position}}},mB_=WPc;var Api;(function(e){e.WARNING="warning",e.ERROR="error"})(Api||(Api={}));var x9n=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new HPc({logger:t,relativePathToFile:Qa.of(r)}))}collect(t){this.errors.push(t)}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}dedupe(){let t=[],r=new Set,i=0;for(let n of this.errors){let a=n.path?n.path.join("->"):"",u=`${n.message}|${n.level||Api.WARNING}|${a}`;r.has(u)?i++:(r.add(u),t.push(n))}return this.errors=t,i}getErrorStats(){this.dedupe();let t=0,r=0;for(let i of this.errors)i.level===Api.ERROR?t++:r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors)if(!(r.level===Api.WARNING&&!t))switch(r.level){case Api.ERROR:if(this.logger.log(M0.Error,r.message),r.path&&r.path.length>0){let i=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),n=i?`${this.relativeFilepathToSpec}:${i.line}:${i.column}`:r.path.join(" -> ");this.logger.log(M0.Error,` - at location (${n})`)}break}}},HPc=class{logger;relativePathToFile;map=new mB_;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,PB_.readFile)(this.relativePathToFile,"utf-8");qd.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(M0.Warn,`Failed to initialize line number mapping for ${this.relativePathToFile}: ${JSON.stringify(t)}`)}}async getSourceLocation(t){return this.initialized||await this.initialize(),this.map.lookup(t)}};var f8=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;authOverrides;environmentOverrides;globalHeaderOverrides;enableUniqueErrorsPerEndpoint;generateV1Examples;constructor(t){this.args=t,this.spec=t.spec,this.settings=t.settings,this.errorCollector=t.errorCollector,this.logger=t.logger,this.generationLanguage=t.generationLanguage,this.smartCasing=t.smartCasing,this.namespace=t.namespace,this.casingsGenerator=NMe({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs,this.authOverrides=t.authOverrides,this.environmentOverrides=t.environmentOverrides,this.globalHeaderOverrides=t.globalHeaderOverrides,this.enableUniqueErrorsPerEndpoint=t.enableUniqueErrorsPerEndpoint,this.generateV1Examples=t.generateV1Examples}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=t.filter((n,a)=>!(/^\d+$/.test(n)||e.BREADCRUMBS_TO_IGNORE.includes(n)||a===0&&n==="components"||a===1&&n==="schemas"||t[0]==="paths"&&(a===0||a===1&&["get","post","put","delete","patch"].includes(n)||a===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&n==="parameters"))),i=T_(r.join("_"));return i.charAt(0).toUpperCase()+i.slice(1)}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],i=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:i?[...r,i]:r,packagePath:r,file:i}}resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:i}){let n=this.spec,a=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(u=>u.replace(/~1/g,"/"));for(let u of a){if(typeof n!="object"||n==null)return i||this.errorCollector.collect({level:Api.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};n=n[u]}return n==null?(i||this.errorCollector.collect({level:Api.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1}):{resolved:!0,value:n}}getErrorMessageForMissingRef({reference:t}){let r=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/");return r.length>=3&&r[0]==="components"&&r[1]==="schemas"?`Schema ${r[2]} does not exist`:`${t.$ref} does not exist`}async resolveMaybeExternalReference(t){let r=this.spec,i,n=!1,a=null,u;if(this.isExternalReference(t.$ref)){n=!0;let s=t.$ref.split("#"),o=s[0];if(i=s[1],!o)return{resolved:!1};u=o;let c=await fetch(o);if(!c.ok)return{resolved:!1};try{let b=await c.text();try{a=JSON.parse(b),r=a}catch{a=qd.load(b),r=a}if(r==null)return{resolved:!1}}catch{return{resolved:!1}}if(!i)return{resolved:!0,value:r}}let l=i??t.$ref;if(l==null||typeof l!="string")return{resolved:!1};let d=l.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(s=>s.replace(/~1/g,"/"));for(let s of d){if(typeof r!="object"||r==null)return{resolved:!1};r=r[s]}if(r==null)return{resolved:!1};if(n&&typeof r=="object"&&r!==null){let s=new Set;s.add(t.$ref),r=await this.resolveNestedExternalReferences(r,a,s,u)}return{resolved:!0,value:r}}async resolveNestedExternalReferences(t,r,i,n){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let u=[];for(let l of t)u.push(await this.resolveNestedExternalReferences(l,r,i,n));return u}if(this.isReferenceObject(t)){let u=t.$ref;if(this.isExternalReference(u)){if(i.has(u))return t;i.add(u);let l=await this.resolveMaybeExternalReference({$ref:u});if(i.delete(u),l.resolved)return l.value}else{let l=`${n}${u}`;if(i.has(l))return t;i.add(l);let d=r,s=u.substring(2).split("/").map(o=>o.replace(/~1/g,"/").replace(/~0/g,"~"));for(let o of s){if(typeof d!="object"||d===null)return t;d=d[o]}if(d!=null){let o=await this.resolveNestedExternalReferences(d,r,i,n);return i.delete(u),o}i.delete(u)}return t}let a={};for(let[u,l]of Object.entries(t))typeof l=="object"&&l!==null?a[u]=await this.resolveNestedExternalReferences(l,r,i,n):a[u]=l;return a}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let i=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?i.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),i}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:i}){if(t==null)return[];let n=[];if(t.example!=null){let a=this.generateUniqueName({prefix:i??`${r.join("_")}_example`,existingNames:[]});n.push([a,t.example])}return t.examples!=null&&n.push(...Object.entries(t.examples)),n}resolveMaybeReference({schemaOrReference:t,breadcrumbs:r,skipErrorCollector:i}){if(this.isReferenceObject(t)){let n=this.resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:i});return n.resolved?n.value:void 0}return t}resolveExample(t){if(!this.isReferenceObject(t))return t;let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}resolveExampleWithValue(t){if(!this.isReferenceObject(t))return this.returnExampleValue(t);let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}returnExampleValue(t){return this.isExampleWithValue(t)?t.value:t}getPropertyAccess(t){let r=t;for(;this.isReferenceObject(r);){let i=this.resolveReference({reference:r});if(!i.resolved)return;r=i.value}if(!(r.readOnly&&r.writeOnly)){if(r.readOnly)return Lkt.ReadOnly;if(r.writeOnly)return Lkt.WriteOnly}}getAudiences({operation:t,breadcrumbs:r}){let n=new pH.AudienceExtension({operation:t,breadcrumbs:r,context:this}).convert();if(n!=null)return n.audiences}getAvailability({node:t,breadcrumbs:r}){for(;this.isReferenceObject(t);){let a=this.resolveReference({reference:t});if(!a.resolved)return;t=a.value}let n=new pH.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(n!=null)return{status:n,message:void 0};if(t.deprecated===!0)return{status:B9.Deprecated,message:void 0}}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return hf.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t),typeId:t,displayName:r,default:void 0,inline:!1})}typeReferenceToDeclaredTypeName(t){if(t.type!=="named")return;let r=t.typeId;return{typeId:r,fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(r),displayName:t.displayName}}removeSchemaFromInlinedTypes({id:t,inlinedTypes:r}){return Object.fromEntries(Object.entries(r).filter(([i])=>i!==t))}static maybeTrimPrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}generateUniqueName({prefix:t,existingNames:r}){if(!r.includes(t))return t;let i=0;for(;r.includes(`${t}_${i}`);)i++;return`${t}_${i}`}isReferenceObject(t){return typeof t=="object"&&t!==null&&"$ref"in t}isExternalReference(t){return typeof t=="string"&&(t.startsWith("http://")||t.startsWith("https://"))}isReferenceObjectWithIdentifier(t){return this.isReferenceObject(t)&&("title"in t||"name"in t||"messageId"in t)}isExampleWithSummary(t){return typeof t=="object"&&t!=null&&"summary"in t}isExampleWithValue(t){return typeof t=="object"&&t!=null&&"value"in t}isOptional(t){return t.type==="container"&&t.container.type==="optional"}isNullable(t){return t.type==="container"&&t.container.type==="nullable"}isList(t){return t.type==="container"&&t.container.type==="list"}isFile(t){return t.type==="primitive"&&t.primitive.v2?.type==="string"&&t.primitive.v2.validation?.format==="binary"}getAsString(t){if(typeof t=="string")return t}getAsInteger(t){if(typeof t=="number"&&Number.isInteger(t))return t}getAsNumber(t){if(typeof t=="number")return t}getAsBoolean(t){if(typeof t=="boolean")return t}getAsArray(t){if(Array.isArray(t))return t}getAsObject(t){if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}getGroup({groupParts:t,namespace:r}){let i=[];return r!=null&&i.push(r),i.push(...t??[]),i}isObjectSchemaType(t){return t.type==="object"||t.properties!=null}};var Pm=class{breadcrumbs;context;constructor(t){this.breadcrumbs=t.breadcrumbs,this.context=t.context}getExtensionValue(t,r){if(typeof t!="object"||t==null)return;let i=t[this.key];if(i!=null)return i;if(r!=null)return t[r]}};function fF(e){let t=XQE(e),{value:r,done:i}=$Pc(t,"{");return i?{head:r,parts:[]}:{head:r,parts:[...YQE(t)]}}function*YQE(e){let t;do{let{value:r}=$Pc(e,"}"),i=$Pc(e,"{");t=i.done,yield{pathParameter:r,tail:i.value}}while(!t)}function*XQE(e){for(let t of e)yield t}function $Pc(e,t){let r="",i=e.next();for(;i.done!==!0&&i.value!==t;)r+=i.value,i=e.next();return{value:r,done:i.done??!1}}function ARa(e){let t=2166136261;function r(n,a){if(typeof n=="object"&&n!=null){if(a>64){i("[MaxDepthExceeded]");return}if(Array.isArray(n)){i("[");for(let u=0;u<n.length;u++)u>0&&i(","),r(n[u],a+1);i("]")}else i("{"),Object.keys(n).sort().forEach((l,d)=>{d>0&&i(","),i(l),i(":"),r(n[l],a+1)}),i("}")}else i(String(n))}function i(n){for(let a=0;a<n.length;a++){let u=n.charCodeAt(a);t^=u,t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24),t>>>=0}}return r(e,0),t.toString(16)}function Wir({typeReference:e,typeDeclarations:t}){if(e.type==="container"&&e.container.type==="optional")return!0;if(e.type==="named"){let r=t?.[e.typeId];if(r?.shape.type==="alias"&&r?.shape.resolvedType.type==="container"&&r?.shape.resolvedType.container.type==="optional")return!0}return!1}function jB_({fieldName:e,containerType:t,maxDepth:r,currentDepth:i,typeDeclarations:n,skipOptionalProperties:a}){if(i>=r)return Hir({containerType:t});switch(t.type){case"list":{let u=Gq({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?Hir({containerType:t}):{type:"success",example:bm.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:bm.literal({literal:t.literal._visit({boolean:u=>Rd.boolean(u),string:u=>Rd.string({original:u}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:t.literal._visit({boolean:u=>u,string:u=>u,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":{if(a)return Hir({containerType:t});let u=Gq({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?Hir({containerType:t}):{type:"success",example:bm.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"nullable":{if(a)return Hir({containerType:t});let u=Gq({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?Hir({containerType:t}):{type:"success",example:bm.nullable({nullable:u.example,valueType:t.nullable}),jsonExample:u.jsonExample}}case"set":{let u=Gq({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?Hir({containerType:t}):{type:"success",example:bm.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=Gq({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a}),l=Gq({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"||l.type==="failure"?Hir({containerType:t}):{type:"success",example:bm.map({map:[{key:u.example,value:l.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:l.jsonExample}}}default:mo(t)}}function Hir({containerType:e}){switch(e.type){case"list":return{type:"success",example:bm.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:bm.literal({literal:e.literal._visit({boolean:t=>Rd.boolean(t),string:t=>Rd.string({original:t}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:e.literal._visit({boolean:t=>t,string:t=>t,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":return{type:"success",example:bm.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:bm.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:bm.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:bm.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:mo(e)}}function SB_({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return rJE({fieldName:e,default_:ZQE(t.v2),validation:kQE(t.v2)});case"BASE_64":return{type:"success",example:Rd.base64(Gy.BASE64),jsonExample:Gy.BASE64};case"BOOLEAN":return{type:"success",example:Rd.boolean(Gy.BOOLEAN),jsonExample:Gy.BOOLEAN};case"DATE":return{type:"success",example:Rd.date(Gy.DATE),jsonExample:Gy.DATE};case"DATE_TIME":return{type:"success",example:Rd.datetime({datetime:new Date(Gy.DATE_TIME),raw:Gy.DATE_TIME}),jsonExample:Gy.DATE_TIME};case"DOUBLE":return iJE({fieldName:e,validation:eJE(t.v2)});case"FLOAT":return{type:"success",example:Rd.float(Gy.FLOAT),jsonExample:Gy.FLOAT};case"INTEGER":return nJE({fieldName:e,validation:tJE(t.v2)});case"UINT_64":return{type:"success",example:Rd.uint64(Gy.INT64),jsonExample:Gy.INT64};case"UINT":return{type:"success",example:Rd.uint(Gy.UINT),jsonExample:Gy.UINT};case"BIG_INTEGER":return{type:"success",example:Rd.bigInteger(Gy.INT64.toString()),jsonExample:`${Gy.INT64}`};case"LONG":return{type:"success",example:Rd.long(Gy.INT64),jsonExample:Gy.INT64};case"UUID":return{type:"success",example:Rd.uuid(Gy.UUID),jsonExample:Gy.UUID};default:mo(t.v1)}}function ZQE(e){if(e?.type==="string")return e.default}function kQE(e){if(e?.type==="string")return e.validation}function eJE(e){if(e?.type==="double")return e.validation}function tJE(e){if(e?.type==="integer")return e.validation}function wB_(e){if(e<=Gy.SAMPLE_STRINGS.length){let t=Gy.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return Gy.SAMPLE_STRINGS[Gy.SAMPLE_STRINGS.length-1]+".".repeat(e-Gy.SAMPLE_STRINGS.length)}function rJE({fieldName:e,default_:t,validation:r}){if(t!=null)return{type:"success",example:Rd.string({original:t}),jsonExample:t};if(r){let n=r.minLength,a=r.maxLength;if(n){let u=wB_(n);return{type:"success",example:Rd.string({original:u}),jsonExample:u}}else if(a){let u=wB_(a);return{type:"success",example:Rd.string({original:u}),jsonExample:u}}}let i=e??Gy.STRING;return{type:"success",example:Rd.string({original:i}),jsonExample:i}}function iJE({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Rd.double(r),jsonExample:r};if(i)return{type:"success",example:Rd.double(i),jsonExample:i}}return{type:"success",example:Rd.double(Gy.DOUBLE),jsonExample:Gy.DOUBLE}}function nJE({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Rd.integer(r),jsonExample:r};if(i)return{type:"success",example:Rd.integer(i),jsonExample:i}}return{type:"success",example:Rd.integer(Gy.INT),jsonExample:Gy.INT}}function R9n({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=Gq({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:l,jsonExample:d}=u;return{type:"success",example:Iw.alias({value:l}),jsonExample:d}}case"enum":{let u=r.shape.values[0];return u==null?{type:"failure",message:"No enum values present"}:{type:"success",example:Iw.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u={},l=[];if((r.shape.extendedProperties==null||r.shape.extendedProperties.length===0)&&r.shape.extends!=null)for(let c of r.shape.extends){let b=t[c.typeId];if(b==null)continue;let g=R9n({fieldName:e,typeDeclaration:b,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});g!=null&&g.type==="success"&&g.example.type==="object"&&(Object.assign(u,g.jsonExample),l.push(...g.example.properties))}let d=aJE({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:n,maxDepth:i,skipOptionalProperties:a});if(d.type==="failure")return d;let{example:s,jsonExample:o}=d;return{type:"success",example:Iw.object({properties:[...l,...s.properties]}),jsonExample:Object.assign({},u,o)}}case"undiscriminatedUnion":{let u=0;for(let l of r.shape.members){let d=Gq({fieldName:e,typeReference:l.type,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});if(d.type==="failure"){++u;continue}let{example:s,jsonExample:o}=d;return{type:"success",example:Iw.undiscriminatedUnion({index:u,singleUnionType:s}),jsonExample:o}}break}case"union":{let u=r.shape.discriminant,l={};if(r.shape.baseProperties!=null)for(let d of r.shape.baseProperties){let s=Gq({fieldName:d.name.wireValue,typeReference:d.valueType,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});s.type==="success"&&(l[d.name.wireValue]=s.jsonExample)}for(let d of r.shape.types){let s=d.shape._visit({noProperties:()=>({type:"success",example:Iw.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:y3.noProperties()}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,...l}}),samePropertiesAsObject:o=>{let c=t[o.typeId];if(c==null)return{type:"failure",message:`Failed to find type declaration with id ${o.typeId}`};let b=R9n({currentDepth:n,maxDepth:i,fieldName:e,typeDeclaration:c,typeDeclarations:t,skipOptionalProperties:a});if(b==null)return{type:"failure",message:"Failed to generate example for type reference"};if(b.type==="failure")return b;let{example:g,jsonExample:O}=b;return{type:"success",example:Iw.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:y3.samePropertiesAsObject({typeId:c.name.typeId,object:g.type==="object"?g:{properties:[]}})}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,...typeof O=="object"?O:{},...l}}},singleProperty:o=>{let c=Gq({currentDepth:n+1,maxDepth:i,fieldName:e,typeReference:o.type,typeDeclarations:t,skipOptionalProperties:a});if(c.type==="failure")return c;let{example:b,jsonExample:g}=c;return{type:"success",example:Iw.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:y3.singleProperty(b)}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,[o.name.wireValue]:g,...l}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(s.type!=="failure")return s}}}return{type:"failure",message:"Failed to generate example for type reference"}}function aJE({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:i,maxDepth:n,currentDepth:a,skipOptionalProperties:u}){let l={},d=[];for(let s of[...r.properties??[],...r.extendedProperties??[]]){let o=Gq({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:i,currentDepth:a+1,maxDepth:n,skipOptionalProperties:u});if(o.type==="failure"&&!Wir({typeDeclarations:i,typeReference:s.valueType}))return{type:"failure",message:`Failed to generate required property ${s.name.wireValue} b/c ${o.message}`};if(o.type==="failure")continue;let{example:c,jsonExample:b}=o;d.push({name:s.name,originalTypeDeclaration:t.name,value:c}),l[s.name.wireValue]=b}return{type:"success",example:Iw.object({properties:d}),jsonExample:l}}function Gq({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){if(n>i)return{type:"failure",message:"Exceeded max depth"};switch(t.type){case"named":{let u=r[t.typeId];if(u==null)return{type:"failure",message:`Failed to find type declaration with id ${t.typeId}`};let l=R9n({fieldName:e,typeDeclaration:u,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(l==null)return{type:"failure",message:"Failed to generate example for type declaration"};if(l.type==="failure")return l;let{example:d,jsonExample:s}=l;return{type:"success",example:{jsonExample:s,shape:Nh.named({shape:d,typeName:u.name})},jsonExample:s}}case"container":{let u=jB_({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure"){let{example:s,jsonExample:o}=Hir({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:Nh.container(s)},jsonExample:o}}let{example:l,jsonExample:d}=u;return{type:"success",example:{jsonExample:d,shape:Nh.container(l)},jsonExample:d}}case"primitive":{let{jsonExample:u,example:l}=SB_({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:Nh.primitive(l)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:Nh.unknown(u)},jsonExample:u}}}}function PKi(e,t){let r=[];for(let i of e){let n=Gq({fieldName:i.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,value:n.example})}return{type:"success",example:r,jsonExample:void 0}}function N9n(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&Wir({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=Gq({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,value:n.example})}return{type:"success",example:r,jsonExample:void 0}}function cko(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&Wir({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=Gq({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??10,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,shape:i.allowMultiple?$2.exploded():$2.single(),value:n.example})}return{type:"success",example:r,jsonExample:void 0}}var GPc=hf.primitive({v1:hb.String,v2:Dp.string({default:void 0,validation:void 0})});function qRa({ir:e,endpoint:t,service:r,typeDeclarations:i,skipOptionalRequestProperties:n,generationResponse:a}){let u={name:void 0,endpointHeaders:[],endpointPathParameters:[],queryParameters:[],servicePathParameters:[],serviceHeaders:[],rootPathParameters:[],request:void 0,response:RT.ok(kC.body(void 0)),docs:void 0},l=PKi(t.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(l.type==="failure")return l;u.endpointPathParameters=l.example;let d=PKi(r.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(d.type==="failure")return d;u.servicePathParameters=d.example;let s=PKi(e.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(s.type==="failure")return s;u.rootPathParameters=s.example;let o=cko(t.queryParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:10});if(o.type==="failure")return o;u.queryParameters=o.example;let c=N9n(t.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(c.type==="failure")return c;u.endpointHeaders=c.example;let b=N9n(r.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(b.type==="failure")return b;if(u.serviceHeaders=b.example,t.requestBody!=null)switch(t.requestBody.type){case"bytes":return{type:"failure",message:"Bytes request unsupported"};case"fileUpload":return{type:"failure",message:"File upload unsupported"};case"inlinedRequestBody":{let g={},O=[];if(t.requestBody.extends!=null)for(let m of t.requestBody.extends){let P=i[m.typeId];if(P==null)throw new Error(`Failed to find extended type declaration with id ${m.typeId}`);let E=R9n({typeDeclaration:P,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});E!=null&&E.type==="success"&&Object.assign(g,E.jsonExample)}for(let m of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let P=Gq({fieldName:m.name.wireValue,typeReference:m.valueType,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});if(P.type==="failure"&&!Wir({typeDeclarations:i,typeReference:m.valueType}))return{type:"failure",message:`Failed to generate required property ${m.name.wireValue} b/c ${P.message}`};if(P.type==="failure")continue;let{example:E,jsonExample:q}=P;O.push({name:m.name,originalTypeDeclaration:void 0,value:E}),g[m.name.wireValue]=q}u.request=xQ.inlinedRequestBody({jsonExample:g,properties:O});break}case"reference":{let g=Gq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.request=xQ.reference(O);break}default:mo(t.requestBody)}if(a.type==="success"&&t.response?.body!=null)switch(t.response.body.type){case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":{let g=Gq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RT.ok(kC.body({...O,jsonExample:m}));break}case"streamParameter":{let g;switch(t.response.body.nonStreamResponse.type){case"bytes":return{type:"failure",message:"Bytes unsupported"};case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":g=Gq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":g=Gq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:GPc,skipOptionalProperties:!1});break;default:mo(t.response.body.nonStreamResponse)}if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RT.ok(kC.body({...O,jsonExample:m}));break}case"streaming":{let g;switch(t.response.body.value.type){case"sse":{if(g=Gq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RT.ok(kC.sse([{data:{...O,jsonExample:m},event:""}]));break}case"json":{if(g=Gq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RT.ok(kC.stream([{...O,jsonExample:m}]));break}case"text":{if(g=Gq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:GPc,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RT.ok(kC.stream([{...O,jsonExample:m}]));break}default:mo(t.response.body.value)}break}case"text":{let g=Gq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:GPc,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RT.ok(kC.body({...O,jsonExample:m}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:mo(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=RT.error({body:void 0,error:a.declaration.name});else{let g=Gq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:a.declaration.type,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.response=RT.error({body:O,error:a.declaration.name})}try{return{type:"success",example:{id:ARa(u),url:oJE(t,u),...u},jsonExample:void 0}}catch(g){return{type:"failure",message:`Parse failure with exceptions ${g}`}}}function oJE(e,t){let r={};[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.fullPath.head+e.fullPath.parts.map(n=>encodeURIComponent(`${r[n.pathParameter]}`)+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function QPc({ir:e,channel:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let n={name:void 0,pathParameters:[],headers:[],queryParameters:[],messages:[],docs:void 0},a=PKi(t.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(a.type==="failure")return a;n.pathParameters.push(...a.example);let u=PKi(e.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(u.type==="failure")return u;n.pathParameters.push(...u.example);let l=cko(t.queryParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:10});if(l.type==="failure")return l;n.queryParameters=l.example;let d=N9n(t.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(d.type==="failure")return d;n.headers.push(...d.example);let s=N9n(e.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(s.type==="failure")return s;n.headers.push(...s.example);let c=t.messages.filter(O=>O.origin==="client")[0];if(c!=null){let O=DB_({message:c,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:c.type,body:O})}let g=t.messages.filter(O=>O.origin==="server")[0];if(g!=null){let O=DB_({message:g,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:g.type,body:O})}return{type:"success",example:{...n,url:uJE(t,n)},jsonExample:void 0}}function DB_({message:e,typeDeclarations:t,skipOptionalRequestProperties:r}){if(e.body.type==="inlinedBody")return;let i=Gq({currentDepth:0,maxDepth:10,typeDeclarations:t,typeReference:e.body.bodyType,skipOptionalProperties:r});if(i.type==="success")return KEe.reference(i.example)}function uJE(e,t){let r={};[...t.pathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.path.head+e.path.parts.map(n=>encodeURIComponent(`${r[n.pathParameter]}`)+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function F9n(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{},i=Object.values(t)[0],n=Object.values(r)[0];return{userExample:i,autoExample:n}}function WAi(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{};return{userExamples:t,autoExamples:r}}function EB_({ir:e,endpoint:t,skipOptionalRequestProperties:r}){let i=e.types,n={pathParameters:{},queryParameters:{},headers:{}};for(let u of t.pathParameters){let{userExample:l,autoExample:d}=F9n(u.v2Examples);l!==void 0?n.pathParameters[u.name.originalName]=l:d!==void 0&&(n.pathParameters[u.name.originalName]=d)}for(let u of t.queryParameters){let{userExample:l,autoExample:d}=F9n(u.v2Examples);if(l!==void 0)n.queryParameters[u.name.name.originalName]=l;else if(d!==void 0){if(r&&Wir({typeReference:u.valueType,typeDeclarations:i}))continue;n.queryParameters[u.name.name.originalName]=d}}let a=[...t.headers,...e.headers,...e.idempotencyHeaders];for(let u of a){let{userExample:l,autoExample:d}=F9n(u.v2Examples);if(l!==void 0)n.headers[u.name.name.originalName]=l;else if(d!==void 0){if(r&&Wir({typeReference:u.valueType,typeDeclarations:i}))continue;n.headers[u.name.name.originalName]=d}}return n}function MB_({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let{pathParameters:i,queryParameters:n,headers:a}=EB_({endpoint:e,ir:t,skipOptionalRequestProperties:r}),u={},l={},d={endpoint:{method:e.method,path:sJE(e)},baseUrl:void 0,environment:e.baseUrl,auth:void 0,pathParameters:i,queryParameters:n,headers:a,requestBody:void 0,docs:void 0};if(e.requestBody!=null)switch(e.requestBody.type){case"bytes":break;case"fileUpload":{let{userExamples:s,autoExamples:o}=WAi(e.requestBody.v2Examples);for(let[c,b]of Object.entries(s))u[c]={...d,requestBody:b};for(let[c,b]of Object.entries(o))l[c]={...d,requestBody:b};break}case"inlinedRequestBody":{let{userExamples:s,autoExamples:o}=WAi(e.requestBody.v2Examples);for(let[c,b]of Object.entries(s))u[c]={...d,requestBody:b};for(let[c,b]of Object.entries(o))l[c]={...d,requestBody:b};break}case"reference":{let{userExamples:s,autoExamples:o}=WAi(e.requestBody.v2Examples);for(let[c,b]of Object.entries(s))u[c]={...d,requestBody:b};for(let[c,b]of Object.entries(o))l[c]={...d,requestBody:b};break}default:mo(e.requestBody)}return{userRequestExamples:u,autoRequestExamples:l,baseExample:d}}function sJE(e){let t={};[...e.pathParameters,...e.allPathParameters].forEach(i=>{let{userExample:n,autoExample:a}=F9n(i.v2Examples),u=n??a,l;u==null?l=i.name.originalName:l=typeof u=="string"?u:JSON.stringify(u),t[i.name.originalName]=l});let r=e.fullPath.head+e.fullPath.parts.map(i=>encodeURIComponent(`${t[i.pathParameter]}`)+i.tail).join("");return r.startsWith("/")||r===""?r:`/${r}`}function AB_({endpoint:e}){let t={},r={},i={statusCode:e.response?.statusCode,body:void 0,docs:void 0};if(e.response==null)return{userResponseExamples:{},autoResponseExamples:{},baseExample:i};if(e.response.body==null)return e.source?.type==="openrpc"?{userResponseExamples:{},autoResponseExamples:{},baseExample:{...i,body:I9.json(TRa(null))}}:{userResponseExamples:{},autoResponseExamples:{},baseExample:i};switch(e.response.body.type){case"bytes":break;case"fileDownload":break;case"text":{let n=e.response.body,{userExamples:a,autoExamples:u}=WAi(n.v2Examples);for(let[l,d]of Object.entries(a)){let s=e.source?.type==="openrpc"?TRa(d):d;t[l]={...i,body:I9.json(s)}}for(let[l,d]of Object.entries(u)){let s=e.source?.type==="openrpc"?TRa(d):d;r[l]={...i,body:I9.json(s)}}break}case"json":{let n=e.response.body.value;if(n.type==="response"){let{userExamples:a,autoExamples:u}=WAi(n.v2Examples);for(let[l,d]of Object.entries(a)){let s=e.source?.type==="openrpc"?TRa(d):d;t[l]={...i,body:I9.json(s)}}for(let[l,d]of Object.entries(u)){let s=e.source?.type==="openrpc"?TRa(d):d;r[l]={...i,body:I9.json(s)}}}break}case"streaming":{let n=e.response.body.value;if(n.type==="json"){let{userExamples:a,autoExamples:u}=WAi(n.v2Examples);for(let[l,d]of Object.entries(a))t[l]={...i,body:I9.stream([d])};for(let[l,d]of Object.entries(u))r[l]={...i,body:I9.stream([d])}}break}case"streamParameter":break;default:mo(e.response.body)}return{userResponseExamples:t,autoResponseExamples:r,baseExample:i}}function TRa(e,t=1){return{id:t,jsonrpc:"2.0",result:e}}function qB_({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let i={},n={},{userRequestExamples:a,autoRequestExamples:u,baseExample:l}=MB_({endpoint:e,ir:t,skipOptionalRequestProperties:r}),{userResponseExamples:d,autoResponseExamples:s,baseExample:o}=AB_({endpoint:e}),c=Object.keys(u)[0],b=Object.values(u)[0],g=Object.values(s)[0];for(let[O,m]of Object.entries(a))i[O]={request:m,response:d[O]??g??o,codeSamples:void 0};for(let[O,m]of Object.entries(d))i[O]={request:a[O]??b??l,response:m,codeSamples:void 0};return Object.keys(i).length===0&&(n[c??T_(`${e.name.originalName}_example`)]={request:b??l,response:g??o,codeSamples:void 0}),{userFullExamples:i,autoFullExamples:n}}function CRa({ir:e,exampleGeneration:t}){for(let[r,i]of Object.entries(e.services))for(let n of i.endpoints){if(n.userSpecifiedExamples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let a=qRa({ir:e,service:i,endpoint:n,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples,generationResponse:{type:"success"}});if(a.type==="failure")continue;let{example:u}=a;n.autogeneratedExamples=[{example:u}]}for(let[r,i]of Object.entries(e.websocketChannels??{})){if(i.examples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let n=QPc({ir:e,channel:i,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});if(n.type==="failure")continue;let{example:a}=n;i.examples=[...i.examples,a]}return e}function JPc({ir:e,exampleGeneration:t}){for(let[r,i]of Object.entries(e.services))for(let n of i.endpoints){n.v2Examples==null&&(n.v2Examples={userSpecifiedExamples:{},autogeneratedExamples:{}});let{userFullExamples:a,autoFullExamples:u}=qB_({endpoint:n,ir:e,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});if(Object.keys(n.v2Examples.userSpecifiedExamples).length>0){if(Object.values(n.v2Examples.userSpecifiedExamples).some(d=>d.request!=null||d.response!=null))continue;let l=Object.values(n.v2Examples.userSpecifiedExamples).filter(d=>d!=null).flatMap(d=>d.codeSamples??[]);for(let[d,s]of Object.entries(u))u[d]={...s,codeSamples:l};for(let[d,s]of Object.entries(a))a[d]={...s,codeSamples:l}}n.v2Examples.autogeneratedExamples=u,n.v2Examples.userSpecifiedExamples=a}for(let[r,i]of Object.entries(e.websocketChannels??{})){if(i.examples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let n=QPc({ir:e,channel:i,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});if(n.type==="failure")continue;let{example:a}=n;i.examples=[...i.examples,a]}return e}function lko(e,t,r){let{environments:i,changedBaseUrlIds1:n,changedBaseUrlIds2:a}=lJE(e.environments,t.environments,r),{services:u,websocketChannels:l}=fJE(e,t,n,a);return{apiName:e.apiName,basePath:e.basePath,selfHosted:e.selfHosted&&t.selfHosted,apiDisplayName:e.apiDisplayName??t.apiDisplayName,apiDocs:e.apiDocs??t.apiDocs,auth:{requirement:e.auth?.requirement??t.auth?.requirement,schemes:t.auth?.schemes?.length!=null&&t.auth.schemes.length>(e.auth?.schemes?.length??0)?t.auth.schemes:e.auth?.schemes??[],docs:e.auth?.docs??t.auth?.docs},headers:[...e.headers??[],...t.headers??[]],environments:i,types:{...e.types??{},...t.types??{}},constants:{...e.constants??{},...t.constants??{}},errors:{...e.errors??{},...t.errors??{}},services:u,webhookGroups:{...e.webhookGroups??{},...t.webhookGroups??{}},subpackages:cJE(e.subpackages,t.subpackages),websocketChannels:l,rootPackage:{service:e.rootPackage.service??t.rootPackage.service,types:[...e.rootPackage.types??[],...t.rootPackage.types??[]],errors:[...e.rootPackage.errors??[],...t.rootPackage.errors??[]],subpackages:[...e.rootPackage.subpackages??[],...(t.rootPackage.subpackages??[]).filter(d=>!e.rootPackage.subpackages?.includes(d))],fernFilepath:e.rootPackage.fernFilepath??t.rootPackage.fernFilepath,webhooks:e.rootPackage.webhooks??t.rootPackage.webhooks,websocket:e.rootPackage.websocket??t.rootPackage.websocket,hasEndpointsInTree:e.rootPackage.hasEndpointsInTree||t.rootPackage.hasEndpointsInTree,navigationConfig:e.rootPackage.navigationConfig??t.rootPackage.navigationConfig,docs:e.rootPackage.docs??t.rootPackage.docs},fdrApiDefinitionId:e.fdrApiDefinitionId??t.fdrApiDefinitionId,apiVersion:e.apiVersion??t.apiVersion,idempotencyHeaders:[...e.idempotencyHeaders??[],...t.idempotencyHeaders??[]],pathParameters:[...e.pathParameters??[],...t.pathParameters??[]],errorDiscriminationStrategy:e.errorDiscriminationStrategy??t.errorDiscriminationStrategy,variables:[...e.variables??[],...t.variables??[]],serviceTypeReferenceInfo:e.serviceTypeReferenceInfo??t.serviceTypeReferenceInfo,readmeConfig:e.readmeConfig??t.readmeConfig,sourceConfig:e.sourceConfig??t.sourceConfig,publishConfig:e.publishConfig??t.publishConfig,dynamic:e.dynamic??t.dynamic,sdkConfig:e.sdkConfig??t.sdkConfig}}function cJE(e,t){let r=e;for(let[i,n]of Object.entries(t))r[i]==null?r[i]=n:r[i]={name:n.name,fernFilepath:n.fernFilepath,hasEndpointsInTree:r[i].hasEndpointsInTree||n.hasEndpointsInTree,navigationConfig:r[i].navigationConfig??n.navigationConfig,docs:r[i].docs??n.docs,service:r[i].service??n.service,subpackages:[...r[i].subpackages??[],...(n.subpackages??[]).filter(a=>!r[i]?.subpackages?.includes(a))],webhooks:r[i].webhooks??n.webhooks,websocket:r[i].websocket??n.websocket,errors:[...r[i].errors??[],...n.errors??[]],types:[...r[i].types??[],...n.types??[]]};return r}function lJE(e,t,r){if(e==null&&t==null)return{environments:void 0,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(t==null)return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(e==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(JSON.stringify(e)===JSON.stringify(t))return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let i=TB_(e),n=TB_(t);if(i&&n&&e.environments.type==="singleBaseUrl"&&t.environments.type==="singleBaseUrl")return{environments:{defaultEnvironment:e.defaultEnvironment??t.defaultEnvironment,environments:cx.singleBaseUrl({environments:[...e.environments.environments,...t.environments.environments]})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let a=i?t.defaultEnvironment:e.defaultEnvironment,u=e.environments,l=t.environments;if(u.type==="singleBaseUrl"&&l.type==="singleBaseUrl"){let d=i?l:u,s=i?u:l,o={},{deconflictedEnvironments2:c,changedBaseUrlIds2:b}=dJE(d,s,r);if(d.environments[0]==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let g="Base",O=r.generateName("Base");return d.environments.forEach(m=>{o[m.id]=g}),{environments:{defaultEnvironment:a,environments:cx.multipleBaseUrls({baseUrls:[{id:g,name:O},...c.environments.map(m=>({id:m.id,name:m.name}))],environments:d.environments.map(m=>({id:m.id,name:m.name,urls:{[g]:m.url,...Object.fromEntries(c.environments.map(P=>[P.id,P.url]))},docs:void 0}))})},changedBaseUrlIds1:i?b:o,changedBaseUrlIds2:i?o:b}}if(u.type==="multipleBaseUrls"&&l.type==="singleBaseUrl"||u.type==="singleBaseUrl"&&l.type==="multipleBaseUrls"){let d=u.type==="singleBaseUrl"?u:l,s=u.type==="multipleBaseUrls"?u:l,{deconflictedEnvironments1:o,changedBaseUrlIds1:c}=pJE(d,s,r);return{environments:{defaultEnvironment:a,environments:cx.multipleBaseUrls({baseUrls:[...s.baseUrls,...o.environments.map(b=>({id:b.id,name:b.name}))],environments:s.environments.map(b=>({...b,urls:{...b.urls,...Object.fromEntries(o.environments.map(g=>[g.id,g.url]))}}))})},changedBaseUrlIds1:u.type==="singleBaseUrl"?c:void 0,changedBaseUrlIds2:u.type==="singleBaseUrl"?void 0:c}}if(u.type==="multipleBaseUrls"&&l.type==="multipleBaseUrls"){let{deconflictedEnvironments:d,changedBaseUrlIds:s}=_JE(u,l,r);return{environments:{defaultEnvironment:a,environments:cx.multipleBaseUrls({baseUrls:[...u.baseUrls,...d.baseUrls],environments:u.environments.flatMap(o=>d.environments.map(c=>({...o,urls:{...o.urls,...c.urls}})))})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:s}}return{environments:e??t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0}}function fJE(e,t,r,i){if(r!=null)for(let[u,l]of Object.entries(r)){for(let d of Object.values(e.services))for(let s of Object.values(d.endpoints))s.baseUrl==u&&(s.baseUrl=l),s.v2BaseUrls?.includes(u)&&(s.v2BaseUrls=s.v2BaseUrls.map(o=>o===u?l:o));for(let d of Object.values(e.websocketChannels??{}))d.baseUrl==u&&(d.baseUrl=l)}if(i!=null)for(let[u,l]of Object.entries(i)){for(let d of Object.values(t.services))for(let s of Object.values(d.endpoints))s.baseUrl==u&&(s.baseUrl=l),s.v2BaseUrls?.includes(u)&&(s.v2BaseUrls=s.v2BaseUrls.map(o=>o===u?l:o));for(let d of Object.values(t.websocketChannels??{}))d.baseUrl==u&&(d.baseUrl=l)}let n=e.services;for(let[u,l]of Object.entries(t.services))n[u]==null?n[u]=l:n[u]={availability:l.availability,name:l.name,displayName:l.displayName,basePath:l.basePath,endpoints:[...n[u].endpoints??[],...l.endpoints],pathParameters:[...n[u].pathParameters??[],...l.pathParameters??[]],headers:[...n[u].headers??[],...l.headers??[]],encoding:l.encoding,transport:l.transport};let a={...e.websocketChannels??{},...t.websocketChannels??{}};return{services:n,websocketChannels:a}}function dJE(e,t,r){let i={},n=new Set(e.environments.map(s=>s.id)),a=new Set(e.environments.map(s=>s.name)),u=new Map(e.environments.map(s=>[s.url,s.id])),l=t.environments.filter(s=>{let o=u.get(s.url);return o!=null?(i[s.id]=o,!1):!0}).map(s=>{if(n.has(s.id)||a.has(s.name)){let o=KPc(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s});return{deconflictedEnvironments2:cx.singleBaseUrl({environments:l}),changedBaseUrlIds2:i}}function pJE(e,t,r){let i={},n=new Set(t.baseUrls.map(d=>d.id)),a=new Set(t.baseUrls.map(d=>d.name)),u=e.environments.map(d=>{if(n.has(d.id)||a.has(d.name)){let s=KPc(d.id,n);return i[d.id]=s,{...d,id:s,name:r.generateName(s)}}return d});return{deconflictedEnvironments1:cx.singleBaseUrl({environments:u}),changedBaseUrlIds1:i}}function _JE(e,t,r){let i={},n=new Set(e.baseUrls.map(s=>s.id)),a=new Set(e.baseUrls.map(s=>s.name)),u=t.baseUrls.map(s=>{if(n.has(s.id)||a.has(s.name)){let o=KPc(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s}),l=t.environments.map(s=>({...s,urls:Object.fromEntries(Object.entries(s.urls).map(([o,c])=>[i[o]??o,c]))}));return{deconflictedEnvironments:cx.multipleBaseUrls({baseUrls:u,environments:l}),changedBaseUrlIds:i}}function TB_(e){return e.environments.type==="singleBaseUrl"?e.environments.environments.some(t=>t.url&&(t.url.startsWith("ws://")||t.url.startsWith("wss://"))):e.environments.type==="multipleBaseUrls"?e.environments.environments.some(t=>Object.values(t.urls).some(r=>r&&(r.startsWith("ws://")||r.startsWith("wss://")))):!1}function KPc(e,t){let r=e,i=1;for(;t.has(r);)r=`${e}-${i}`,i++;return r}function XPc({rawApiFileSchema:e,casingsGenerator:t}){if(e.auth==null)return{docs:void 0,requirement:yRe.All,schemes:[]};let r=typeof e.auth!="string"?e.auth.docs:void 0;return BHi(e.auth,{single:i=>{let n=CB_({reference:i,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t});return{docs:r,requirement:yRe.All,schemes:[n]}},any:({any:i})=>({docs:r,requirement:yRe.Any,schemes:i.map(n=>CB_({reference:n,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t}))})})}function CB_({reference:e,authSchemeDeclarations:t,casingsGenerator:r}){let i=(a,u)=>{let l=t?.[a];if(l==null)throw new Error("Unknown auth scheme: "+a);return IDa(l,{header:d=>CB.header({docs:u,name:r.generateNameAndWireValue({name:d.name??a,wireValue:d.header}),valueType:hf.primitive({v1:hb.String,v2:Dp.string({default:void 0,validation:void 0})}),prefix:d.prefix,headerEnvVar:d.env}),basic:d=>BB_({casingsGenerator:r,docs:u,rawScheme:d}),bearer:d=>YPc({casingsGenerator:r,docs:u,rawScheme:d}),oauth:d=>YPc({casingsGenerator:r,docs:u,rawScheme:void 0})})},n=typeof e=="string"?e:e.scheme;switch(n){case"bearer":case"oauth":return YPc({casingsGenerator:r,docs:void 0,rawScheme:void 0});case"basic":return BB_({casingsGenerator:r,docs:void 0,rawScheme:void 0});default:return i(n,typeof e!="string"?e.docs:void 0)}}function YPc({casingsGenerator:e,docs:t,rawScheme:r}){return CB.bearer({docs:t,token:e.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function BB_({casingsGenerator:e,docs:t,rawScheme:r}){return CB.basic({docs:t,username:e.generateName(r?.username?.name??"username"),usernameEnvVar:r?.username?.env,password:e.generateName(r?.password?.name??"password"),passwordEnvVar:r?.password?.env})}function BRa({rawApiFileSchema:{"default-environment":e,environments:t},casingsGenerator:r}){if(t==null)return;let i=Object.values(t)[0];if(i!=null)return{environmentsConfig:{defaultEnvironment:e??void 0,environments:Jkt(i,{singleBaseUrl:()=>cx.singleBaseUrl(hJE({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>cx.multipleBaseUrls(yJE({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})},audiences:{...Object.fromEntries(Object.entries(t).map(([n,a])=>[n,Jkt(a,{singleBaseUrl:u=>[...typeof u=="string"?[]:u.audiences??[]],multipleBaseUrls:u=>[...u.audiences??[]]})]))}}}function hJE({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>Jkt(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:IB_(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function yJE({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>Jkt(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:dd(a.urls,u=>IB_(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function IB_(e){return e.endsWith("/")?e.slice(0,-1):e}function FMe(e){return e.allParts.map(t=>t.originalName).join("/")}var jm={generateTypeId:e=>`type_${FMe(e.fernFilepath)}:${e.name.originalName}`,generateErrorId:e=>`error_${FMe(e.fernFilepath)}:${e.name.originalName}`,generateServiceId:e=>`service_${FMe(e.fernFilepath)}`,generateServiceIdFromFernFilepath:e=>`service_${FMe(e)}`,generateSubpackageId:e=>`subpackage_${FMe(e)}`,generateEndpointId:(e,t)=>{let r=FMe(e.fernFilepath),i=t.name.originalName;return`endpoint_${r}.${i}`},generateWebhookGroupId:e=>`webhooks_${FMe(e)}`,generateWebhookId:(e,t)=>`webhooks_${FMe(e)}.${t}`,generateWebSocketChannelId:e=>`channel_${FMe(e)}`};function L9n(e){return e.type!=null}var fko=class{environments=new Set;types=new Set;properties;errors=new Set;services=new Set;endpoints=new Set;requestProperties;queryParameters;webhooks=new Set;webhookPayloadProperties;channels=new Set;subpackages=new Set;constructor({types:t,properties:r,errors:i,environments:n,services:a,endpoints:u,webhooks:l,subpackages:d,queryParameters:s,requestProperties:o,webhookPayloadProperties:c,channels:b}){this.environments=n,this.types=t,this.properties=r,this.errors=i,this.services=a,this.endpoints=u,this.webhooks=l,this.webhookPayloadProperties=c,this.subpackages=d,this.requestProperties=o,this.queryParameters=s,this.channels=b}hasTypeId(t){return this.types.has(t)}hasErrorId(t){return this.errors.has(t)}hasServiceId(t){return this.services.has(t)}hasSubpackageId(t){return this.subpackages.has(t)}hasType(t){let r=jm.generateTypeId(t.name);return this.types.has(r)}hasProperty(t,r){let i=this.properties[t];return i==null?!0:i.has(r)}hasError(t){let r=jm.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=jm.generateServiceId(t.name);return this.services.has(r)}hasEnvironmentId(t){return this.environments.has(t)}hasEndpoint(t){return this.endpoints.has(t.id)}hasRequestProperty(t,r){let i=this.requestProperties[t];return i==null?!0:i.has(r)}hasQueryParameter(t,r){let i=this.queryParameters[t];return i==null?!0:i.has(r)}hasSubpackage(t){return this.subpackages.has(t)}hasWebhook(t){return t.id?this.webhooks.has(t.id):!0}hasChannel(t){return t?this.channels.has(t):!0}hasWebhookPayloadProperty(t,r){let i=this.webhookPayloadProperties[t];return i==null?!0:i.has(r)}};function jKi(e){let t={};for(let[r,i]of Object.entries(e))if(typeof i!="string")for(let n of i.audiences??[])t[n]==null&&(t[n]=new Set),t[n]?.add(r);return t}var wKi=class{types={};properties={};queryParameters={};requestProperties={};webhookProperties={};errors={};endpoints={};webhooks={};channels={};audiences;typesReferencedByService={};environmentsNeededForAudience=new Set;typesNeededForAudience=new Set;servicesNeededForAudience=new Set;endpointsNeededForAudience=new Set;webhooksNeededForAudience=new Set;channelsNeededForAudience=new Set;subpackagesNeededForAudience=new Set;constructor(t){this.audiences=vJE(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let u=jm.generateTypeId(t),l={typeId:u,allDescendants:r,descendantsByAudience:n,referencedSubpackages:i};this.types[u]=l,this.typesReferencedByService[u]==null&&(this.typesReferencedByService[u]=new Set),this.properties[u]={typeId:u,propertiesByAudience:a}}markTypeForAudiences(t,r){let i=jm.generateTypeId(t);this.hasAudience(r)&&(this.typesNeededForAudience.add(i),this.addSubpackages(t.fernFilepath),this.types[i]?.referencedSubpackages.forEach(n=>{this.addSubpackages(n)}))}markEnvironmentForAudiences(t,r,i){t&&(this.hasAudience(r)||i)&&this.environmentsNeededForAudience.add(t.id)}getTypesReferencedByService(){for(let t of Object.values(this.endpoints))for(let r of t.referencedTypes)this.markTypeForService(r,t.serviceId);return this.typesReferencedByService}addError(t){let r=jm.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&Px(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=jm.generateServiceId(t.name),a=r.id,u=new Set,l=new Set,d=new Set;for(let s of[...t.headers,...r.headers])Px(s.valueType,u,d);for(let s of[...t.pathParameters,...r.pathParameters])Px(s.valueType,u,d);for(let s of r.queryParameters)Px(s.valueType,u,d);if(i!=null&&i.request!=null&&typeof i.request!="string"){let s=jKi(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:s}}r.requestBody!=null&&pC._visit(r.requestBody,{inlinedRequestBody:s=>{for(let o of s.extends)dko(o,u,d);for(let o of s.properties)Px(o.valueType,u,d);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&ZC(i.request.body)){let o=jKi(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:s})=>{Px(s,u,d)},fileUpload:({properties:s})=>{for(let o of s)z9._visit(o,{file:Go,bodyProperty:({valueType:c})=>{Px(c,u,d)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+o.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&NS._visit(r.response.body,{fileDownload:Go,json:s=>{Px(s.responseBodyType,u,d)},streaming:s=>{s._visit({sse:o=>Px(o.payload,u,d),json:o=>Px(o.payload,u,d),text:Go,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.type)}})},streamParameter:s=>{s.streamResponse._visit({sse:o=>Px(o.payload,u,d),json:o=>Px(o.payload,u,d),text:Go,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.streamResponse.type)}}),s.nonStreamResponse.type==="json"&&Px(s.nonStreamResponse.value.responseBodyType,u,d)},text:Go,bytes:Go,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(s=>{l.add(jm.generateErrorId(s.error)),d.add(s.error.fernFilepath)}),this.endpoints[a]={endpointId:a,serviceId:n,referencedTypes:u,referencedErrors:l,referencedSubpackages:d}}markEndpointForAudience(t,r,i){if(this.hasAudience(i)){let n=jm.generateServiceId(t);this.servicesNeededForAudience.add(n),r.forEach(a=>{let u=a.id;this.endpointsNeededForAudience.add(u),this.endpoints[u]?.referencedSubpackages.forEach(l=>{this.addSubpackages(l)})}),this.servicesNeededForAudience.add(n),this.addSubpackages(t.fernFilepath)}}getFilteredSubpackages(){return this.subpackagesNeededForAudience}getFilteredServices(){return this.servicesNeededForAudience}getFilteredEndpoints(){return this.endpointsNeededForAudience}getFilteredChannels(){return this.channelsNeededForAudience}getFilteredWebhooks(){return this.webhooksNeededForAudience}addWebhook(t,r,i){let n=r.id;if(n==null)return;let a=new Set,u=new Set;r.payload!=null&&EW._visit(r.payload,{inlinedPayload:l=>{for(let d of l.extends)dko(d,a,u);for(let d of l.properties)Px(d.valueType,a,u);if(i?.payload!=null&&typeof i.payload=="object"&&!L9n(i.payload)){let d=jKi(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:d}}},reference:({payloadType:l})=>{Px(l,a,u)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),u.add(t),this.webhooks[n]={webhookId:n,referencedTypes:a,referencedSubpackages:u}}markWebhookForAudiences(t,r,i){let n=r.id;n!=null&&this.hasAudience(i)&&(this.webhooksNeededForAudience.add(n),this.addSubpackages(t))}addChannel(t,r,i,n){if(r==null)return;let a=new Set,u=new Set;for(let l of i.messages)N9._visit(l.body,{reference:({bodyType:d})=>{Px(d,a,u)},inlinedBody:d=>{for(let s of d.extends)dko(s,a,u);for(let s of d.properties)Px(s.valueType,a,u)},_other:()=>{}});for(let l of i.queryParameters)Px(l.valueType,a,u);u.add(t),this.channels[r]={channelId:r,referencedTypes:a,referencedSubpackages:u}}markChannelForAudiences(t,r,i){r!=null&&this.hasAudience(i)&&(this.channelsNeededForAudience.add(r),this.addSubpackages(t))}build(){let t=new Set,r=new Set;for(let l of this.endpointsNeededForAudience.keys()){let d=this.getEndpointNode(l);for(let s of d.referencedErrors){if(r.has(s))continue;r.add(s);let o=this.getErrorNode(s);this.addReferencedTypes(t,o.referencedTypes)}this.addReferencedTypes(t,d.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let l of this.webhooksNeededForAudience.keys()){let d=this.getWebhookNode(l);this.addReferencedTypes(t,d.referencedTypes)}for(let l of this.channelsNeededForAudience.keys()){let d=this.getChannelNode(l);this.addReferencedTypes(t,d.referencedTypes)}let i={},n={},a={},u={};if(this.audiences.type==="filtered"){for(let[l,d]of Object.entries(this.properties)){if(!t.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}s.size>0&&(i[l]=s),i[l]=s.size>0?s:void 0}for(let[l,d]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}n[l]=s.size>0?s:void 0}for(let[l,d]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.parametersByAudience[o];c?.forEach(b=>{s.add(b)})}a[l]=s.size>0?s:void 0}for(let[l,d]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}u[l]=s.size>0?s:void 0}}return new fko({types:t,properties:i,errors:r,requestProperties:n,queryParameters:a,environments:this.environmentsNeededForAudience,services:this.servicesNeededForAudience,endpoints:this.endpointsNeededForAudience,webhooks:this.webhooksNeededForAudience,webhookPayloadProperties:u,subpackages:this.subpackagesNeededForAudience,channels:this.channelsNeededForAudience})}markTypeForService(t,r){let i=this.typesReferencedByService[t]??=new Set;if(i.has(r))return;i.add(r);let n=this.getTypeNode(t);for(let a of n.allDescendants)this.markTypeForService(a,r)}addReferencedTypes(t,r){for(let i of r){if(t.has(i))continue;t.add(i);let n=this.getTypeNode(i);if(this.audiences.type==="filtered")for(let a of this.audiences.audiences){let u=n.descendantsByAudience[a];if(u!=null)u.forEach(l=>{t.add(l)});else{n.allDescendants.forEach(l=>{t.add(l)});break}}else n.allDescendants.forEach(a=>{t.add(a)})}}getTypeNode(t){let r=this.types[t];if(r==null)throw new Error(`Failed to find type node with id ${t}`);return r}getErrorNode(t){let r=this.errors[t];if(r==null)throw new Error(`Failed to find error node with id ${t}`);return r}getEndpointNode(t){let r=this.endpoints[t];if(r==null)throw new Error(`Failed to find endpoint node with id ${t}`);return r}getWebhookNode(t){let r=this.webhooks[t];if(r==null)throw new Error(`Failed to find webhook node with id ${t}`);return r}getChannelNode(t){let r=this.channels[t];if(r==null)throw new Error(`Failed to find channel node with id ${t}`);return r}hasNoAudiences(){return this.audiences.type==="none"}hasAudience(t){let r=this.audiences;switch(r.type){case"none":return!0;case"filtered":return t.some(i=>r.audiences.has(i));default:mo(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(jm.generateSubpackageId(i))}}};function vJE(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:mo(e)}}function Px(e,t,r){hf._visit(e,{container:i=>{bJE(i,t,r)},named:i=>{dko(i,t,r)},primitive:Go,unknown:Go,_other:Go})}function dko(e,t,r){t.add(jm.generateTypeId(e)),r.add(e.fernFilepath)}function bJE(e,t,r){_b._visit(e,{list:i=>{Px(i,t,r)},map:i=>{Px(i.keyType,t,r),Px(i.valueType,t,r)},optional:i=>{Px(i,t,r)},nullable:i=>{Px(i,t,r)},set:i=>{Px(i,t,r)},literal:Go,_other:Go})}var ZPc=class{errors;constructor(){this.errors=[]}add(t){this.errors.push({message:t})}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}},IRa=class{errors;constructor(){this.errors=new ZPc}async check({from:t,to:r}){let i=this.checkBreaking({from:t,to:r});return{bump:i.isBreaking?"major":"minor",isBreaking:i.isBreaking,errors:i.errors}}checkBreaking({from:t,to:r}){this.checkTypeBreakingChanges({from:t.types,to:r.types}),this.checkErrorsBreakingChanges({from:t.errors,to:r.errors}),this.checkServicesBreakingChanges({from:t.services,to:r.services});let i=this.errors.hasErrors();return{bump:i?"major":"minor",isBreaking:i,errors:this.errors.getErrors()}}checkTypeBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){let a=r[i];if(!a){this.errors.add(`Type "${i}" was removed.`);continue}this.areTypeDeclarationsCompatible({from:n,to:a})||this.errors.add(`Type "${i}" has an incompatible change.`)}}checkErrorsBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){let a=Object.values(r).find(u=>u.name.errorId===n.name.errorId);if(!a){this.errors.add(`Error "${n.name.errorId}" with status code "${n.statusCode}" was removed.`);continue}this.checkErrorBreakingChanges({from:n,to:a})}}checkErrorBreakingChanges({from:t,to:r}){if(t.type!=null){if(r.type==null){this.errors.add(`Error "${t.name.errorId}" with status code "${t.statusCode}" had its type removed.`);return}this.areTypeReferencesCompatible({from:t.type,to:r.type})||this.errors.add(`Error "${t.name.errorId}" type reference changed.`)}this.areDeclaredErrorNamesCompatible({from:t.name,to:r.name})||this.errors.add(`Error "${t.name.errorId}" name changed.`),this.areNameAndWireValuesCompatible({from:t.discriminantValue,to:r.discriminantValue})||this.errors.add(`Error "${t.name.errorId}" discriminant value changed.`)}checkServicesBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){let a=r[i];if(!a){this.errors.add(`Service "${i}" was removed.`);continue}this.checkServiceBreakingChanges({id:i,from:n,to:a})}}checkServiceBreakingChanges({id:t,from:r,to:i}){this.checkHeadersBreakingChanges({id:t,from:r.headers,to:i.headers}),this.checkEndpointsBreakingChanges({id:t,from:r,to:i})}checkEndpointsBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.endpoints.map(u=>[u.id,u])),a=Object.fromEntries(i.endpoints.map(u=>[u.id,u]));for(let[u,l]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Endpoint "${u}" was removed.`);continue}this.checkEndpointBreakingChanges({id:u,from:l,to:d})}}checkEndpointBreakingChanges({id:t,from:r,to:i}){this.checkHttpMethodsBreakingChanges({id:t,from:r.method,to:i.method}),this.checkHttpPathsBreakingChanges({id:t,from:r.fullPath,to:i.fullPath}),this.checkPathParametersBreakingChanges({id:t,from:r.pathParameters,to:i.pathParameters}),this.checkQueryParametersBreakingChanges({id:t,from:r.queryParameters,to:i.queryParameters}),this.checkHeadersBreakingChanges({id:t,from:r.headers,to:i.headers}),r.requestBody!=null&&(i.requestBody!=null?this.checkHttpRequestBodiesCompatible({id:t,from:r.requestBody,to:i.requestBody}):this.errors.add(`Request body was removed from endpoint "${r.id}".`)),r.response!=null&&(i.response!=null?this.checkHttpResponseBreakingChanges({id:t,from:r.response,to:i.response}):this.errors.add(`Response was removed from endpoint "${r.id}".`)),(r.pagination!=null&&i.pagination==null||r.pagination==null&&i.pagination!=null)&&this.errors.add(`Pagination was ${r.pagination!=null?"added":"removed"} from endpoint "${r.id}".`)}checkPathParametersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(u=>[u.name.originalName,u])),a=Object.fromEntries(i.map(u=>[u.name.originalName,u]));for(let[u,l]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Path parameter "${u}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:l.valueType,to:d.valueType})||this.errors.add(`Path parameter "${u}" type changed in endpoint "${t}".`)}}checkQueryParametersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(u=>[u.name.wireValue,u])),a=Object.fromEntries(i.map(u=>[u.name.wireValue,u]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(n).map(([u,l])=>[u,l.valueType])),to:Object.fromEntries(Object.entries(a).map(([u,l])=>[u,l.valueType]))});for(let[u,l]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Query parameter "${u}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:l.valueType,to:d.valueType})||this.errors.add(`Query parameter "${u}" type changed in endpoint "${t}".`),l.allowMultiple!==d.allowMultiple&&this.errors.add(`Query parameter "${u}" allow-multiple values changed in endpoint "${t}".`)}}checkHeadersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(u=>[u.name.wireValue,u])),a=Object.fromEntries(i.map(u=>[u.name.wireValue,u]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(n).map(([u,l])=>[u,l.valueType])),to:Object.fromEntries(Object.entries(a).map(([u,l])=>[u,l.valueType]))});for(let[u,l]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Header "${u}" was removed from ${t}.`);continue}this.areTypeReferencesCompatible({from:l.valueType,to:d.valueType})||this.errors.add(`Header "${u}" type changed in ${t}.`)}}checkHttpMethodsBreakingChanges({id:t,from:r,to:i}){r!==i&&this.errors.add(`HTTP method changed in ${t}.`)}checkHttpPathsBreakingChanges({id:t,from:r,to:i}){this.areHttpPathsCompatible({from:r,to:i})||this.errors.add(`HTTP path changed in ${t}.`)}areHttpPathsCompatible({from:t,to:r}){if(t.head!==r.head||t.parts.length!==r.parts.length)return!1;for(let i=0;i<t.parts.length;i++){let n=t.parts[i];if(n==null)return!1;let a=r.parts[i];if(a==null||n.pathParameter!==a.pathParameter||n.tail!==a.tail)return!1}return!0}checkHttpRequestBodiesCompatible({id:t,from:r,to:i}){switch(r.type){case"inlinedRequestBody":if(i.type==="inlinedRequestBody"&&this.areInlinedRequestBodiesCompatible({from:r,to:i}))return;break;case"reference":if(i.type==="reference"&&this.areReferenceRequestBodiesCompatible({from:r,to:i}))return;break;case"fileUpload":if(i.type==="fileUpload"&&this.areFileUploadRequestBodiesCompatible({from:r,to:i}))return;break;case"bytes":if(i.type==="bytes")return;break;default:mo(r)}this.errors.add(`Request body type changed from "${r.type}" to "${i.type}" in endpoint "${t}".`)}areInlinedRequestBodiesCompatible({from:t,to:r}){let i=this.getInlinedRequestBody(t),n=this.getInlinedRequestBody(r);return this.checkForNewInlinedRequestBodyProperties({from:i,to:n}),Object.entries(i).every(([a,u])=>{let l=n[a];return l?this.areTypeReferencesCompatible({from:u,to:l}):(this.errors.add(`Request body property "${a}" was removed.`),!1)})}areReferenceRequestBodiesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.requestBodyType,to:r.requestBodyType})}areFileUploadRequestBodiesCompatible({from:t,to:r}){let i=this.getFileUploadRequest(t.properties),n=this.getFileUploadRequest(r.properties);this.checkForNewFileUploadRequestProperties({from:i,to:n});for(let[a,u]of Object.entries(i)){let l=n[a];if(!l)return this.errors.add(`File upload property "${a}" was removed.`),!1;if(u==="file"&&l!=="file")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(u==="fileArray"&&l!=="fileArray")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(u!=="file"&&u!=="fileArray"&&l!=="file"&&l!=="fileArray"&&!this.areTypeReferencesCompatible({from:u,to:l}))return this.errors.add(`File upload property "${a}" type changed.`),!1}return!0}checkHttpResponseBreakingChanges({id:t,from:r,to:i}){if(r.statusCode!==i.statusCode&&this.errors.add(`Response status code changed from "${r.statusCode}" to "${i.statusCode}".`),!(r.body==null&&i.body==null)){if(r.body==null||i.body==null){this.errors.add(`Response body was ${r.body==null?"added":"removed"}.`);return}switch(r.body.type){case"json":if(i.body.type==="json"){this.areJsonResponsesCompatible({from:r.body.value,to:i.body.value});return}break;case"fileDownload":if(i.body.type==="fileDownload")return;break;case"text":if(i.body.type==="text")return;break;case"bytes":if(i.body.type==="bytes")return;break;case"streaming":if(i.body.type==="streaming"){this.areStreamingResponsesCompatible({from:r.body.value,to:i.body.value});return}break;case"streamParameter":if(i.body.type==="streamParameter"){this.areStreamingResponsesCompatible({from:r.body.streamResponse,to:i.body.streamResponse});return}break;default:mo(r.body)}this.errors.add(`HTTP response type "${r.body.type}" defined for endpoint "${t}" is not compatible with type "${i.body.type}".`)}}areJsonResponsesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.responseBodyType,to:r.responseBodyType})}areStreamingResponsesCompatible({from:t,to:r}){switch(t.type){case"json":if(r.type==="json")return this.areTypeReferencesCompatible({from:t.payload,to:r.payload});break;case"sse":if(r.type==="sse")return this.areTypeReferencesCompatible({from:t.payload,to:r.payload});break;case"text":if(r.type==="text")return!0;break;default:mo(t)}return this.errors.add(`Streaming response type "${t.type}" is not compatible with type "${r.type}".`),!1}areTypeDeclarationsCompatible({from:t,to:r}){return this.areDeclaredTypeNamesCompatible({from:t.name,to:r.name})&&this.areTypeShapesCompatible({from:t.shape,to:r.shape})}areTypeShapesCompatible({from:t,to:r}){switch(t.type){case"alias":if(r.type==="alias")return this.areAliasTypesCompatible({from:t,to:r});break;case"enum":if(r.type==="enum")return this.areEnumTypesCompatible({from:t,to:r});break;case"object":if(r.type==="object")return this.areObjectTypesCompatible({from:t,to:r});break;case"union":if(r.type==="union")return this.areUnionTypesCompatible({from:t,to:r});break;case"undiscriminatedUnion":if(r.type==="undiscriminatedUnion")return this.areUndiscriminatedUnionTypesCompatible({from:t,to:r});break;default:mo(t)}return this.errors.add(`Type "${t.type}" is not compatible with type "${r.type}".`),!1}areAliasTypesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.aliasOf,to:r.aliasOf})}areEnumTypesCompatible({from:t,to:r}){let i=Object.fromEntries(t.values.map(a=>[a.name.wireValue,a])),n=Object.fromEntries(r.values.map(a=>[a.name.wireValue,a]));return Object.keys(i).length!==Object.keys(n).length?!1:Object.values(i).every(a=>{let u=n[a.name.wireValue];return u?this.areNameAndWireValuesCompatible({from:a.name,to:u.name}):(this.errors.add(`Enum value "${a.name.wireValue}" was removed.`),!1)})}areObjectTypesCompatible({from:t,to:r}){let i=Object.fromEntries([...t.properties.map(a=>[a.name.wireValue,a]),...t.extendedProperties?.map(a=>[a.name.wireValue,a])??[]]),n=Object.fromEntries([...r.properties.map(a=>[a.name.wireValue,a]),...r.extendedProperties?.map(a=>[a.name.wireValue,a])??[]]);return this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(i).map(([a,u])=>[a,u.valueType])),to:Object.fromEntries(Object.entries(n).map(([a,u])=>[a,u.valueType]))}),Object.values(i).every(a=>{let u=n[a.name.wireValue];return u?this.areObjectPropertiesCompatible({from:a,to:u}):(this.errors.add(`Object property "${a.name.wireValue}" was removed.`),!1)})}areObjectPropertiesCompatible({from:t,to:r}){return this.areNameAndWireValuesCompatible({from:t.name,to:r.name})&&this.areTypeReferencesCompatible({from:t.valueType,to:r.valueType})}areUnionTypesCompatible({from:t,to:r}){if(!this.areNameAndWireValuesCompatible({from:t.discriminant,to:r.discriminant}))return this.errors.add(`Union type with discriminant value "${t.discriminant.wireValue}" changed.`),!1;let i=new Set(t.extends.map(s=>this.getKeyForDeclaration(s))),n=new Set(r.extends.map(s=>this.getKeyForDeclaration(s)));for(let s of i)if(!n.has(s))return this.errors.add(`Extended type "${s}" was removed.`),!1;let a=Object.fromEntries(t.baseProperties.map(s=>[s.name.wireValue,s])),u=Object.fromEntries(r.baseProperties.map(s=>[s.name.wireValue,s]));for(let s of Object.values(a)){let o=u[s.name.wireValue];if(!o)return this.errors.add(`Union type with discriminant value "${s.name.wireValue}" no longer has a property named "${s.name.wireValue}".`),!1;if(!this.areObjectPropertiesCompatible({from:s,to:o}))return!1}this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(a).map(([s,o])=>[s,o.valueType])),to:Object.fromEntries(Object.entries(u).map(([s,o])=>[s,o.valueType]))});let l=Object.fromEntries(t.types.map(s=>[s.discriminantValue.wireValue,s])),d=Object.fromEntries(r.types.map(s=>[s.discriminantValue.wireValue,s]));return Object.values(l).every(s=>{let o=d[s.discriminantValue.wireValue];return o?this.areSingleUnionTypesCompatible({from:s.shape,to:o.shape}):(this.errors.add(`Union type for discriminant value "${s.discriminantValue.wireValue}" was removed.`),!1)})}areSingleUnionTypesCompatible({from:t,to:r}){switch(t.propertiesType){case"samePropertiesAsObject":if(r.propertiesType==="samePropertiesAsObject")return this.areDeclaredTypeNamesCompatible({from:t,to:r});break;case"singleProperty":if(r.propertiesType==="singleProperty")return this.areNameAndWireValuesCompatible({from:t.name,to:r.name})&&this.areTypeReferencesCompatible({from:t.type,to:r.type});break;case"noProperties":if(r.propertiesType==="noProperties")return!0;break;default:mo(t)}return this.errors.add(`Single union type of style "${t.propertiesType}" is not compatible with style "${r.propertiesType}".`),!1}areUndiscriminatedUnionTypesCompatible({from:t,to:r}){return t.members.every((i,n)=>{let a=r.members[n];return a?this.areTypeReferencesCompatible({from:i.type,to:a.type}):(this.errors.add(`Undiscriminated union member at index ${n} was removed.`),!1)})}checkForNewRequiredTypeReferences({from:t,to:r}){for(let[i,n]of Object.entries(r))t[i]||(n.type!=="container"||n.container.type!=="optional")&&this.errors.add(`Required property "${i}" was added.`)}checkForNewFileUploadRequestProperties({from:t,to:r}){for(let[i,n]of Object.entries(r))t[i]||n==="file"||n==="fileArray"||(n.type!=="container"||n.container.type!=="optional")&&this.errors.add(`Required property "${i}" was added.`)}checkForNewInlinedRequestBodyProperties({from:t,to:r}){for(let[i,n]of Object.entries(r))t[i]||(n.type!=="container"||n.container.type!=="optional")&&this.errors.add(`Required property "${i}" was added.`)}areTypeReferencesCompatible({from:t,to:r}){switch(t.type){case"primitive":if(r.type==="primitive")return this.arePrimitiveTypesCompatible({from:t,to:r});break;case"container":if(r.type==="container")return this.areContainerTypesCompatible({from:t.container,to:r.container});break;case"named":if(r.type==="named")return this.areNamedTypesCompatible({from:t,to:r});break;case"unknown":if(r.type==="unknown")return!0;break;default:mo(t)}return this.errors.add(`TypeReference "${t.type}" is not compatible with type "${r.type}".`),!1}arePrimitiveTypesCompatible({from:t,to:r}){return t.primitive.v1===r.primitive.v1}areContainerTypesCompatible({from:t,to:r}){switch(t.type){case"list":if(r.type==="list")return this.areTypeReferencesCompatible({from:t.list,to:r.list});break;case"set":if(r.type==="set")return this.areTypeReferencesCompatible({from:t.set,to:r.set});break;case"map":if(r.type==="map")return this.areTypeReferencesCompatible({from:t.keyType,to:r.keyType})&&this.areTypeReferencesCompatible({from:t.valueType,to:r.valueType});break;case"optional":if(r.type==="optional")return this.areTypeReferencesCompatible({from:t.optional,to:r.optional});break;case"nullable":if(r.type==="nullable")return this.areTypeReferencesCompatible({from:t.nullable,to:r.nullable});break;case"literal":if(r.type==="literal")return this.areLiteralsCompatible({from:t.literal,to:r.literal});break;default:mo(t)}return this.errors.add(`Container type "${t.type}" is not compatible with type "${r.type}".`),!1}areNamedTypesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areDeclaredTypeNamesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areDeclaredErrorNamesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areNameAndWireValuesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&t.wireValue===r.wireValue}areLiteralsCompatible({from:t,to:r}){switch(t.type){case"boolean":if(r.type==="boolean")return t.boolean===r.boolean;break;case"string":if(r.type==="string")return t.string===r.string;break;default:mo(t)}return!1}areFernFilepathsCompatible({from:t,to:r}){return t.allParts.length!==r.allParts.length?!1:t.allParts.every((i,n)=>{let a=r.allParts[n];return a==null?!1:this.areNamesCompatible({from:i,to:a})})}areNamesCompatible({from:t,to:r}){return t.originalName===r.originalName}getInlinedRequestBody(t){let r={};for(let i of[...t.extendedProperties??[],...t.properties])r[i.name.wireValue]=i.valueType;return r}getFileUploadRequest(t){let r={};for(let i of t)switch(i.type){case"file":r[i.value.key.wireValue]="file";break;case"bodyProperty":r[i.name.wireValue]=i.valueType;break;default:mo(i)}return r}getKeyForDeclaration({name:t,fernFilepath:r}){return`${r.allParts.map(n=>n.camelCase.unsafeName).join(".")}.${t.pascalCase.unsafeName}`}};function xB_({filteredIr:e,singleUnionTypeProperties:t}){return t._visit({samePropertiesAsObject:r=>{let i=e.hasTypeId(r.typeId)?{...r,object:{properties:r.object.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:wR({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)}}:void 0;return i!==void 0?y3.samePropertiesAsObject(i):void 0},singleProperty:r=>{let i=wR({filteredIr:e,exampleTypeReference:r});return i!==void 0?y3.singleProperty(i):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function wR({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:i=>({...t,shape:Nh.container(bm.list({...i,list:i.list.map(n=>wR({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:Nh.container(bm.set({...i,set:i.set.map(n=>wR({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?wR({filteredIr:e,exampleTypeReference:i.optional}):void 0;return n!=null?{...t,shape:Nh.container(bm.optional({optional:n,valueType:i.valueType}))}:void 0},nullable:i=>{let n=i.nullable!=null?wR({filteredIr:e,exampleTypeReference:i.nullable}):void 0;return n!=null?{...t,shape:Nh.container(bm.nullable({nullable:n,valueType:i.valueType}))}:void 0},map:i=>({...t,shape:Nh.container(bm.map({...i,map:i.map.map(n=>{let a=wR({filteredIr:e,exampleTypeReference:n.key}),u=wR({filteredIr:e,exampleTypeReference:n.value});return a!==void 0&&u!==void 0?{key:a,value:u}:void 0}).filter(n=>n!==void 0)}))}),literal:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}}),named:r=>e.hasTypeId(r.typeName.typeId)?r.shape._visit({alias:i=>{let n=wR({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:Nh.named({...r,shape:Iw.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:Nh.named({...r,shape:Iw.enum(i)})}),object:i=>({...t,shape:Nh.named({...r,shape:Iw.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:wR({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=xB_({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:Nh.named({...r,shape:Iw.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=wR({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:Nh.named({...r,shape:Iw.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function kPc({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=wR({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function gJE({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=wR({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function zB_({filteredIr:e,headers:t}){return t.map(r=>{let i=wR({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function OJE({filteredIr:e,requestBody:t}){return t._visit({inlinedRequestBody:r=>({...t,properties:r.properties.filter(i=>i.originalTypeDeclaration?e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue):!0).map(i=>{let n=wR({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=wR({filteredIr:e,exampleTypeReference:r});return i!==void 0?xQ.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function mJE({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>RT.ok(kC.body(i!=null?wR({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>RT.ok(kC.stream(i.map(n=>wR({filteredIr:e,exampleTypeReference:n})).filter(V0))),sse:i=>RT.ok(kC.sse(i.map(({event:n,data:a})=>{let u=wR({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:n,data:u}:void 0}).filter(V0))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>RT.error({error:r,body:i!=null?wR({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function ejc({filteredIr:e,example:t}){return{...t,rootPathParameters:kPc({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:kPc({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:kPc({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:zB_({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:zB_({filteredIr:e,headers:t.endpointHeaders}),queryParameters:gJE({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?OJE({filteredIr:e,requestBody:t.request}):void 0,response:mJE({filteredIr:e,response:t.response})}}function RB_({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=wR({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:Iw.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:Iw.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:wR({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=xB_({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:Iw.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=wR({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:Iw.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function tjc(e,t){if(t==null)return e;let r=AVi(e.types,l=>t.hasType(l)),i=Object.fromEntries(Object.entries(r).map(([l,d])=>{let s=[];if(d.userProvidedExamples=d.userProvidedExamples.map(o=>RB_({filteredIr:t,exampleType:o})).filter(o=>o!==void 0),d.shape.type==="object"){for(let o of d.shape.properties)t.hasProperty(l,o.name.wireValue)&&s.push(o);return[l,{...d,shape:lO.object({...d.shape,properties:s})}]}return[l,d]})),n=Object.fromEntries(Object.entries(e.webhookGroups).map(([l,d])=>{let s=d.filter(o=>t.hasWebhook(o)).map(o=>{let c=o.id;return o.payload.type==="inlinedPayload"&&c!=null&&(o.payload={...o.payload,properties:o.payload.properties.filter(b=>t.hasWebhookPayloadProperty(c,b.name.wireValue))}),o});return[l,s]})),a=e.websocketChannels!=null?Object.fromEntries(Object.entries(e.websocketChannels).filter(([l])=>t.hasChannel(l)).map(([l,d])=>[l,{...d}])):{},u=e.environments;if(u){switch(u.environments.type){case"singleBaseUrl":{u.environments.environments=u.environments.environments.filter(l=>t.hasEnvironmentId(l.id));break}case"multipleBaseUrls":{u.environments.environments=u.environments.environments.filter(l=>t.hasEnvironmentId(l.id));break}}u.defaultEnvironment&&(t.hasEnvironmentId(u.defaultEnvironment)||(u.defaultEnvironment=void 0))}return{...e,environments:u,types:i,errors:AVi(e.errors,l=>t.hasError(l)),services:dd(AVi(e.services,l=>t.hasService(l)),l=>({...l,endpoints:l.endpoints.filter(d=>t.hasEndpoint(d)).map(d=>(d.autogeneratedExamples=d.autogeneratedExamples.map(s=>({...s,example:ejc({filteredIr:t,example:s.example})})),d.userSpecifiedExamples=d.userSpecifiedExamples.map(s=>({...s,example:s.example!=null?ejc({filteredIr:t,example:s.example}):void 0})),d.queryParameters.length>0&&(d.queryParameters=d.queryParameters.filter(s=>t.hasQueryParameter(d.id,s.name.wireValue))),d.requestBody?.type==="inlinedRequestBody"?{...d,requestBody:{...d.requestBody,properties:d.requestBody.properties.filter(s=>t.hasRequestProperty(d.id,s.name.wireValue))}}:d))})),websocketChannels:a,webhookGroups:n,serviceTypeReferenceInfo:PJE(e.serviceTypeReferenceInfo,t)}}function PJE(e,t){if(t==null)return e;let r={};return Object.entries(e.typesReferencedOnlyByService).forEach(([i,n])=>{t.hasServiceId(i)&&(r[i]=n.filter(a=>t.hasTypeId(a)))}),{sharedTypes:e.sharedTypes.filter(i=>t.hasTypeId(i)),typesReferencedOnlyByService:r}}var pH={};jo(pH,{AudienceExtension:()=>pko,FernAvailabilityExtension:()=>_ko,FernEnumExtension:()=>hko,FernIgnoreExtension:()=>SKi,FernOptionalExtension:()=>yko,FernTypeExtension:()=>gko,FernTypeNameExtension:()=>Oko,SdkGroupNameExtension:()=>vko,SdkMethodNameExtension:()=>bko});var pko=class extends Pm{operation;key="x-fern-audiences";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(i=>typeof i=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{audiences:r}}};var _ko=class extends Pm{node;key="x-fern-availability";constructor({breadcrumbs:t,node:r,context:i}){super({breadcrumbs:t,context:i}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t==null||typeof t!="string")return;switch(t.toUpperCase().replace(/[-_\s]/g,"_")){case"IN_DEVELOPMENT":return B9.InDevelopment;case"PRE_RELEASE":case"BETA":return B9.PreRelease;case"GENERAL_AVAILABILITY":case"GA":return B9.GeneralAvailability;case"DEPRECATED":return B9.Deprecated;default:return}}};var jJE=hu.object({snake:hu.string().optional(),camel:hu.string().optional(),screamingSnake:hu.string().optional(),pascal:hu.string().optional()}),wJE=hu.object({description:hu.string().optional(),name:hu.string().optional(),casing:jJE.optional()}),NB_=hu.record(wJE);var hko=class extends Pm{schema;key="x-fern-enum";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t==null)return;let r=NB_.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-enum extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data}};var SKi=class extends Pm{operation;key="x-fern-ignore";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-ignore",path:this.breadcrumbs});return}return t}}};var yko=class extends Pm{parameter;key="x-fern-optional";constructor({breadcrumbs:t,parameter:r,context:i}){super({breadcrumbs:t,context:i}),this.parameter=r}convert(){let t=this.getExtensionValue(this.parameter);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-optional",path:this.breadcrumbs});return}return t}}};var vko=class extends Pm{operation;key="x-fern-sdk-group-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(i=>typeof i=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{groups:r}}};var bko=class extends Pm{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null&&typeof t=="string")return{methodName:t}}};var gko=class extends Pm{schema;key="x-fern-type";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t!=null&&typeof t=="string")return t}};var Oko=class extends Pm{schema;key="x-fern-type-name";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(typeof t=="string")return t}};var qpi=class extends yb{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:i}){super({breadcrumbs:t,context:r}),this.audiences=i,this.irGraph=new wKi(i),this.ir={auth:{docs:void 0,requirement:Ws.AuthSchemesRequirement.All,schemes:[]},selfHosted:!1,types:{},services:{},errors:{},webhookGroups:{},websocketChannels:void 0,headers:[],idempotencyHeaders:[],apiVersion:void 0,apiDisplayName:void 0,apiDocs:void 0,basePath:void 0,pathParameters:[],errorDiscriminationStrategy:Ws.ErrorDiscriminationStrategy.statusCode(),variables:[],serviceTypeReferenceInfo:{sharedTypes:[],typesReferencedOnlyByService:{}},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,environments:void 0,fdrApiDefinitionId:void 0,rootPackage:this.createPackage(),subpackages:{},sdkConfig:{hasFileDownloadEndpoints:!1,hasPaginatedEndpoints:!1,hasStreamingEndpoints:!1,isAuthMandatory:!0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}}}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((i,n)=>!new SKi({breadcrumbs:[...r,String(n)],operation:i,context:this.context}).convert()).map((i,n)=>this.removeXFernIgnores({document:i,breadcrumbs:[...r,String(n)]})):t!=null&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([i,n])=>!new SKi({breadcrumbs:[...r,i],operation:n,context:this.context}).convert()).map(([i,n])=>[i,this.removeXFernIgnores({document:n,breadcrumbs:[...r,i]})])):t}finalizeIr(){let t={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}};this.irGraph.hasNoAudiences()||(t=this.filterIrForAudiences(t));let r=this.context.exampleGenerationArgs,i=JPc({ir:t,exampleGeneration:r});if(this.context.generateV1Examples){let n=CRa({ir:t,exampleGeneration:r});return{...t,...n,...i}}return{...t,...i}}filterIrForAudiences(t){let r=this.irGraph.getFilteredEndpoints(),i=this.irGraph.getFilteredChannels(),n=this.irGraph.getFilteredWebhooks();for(let a of Object.values(t.services)){let u=[];for(let l of a.endpoints)r.has(l.id)&&u.push(l);a.endpoints=u}return t.websocketChannels=Object.fromEntries(Object.entries(t.websocketChannels??{}).filter(([a])=>i.has(a))),t.webhookGroups=Object.fromEntries(Object.entries(t.webhookGroups).filter(([a])=>n.has(a))),t}async resolveAllExternalRefs({spec:t}){let r=[t];for(;r.length>0;){let i=r.shift();i!=null&&(Array.isArray(i)?await this.resolveExternalRefsInArray(i,r):typeof i=="object"&&await this.resolveExternalRefsInObject(i,r))}return t}async resolveExternalRefsInArray(t,r){for(let i=0;i<t.length;i++)t[i]=await this.resolveReferenceChain(t[i],r)}async resolveExternalRefsInObject(t,r){for(let[i,n]of Object.entries(t))t[i]=await this.resolveReferenceChain(n,r)}async resolveReferenceChain(t,r){let i=t;if(!this.context.isReferenceObject(i))return r.push(i),t;for(;this.context.isReferenceObject(i);){let n=this.context.isExternalReference(i.$ref),a=await this.context.resolveMaybeExternalReference(i);if(a.resolved){if(i=a.value,n)return i}else return t}return t}shouldAddServerToCollectedServers({server:t,currentServers:r,specType:i="openapi"}){return i==="openapi"?!r.some(n=>n.url===t.url&&"x-fern-server-name"in n&&"x-fern-server-name"in t&&n["x-fern-server-name"]===t["x-fern-server-name"]):!r.some(n=>n.url===t.url&&"name"in n&&"name"in t&&n.name===t.name)}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:i,endpointGroupDisplayName:n,serviceName:a}){let u=this.context.getGroup({groupParts:i,namespace:this.context.namespace}),l=this.getOrCreatePackage({group:i}),d=[...u].map(c=>this.context.casingsGenerator.generateName(c)),s=d[d.length-1];l.service==null&&(l.service=a??`service_${u.map(c=>T_(c)).join("/")}`),this.ir.services[l.service]==null&&(this.ir.services[l.service]=this.createNewService({allParts:d,finalpart:s,endpointGroupDisplayName:n})),this.ir.services[l.service]?.endpoints.push(t);let o=this.ir.services[l.service];o!=null&&(this.irGraph.addEndpoint(o,t),this.irGraph.markEndpointForAudience(o.name,[t],r))}addWebhookToIr({webhook:t,operationId:r,audiences:i,group:n}){let a=n?.join(".")??r,u=this.getOrCreatePackage({group:n});this.ir.webhookGroups[a]==null&&(this.ir.webhookGroups[a]=[]),this.ir.webhookGroups[a].push(t),u.webhooks=a;let l=this.context.createFernFilepath();this.irGraph.addWebhook(l,t),i!=null&&this.irGraph.markWebhookForAudiences(l,t,i)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:i,websocketGroup:n}){let a=T_(n?.join(".")),u=T_(r),l=this.context.namespace?`${T_(this.context.namespace)}/`:"",d=a?`channel_${l}${a}`:`channel_${l}${u}`,s=n?this.getOrCreatePackage({group:n}):this.getOrCreatePackage({group:[u]});this.ir.websocketChannels={...this.ir.websocketChannels,[d]:t},d!==""?s.websocket==null&&(s.websocket=d):this.ir.rootPackage.websocket="";let o=this.context.createFernFilepath();this.irGraph.addChannel(o,d,t),i!=null&&this.irGraph.markChannelForAudiences(o,d,i)}addAuthToIR(t){this.ir.auth=t}addErrorsToIr(t){this.ir.errors=t;for(let r of Object.values(t))this.irGraph.addError(r)}addGlobalHeadersToIr(t){this.ir.headers=t}addEnvironmentsToIr({environmentConfig:t,audiences:r}){if(this.ir.environments=t,r!=null)for(let[i,n]of Object.entries(t??{}))r[i]!=null&&this.irGraph.markEnvironmentForAudiences(n,r[i])}addTypeToRootPackage(t){this.ir.rootPackage.types.push(t)}addTypeToPackage(t){let r=this.context.getGroup({groupParts:[],namespace:this.context.namespace});this.getOrCreatePackage({group:r}).types.push(t)}addTypesToIr(t){Object.assign(this.ir.types,Object.fromEntries(Object.entries(t).map(([r,i])=>[r,i.typeDeclaration])));for(let r of Object.values(t))this.irGraph.addType({declaredTypeName:r.typeDeclaration.name,descendantTypeIds:r.typeDeclaration.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:r.propertiesByAudience,descendantFilepaths:new Set}),this.irGraph.markTypeForAudiences(r.typeDeclaration.name,r.audiences)}updateEndpointsWithDefaultUrl(t){if(t!=null)for(let r of Object.values(this.ir.services))for(let i of r.endpoints)i.baseUrl==null&&(i.baseUrl=t)}createNewService({allParts:t,finalpart:r,endpointGroupDisplayName:i}){return{name:{fernFilepath:{allParts:t,packagePath:t.slice(0,-1),file:r}},displayName:i,basePath:fF(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0}}createPackage(t={}){return{fernFilepath:this.context.createFernFilepath(t),service:void 0,types:[],errors:[],subpackages:[],docs:void 0,webhooks:void 0,websocket:void 0,hasEndpointsInTree:!1,navigationConfig:void 0}}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...(t??[]).map(n=>T_(n))),r.length==0)return this.ir.rootPackage;let i=this.ir.rootPackage;for(let n=0;n<r.length;n++){let a=r[n]??"",l=`subpackage_${r.slice(0,n+1).join("/")}`;this.ir.subpackages[l]==null&&(this.ir.subpackages[l]={name:this.context.casingsGenerator.generateName(a),...this.createPackage({name:a})});let d=this.ir.subpackages[l];i.subpackages.includes(l)||i.subpackages.push(l),i=d}return i}};var TM={};jo(TM,{AbstractConverters:()=>ijc,ExampleConverter:()=>VFe,SchemaConverters:()=>rjc,ServersConverter:()=>LMe});var ijc={};jo(ijc,{AbstractMediaTypeObjectConverter:()=>Pko,AbstractParameterConverter:()=>jko});var VFe=class e extends yb{MAX_DEPTH=12;EXAMPLE_STRING="foo";EXAMPLE_NUMBER=42;EXAMPLE_BOOLEAN=!0;EXAMPLE_INTEGER=42;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;constructor({breadcrumbs:t,context:r,schema:i,example:n,depth:a=0,exampleGenerationStrategy:u,generateOptionalProperties:l=!1,seenRefs:d=new Set}){super({breadcrumbs:t,context:r}),this.example=n,this.schema=i,this.depth=a,this.exampleGenerationStrategy=u,this.generateOptionalProperties=l,this.seenRefs=d}convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,validExample:typeof this.example<"u"?this.example:{},errors:[]};if(this.context.isReferenceObject(this.schema)){let r=this.schema.$ref;if(this.seenRefs.has(r))return{isValid:!0,coerced:!1,validExample:this.example,errors:[]}}let t=this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});return t==null?{isValid:!1,coerced:!1,validExample:null,errors:[{message:"Schema is not resolvable",path:this.breadcrumbs}]}:typeof t!="object"?{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Schema should be an object: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]}:"nullable"in t&&t.nullable===!0&&this.example===null?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:Array.isArray(t.type)?this.convertSchemaTypeArray({resolvedSchema:t}):t.type=="null"?this.convertNull():t.type=="boolean"?this.convertBoolean():t.enum!=null?this.convertEnum(t):t.type=="number"?this.convertNumber():t.type=="string"?this.convertString():t.type=="integer"?this.convertInteger():t.type=="array"?this.convertArray({resolvedSchema:t}):"oneOf"in t&&t.oneOf!=null?this.convertOneOf({resolvedSchema:t}):"anyOf"in t&&t.anyOf!=null?this.convertAnyOf({resolvedSchema:t}):t.type=="object"||t.properties!=null||t.allOf!=null?this.convertObject({resolvedSchema:t}):typeof t=="object"&&Object.keys(t).length===0?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Unsupported schema type: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]}}convertNull(){let t=this.example===null;return t?{isValid:t,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Example is not null: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertBoolean(){let t=typeof this.example=="boolean";if(t)return{isValid:t,coerced:!1,validExample:this.example,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.default:this.schema.default,i=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.const:this.schema.const;return typeof r=="boolean"||typeof i=="boolean"?{isValid:!0,coerced:!1,validExample:i??r,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_BOOLEAN,errors:[{message:`Example is not a boolean: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertEnum(t){let r=t.enum?.includes(this.example)??!1;if(r)return{isValid:r,coerced:!1,validExample:this.example,errors:[]};let i=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return i!==void 0&&t.enum?.includes(i)?{isValid:!0,coerced:!1,validExample:i,errors:[]}:{isValid:r,coerced:!1,validExample:t.enum?.[0],errors:[{message:`Example is not one of the allowed enum values: ${JSON.stringify(t.enum,null,2)}`,path:this.breadcrumbs}]}}convertNumber(){if(typeof this.example=="number")return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};let t=Number(this.example);if(!isNaN(t))return{isValid:!0,coerced:!0,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof r=="number"?{isValid:!0,coerced:!1,validExample:r,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertString(){if(typeof this.example=="string")return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};if(typeof this.example!="object"&&!Array.isArray(this.example)&&this.example!=null)return{isValid:!0,coerced:!0,validExample:String(this.example),errors:[]};let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof t=="string"?{isValid:!0,coerced:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_STRING,errors:[{message:`Example cannot be converted to string: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertInteger(){if(typeof this.example=="number"&&Number.isInteger(this.example))return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};if(typeof this.example=="string"){let r=Number(this.example);if(!isNaN(r)&&Number.isInteger(r))return{isValid:!0,coerced:!0,validExample:r,errors:[]}}let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof t=="number"&&Number.isInteger(t)?{isValid:!0,coerced:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_INTEGER,errors:[{message:`Example is not an integer: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertArray({resolvedSchema:t}){if(t.type!="array")return{isValid:!1,coerced:!1,validExample:null,errors:[]};t.items==null&&(t.items={type:"string"});let r=this.example==null,i=this.example??t.example,a=(Array.isArray(i)?i:[i]).map(l=>new e({breadcrumbs:[...this.breadcrumbs,"items"],context:this.context,schema:t.items,example:l,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),u=a.every(l=>l?.isValid??!1)&&!r;return{isValid:u,coerced:!1,validExample:a.map(l=>l.validExample),errors:u?[]:a.flatMap(l=>l.errors)}}convertObject({resolvedSchema:t}){if(t.type=="object"&&t.properties==null&&t.allOf==null)return{isValid:!0,coerced:!1,validExample:this.example??{},errors:[]};let r=typeof this.example!="object"||this.example==null?{}:this.example,i=Object.entries(t.properties??{}).map(([l,d])=>{if(typeof d!="object")return{key:l,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(d)&&!this.isRequiredProperty({key:l,resolvedSchema:t}))return{key:l,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("readOnly"in d&&d.readOnly===!0&&"writeOnly"in d&&d.writeOnly===!0)return{key:l,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("readOnly"in d&&d.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:l,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("writeOnly"in d&&d.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:l,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};let s=!(l in r)||!("nullable"in d)&&r[l]==null||"nullable"in d&&d.nullable===!0&&r[l]===void 0,o=!t.required?.includes(l);if(s&&o){if(this.example===void 0&&this.generateOptionalProperties){let c=new e({breadcrumbs:[...this.breadcrumbs,l],context:this.context,schema:d,example:void 0,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:l,result:c.convert()}}return{key:l,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}}}else{let b=new e({breadcrumbs:[...this.breadcrumbs,l],context:this.context,schema:d,example:r[l],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:l,result:b}}}),n=(t.allOf??[]).map((l,d)=>new e({breadcrumbs:[...this.breadcrumbs,`allOf[${d}]`],context:this.context,schema:{...t,...l,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),a=i.every(l=>l.result.isValid)&&n.every(l=>l.isValid),u=Object.fromEntries(i.map(({key:l,result:d})=>[l,d.validExample]).filter(([l,d])=>d!==void 0));for(let l of n)if(typeof l.validExample=="object"&&l.validExample!==null){let d=l.validExample;u={...u,...Object.fromEntries(Object.entries(d).filter(([s,o])=>o!==void 0))}}if(Object.keys(u).length===0){let l=n.find(d=>d.validExample!==void 0&&(typeof d.validExample!="object"||d.validExample===null));l&&(u=l.validExample)}return{isValid:a,coerced:!1,validExample:u,errors:[...i.flatMap(({result:l})=>l.errors),...n.flatMap(l=>l.errors)]}}convertSchemaTypeArray({resolvedSchema:t}){if(!Array.isArray(t.type))return{isValid:!1,coerced:!1,validExample:null,errors:[]};if(t.type.length===1)return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:{...t,type:t.type[0]},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();let r=t.type.map((u,l)=>new e({breadcrumbs:[...this.breadcrumbs,`type[${l}]`],context:this.context,schema:{...t,type:u},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.some(u=>u?.isValid??!1),a=r.find(u=>u.isValid)?.validExample??r[0]?.validExample??null;return{isValid:i,coerced:!1,validExample:a,errors:i?[]:r.flatMap(u=>u?.errors??[])}}convertOneOf({resolvedSchema:t}){if(!("oneOf"in t)||t.oneOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=t.oneOf.map((u,l)=>new e({breadcrumbs:[...this.breadcrumbs,`oneOf[${l}]`],context:this.context,schema:{...t,...u,oneOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.filter(u=>u.isValid),n=i.length>0,a;return n?a=i.find(l=>!l.coerced)?.validExample??i[0]?.validExample:a=r[0]?.validExample,{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(u=>u.errors)}}convertAnyOf({resolvedSchema:t}){if(!("anyOf"in t)||t.anyOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=t.anyOf.map((u,l)=>new e({breadcrumbs:[...this.breadcrumbs,`anyOf[${l}]`],context:this.context,schema:u,example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.filter(u=>u.isValid),n=i.length>0,a;return n?a=i.find(l=>!l.coerced)?.validExample??i[0]?.validExample:a=r[0]?.validExample,{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(u=>u.errors)}}getMaybeUpdatedSeenRefs(){let t=new Set(this.seenRefs);return this.context.isReferenceObject(this.schema)&&t.add(this.schema.$ref),t}maybeResolveSchemaExample(t){let r=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(r!=null){if("example"in r)return r.example;if("examples"in r)return Object.values(r.examples??{})[0]}}isDeprecatedProperty(t){return t!=null&&"availability"in t&&t.availability==="deprecated"}isRequiredProperty({key:t,resolvedSchema:r}){return r.required?.includes(t)??!1}};var rjc={};jo(rjc,{ArraySchemaConverter:()=>$9n,EnumSchemaConverter:()=>U9n,ObjectSchemaConverter:()=>V9n,OneOfSchemaConverter:()=>W9n,PrimitiveSchemaConverter:()=>H9n,SchemaConverter:()=>HAi,SchemaOrReferenceConverter:()=>SJ});function FB_(e){return G2({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return hf.primitive({v1:"BASE_64",v2:Dp.base64({})});case"BOOLEAN":return hf.primitive({v1:"BOOLEAN",v2:Dp.boolean({default:void 0})});case"DATE":return hf.primitive({v1:"DATE",v2:Dp.date({})});case"DATE_TIME":return hf.primitive({v1:"DATE_TIME",v2:Dp.dateTime({})});case"FLOAT":return hf.primitive({v1:"FLOAT",v2:Dp.float({})});case"DOUBLE":return hf.primitive({v1:"DOUBLE",v2:Dp.double({default:void 0,validation:void 0})});case"UINT":return hf.primitive({v1:"UINT",v2:Dp.uint({})});case"UINT_64":return hf.primitive({v1:"UINT_64",v2:Dp.uint64({})});case"INTEGER":return hf.primitive({v1:"INTEGER",v2:Dp.integer({default:void 0,validation:void 0})});case"LONG":return hf.primitive({v1:"LONG",v2:Dp.long({default:void 0})});case"STRING":return hf.primitive({v1:"STRING",v2:Dp.string({default:void 0,validation:void 0})});case"UUID":return hf.primitive({v1:"UUID",v2:Dp.uuid({})});case"BIG_INTEGER":return hf.primitive({v1:"BIG_INTEGER",v2:Dp.bigInteger({default:void 0})});default:return}},unknown:()=>hf.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return hf.container(_b.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return hf.container(_b.list(t))},optional:t=>{if(t!=null)return hf.container(_b.optional(t))},nullable:t=>{if(t!=null)return hf.container(_b.nullable(t))},set:t=>{if(t!=null)return hf.container(_b.set(t))},literal:t=>hf.container(_b.literal(t._visit({string:r=>R9.string(r),boolean:r=>R9.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var U9n=class extends yb{schema;maybeFernEnum;constructor({context:t,breadcrumbs:r,schema:i,maybeFernEnum:n}){super({context:t,breadcrumbs:r}),this.schema=i,this.maybeFernEnum=n}convert(){if(!this.schema.enum)return;let r=this.schema.enum.filter(n=>typeof n=="string"||typeof n=="number").map(n=>{let a=n.toString(),u=this.maybeFernEnum?.[a],l=u?.name??a;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:l,wireValue:a}),docs:u?.description,availability:void 0,casing:u?.casing}});if(r.length===0){this.context.errorCollector.collect({message:`Received enum schema with no valid values: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}let i=this.context.getAsString(this.schema.default);return{type:lO.enum({default:i!=null?r.find(n=>n.name.wireValue===i):void 0,values:r})}}};var mko=class extends yb{schemaOrReferenceOrBoolean;constructor({context:t,breadcrumbs:r,schemaOrReferenceOrBoolean:i}){super({context:t,breadcrumbs:r}),this.schemaOrReferenceOrBoolean=i}convert(){let t=this.tryConvertUnknownMap();if(t!=null)return t;let r=this.tryConvertTypedMap();if(r!=null)return r}tryConvertUnknownMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean"){let t=hf.container(_b.map({keyType:yb.STRING,valueType:hf.unknown()}));return{type:lO.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new SJ({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let i=hf.container(_b.map({keyType:yb.STRING,valueType:r.type})),n=new Set;for(let a of r.schema?.typeDeclaration.referencedTypes??[])n.add(a);for(let a of Object.keys(r.inlinedTypes))n.add(a);return{type:lO.alias({aliasOf:i,resolvedType:i}),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}};function zRa({properties:e,required:t,breadcrumbs:r,context:i,errorCollector:n}){let a=[],u={},l={},d=new Set;for(let[s,o]of Object.entries(e??{})){let c=[...r,"properties",s];if(typeof o!="object"){n.collect({message:`Schema property ${s} should be an object`,path:c});continue}let b=SJE(r,o,i)??i.convertBreadcrumbsToName(c),g="nullable"in o?o.nullable:!1,m=new SJ({context:i,breadcrumbs:c,schemaOrReference:o,schemaIdOverride:b,wrapAsOptional:!t.includes(s),wrapAsNullable:g}).convert();if(m!=null){a.push({name:i.casingsGenerator.generateNameAndWireValue({name:s,wireValue:s}),valueType:m.type,docs:o.description,availability:m.availability,propertyAccess:i.getPropertyAccess(o),v2Examples:m.schema?.typeDeclaration?.v2Examples??{userSpecifiedExamples:{},autogeneratedExamples:{}}}),u={...u,...m.inlinedTypes},m.schema?.typeDeclaration.referencedTypes!=null&&m.schema.typeDeclaration.referencedTypes.forEach(P=>{d.add(P)});for(let P of m.schema?.audiences??[])l[P]==null&&(l[P]=new Set),l[P].add(s)}}for(let s of Object.keys(u))d.add(s);return{convertedProperties:a,propertiesByAudience:l,inlinedTypesFromProperties:u,referencedTypes:d}}function SJE(e,t,r){return r.isReferenceObject(t)?void 0:new pH.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}var V9n=class extends yb{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:lO.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set};let{convertedProperties:r,inlinedTypesFromProperties:i,referencedTypes:n,propertiesByAudience:a}=zRa({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector}),u=[],l=n,d=this.schema.required!=null&&this.schema.required.length>0,s=i,o=a;for(let[c,b]of(this.schema.allOf??[]).entries()){let g=[...this.breadcrumbs,"allOf",c.toString()],O;if(this.context.isReferenceObject(b)){if(!d){this.addTypeReferenceToExtends({reference:b,breadcrumbs:g,extends_:u,referencedTypes:l});continue}let M=this.context.resolveMaybeReference({schemaOrReference:b,breadcrumbs:g});if(M==null)continue;if(O=M,Object.keys(O.properties??{}).every(D=>!this.schema.required?.includes(D))){this.addTypeReferenceToExtends({reference:b,breadcrumbs:g,extends_:u,referencedTypes:l});continue}}else O=b;let{convertedProperties:m,inlinedTypesFromProperties:P,referencedTypes:E,propertiesByAudience:q}=zRa({properties:O.properties??{},required:[...this.schema.required??[],...O.required??[]],breadcrumbs:g,context:this.context,errorCollector:this.context.errorCollector});r.push(...m),s={...s,...P},o={...o,...q},E.forEach(M=>{l.add(M)})}for(let c of Object.keys(s))l.add(c);return{type:lO.object({properties:r,extends:u.map(c=>this.context.typeReferenceToDeclaredTypeName(c)).filter(V0),extendedProperties:[],extraProperties:t}),propertiesByAudience:o,referencedTypes:l,inlinedTypes:s}}addTypeReferenceToExtends({reference:t,breadcrumbs:r,extends_:i,referencedTypes:n}){let a=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:r});a.ok&&i.push(a.reference);let u=this.context.getTypeIdFromSchemaReference(t);u!=null&&n.add(u)}};var W9n=class extends yb{schema;id;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlinedTypes:a}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n}convert(){return this.shouldConvertAsNullableSchemaOrReference()?this.convertAsNullableSchemaOrReference():this.schema.discriminator!=null&&!this.unionVariantsContainLiteral({discriminantProperty:this.schema.discriminator.propertyName})?this.convertAsDiscriminatedUnion():this.convertAsUndiscriminatedUnion()}unionVariantsContainLiteral({discriminantProperty:t}){for(let[r,i]of Object.entries(this.schema.discriminator?.mapping??{})){let n=this.context.resolveReference({reference:{$ref:i},breadcrumbs:this.breadcrumbs});if(n.resolved&&!Object.keys(n.value.properties??{}).includes(t))return!1}return!0}convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=[],r=new Set,i={};for(let[d,s]of Object.entries(this.schema.discriminator.mapping??{})){let o=new SJ({context:this.context,schemaOrReference:{$ref:s},breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",d]}),c=this.context.getTypeIdFromSchemaReference({$ref:s});c!=null&&r.add(c);let b=o.convert();if(b?.type!=null&&c!=null){for(let O of Object.keys(b?.inlinedTypes??{}))r.add(O);for(let O of b.schema?.typeDeclaration.referencedTypes??[])r.add(O);let g=this.context.casingsGenerator.generateNameAndWireValue({name:d,wireValue:d});t.push({docs:void 0,discriminantValue:g,availability:b.availability,displayName:d,shape:RQ.samePropertiesAsObject({typeId:c,name:this.context.casingsGenerator.generateName(c),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:d})}),i={...i,...b.inlinedTypes}}}let{convertedProperties:n,referencedTypes:a,inlinedTypesFromProperties:u}=zRa({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});r=new Set([...r,...a]);let l=[];for(let[d,s]of(this.schema.allOf??[]).entries()){let o=[...this.breadcrumbs,"allOf",d.toString()];if(this.context.isReferenceObject(s)){let c=this.context.convertReferenceToTypeReference({reference:s,breadcrumbs:o});if(c.ok){let g=this.context.typeReferenceToDeclaredTypeName(c.reference);g!=null&&l.push(g)}let b=this.context.getTypeIdFromSchemaReference(s);b!=null&&r.add(b);continue}}for(let d of Object.keys({...i,...u}))r.add(d);return{type:lO.union({baseProperties:n,discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:l,types:t}),referencedTypes:r,inlinedTypes:{...i,...u}}}convertAsUndiscriminatedUnion(){if(!this.schema.oneOf&&!this.schema.anyOf||this.schema.anyOf?.length===0&&this.schema.oneOf?.length===0)return;let t=[],r=new Set,i={};for(let[n,a]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(a)){let c;if(this.context.isReferenceObjectWithIdentifier(a))c=this.context.convertReferenceToTypeReference({reference:a,displayNameOverride:a.title??a.name??a.messageId,displayNameOverrideSource:"reference_identifier"});else if(this.getDiscriminatorKeyForRef(a)!=null){let g=this.getDiscriminatorKeyForRef(a);c=this.context.convertReferenceToTypeReference({reference:a,displayNameOverride:g,displayNameOverrideSource:"discriminator_key"})}else c=this.context.convertReferenceToTypeReference({reference:a,displayNameOverrideSource:"schema_identifier"});c.ok&&t.push({type:c.reference,docs:a.description});let b=this.context.getTypeIdFromSchemaReference(a);b!=null&&r.add(b);continue}let u=this.extendSubSchema(a),l=this.context.convertBreadcrumbsToName([`${this.id}_${n}`]),d=a.title,o=new HAi({context:this.context,id:l,nameOverride:d,breadcrumbs:[...this.breadcrumbs,`oneOf[${n}]`],schema:u??a}).convert();if(o!=null){let c=o.convertedSchema.typeDeclaration.shape;c.type==="alias"&&this.typeReferenceIsWrappedPrimitive(c.aliasOf)?t.push({type:c.aliasOf,docs:a.description}):c.type==="object"&&c.properties.length===0?t.push({type:hf.container(_b.map({keyType:yb.STRING,valueType:hf.unknown()})),docs:a.description}):(t.push({type:this.context.createNamedTypeReference(l,d),docs:a.description}),i={...i,...o.inlinedTypes,[l]:o.convertedSchema}),o.convertedSchema.typeDeclaration.referencedTypes.forEach(b=>{r.add(b)})}}return{type:lO.undiscriminatedUnion({members:t}),referencedTypes:r,inlinedTypes:i}}shouldConvertAsNullableSchemaOrReference(){return this.schema.oneOf!=null?this.schema.oneOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):this.schema.anyOf!=null?this.schema.anyOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):!1}removeNullFromOneOfOrAnyOf(){let t=this.schema.oneOf??this.schema.anyOf,r=this.schema.oneOf!=null?"oneOf":"anyOf";if(t==null)return;let i=t.filter(n=>!("type"in n&&n.type==="null"));if(i.length===0){this.context.errorCollector.collect({message:`Received ${r} schema with no valid non-null types`,path:this.breadcrumbs});return}return i.length===1?{...this.schema,[r]:void 0,...i[0]}:{...this.schema,[r]:i}}convertAsNullableSchemaOrReference(){let t=this.removeNullFromOneOfOrAnyOf();if(t==null)return;let i=new SJ({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(i==null)return;let n=this.wrapInNullable(i.type);return{type:lO.alias({aliasOf:n,resolvedType:n}),referencedTypes:i.schema?.typeDeclaration.referencedTypes??new Set,inlinedTypes:i.inlinedTypes}}typeReferenceIsWrappedPrimitive(t){switch(t.type){case"container":return this.containerTypeIsWrappedPrimitive(t.container);case"named":return!1;case"primitive":return!0;case"unknown":return!0;default:return!1}}containerTypeIsWrappedPrimitive(t){switch(t.type){case"list":return this.typeReferenceIsWrappedPrimitive(t.list);case"map":return this.typeReferenceIsWrappedPrimitive(t.keyType)&&this.typeReferenceIsWrappedPrimitive(t.valueType);case"nullable":return this.typeReferenceIsWrappedPrimitive(t.nullable);case"optional":return this.typeReferenceIsWrappedPrimitive(t.optional);case"set":return this.typeReferenceIsWrappedPrimitive(t.set);case"literal":return!0;default:return!1}}wrapInNullable(t){return hf.container(_b.nullable(t))}mergeIntoObjectSchema(t,r){return{...t,properties:{...r,...t.properties??{}}}}extendSubSchema(t){if(Object.entries(this.schema.properties??{}).length===0)return t;if(t.type==="object")return this.mergeIntoObjectSchema(t,this.schema.properties??{});this.context.isObjectSchemaType(t)||this.context.errorCollector.collect({message:"Received additional object properties for oneOf/anyOf that are not objects",path:this.breadcrumbs})}getDiscriminatorKeyForRef(t){return Object.entries(this.schema.discriminator?.mapping??{}).find(([r,i])=>i===t.$ref)?.[0]}};var H9n=class extends yb{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){switch(this.schema.type){case"string":{let t=this.context.getAsString(this.schema.const);if(t!=null)return hf.container(_b.literal(R9.string(t)));if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return hf.primitive({v1:hb.Date,v2:Dp.date({})});if(this.schema.format==="date-time")return hf.primitive({v1:hb.DateTime,v2:Dp.dateTime({})})}return hf.primitive({v1:"STRING",v2:Dp.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return hf.primitive({v1:"DOUBLE",v2:Dp.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return hf.primitive({v1:"FLOAT",v2:Dp.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return hf.primitive({v1:"INTEGER",v2:Dp.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return hf.primitive({v1:"LONG",v2:Dp.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return hf.primitive({v1:"UINT",v2:Dp.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return hf.primitive({v1:"UINT_64",v2:Dp.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return hf.primitive({v1:"DOUBLE",v2:Dp.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return hf.primitive({v1:"DOUBLE",v2:Dp.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return hf.primitive({v1:"FLOAT",v2:Dp.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return hf.primitive({v1:"INTEGER",v2:Dp.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return hf.primitive({v1:"LONG",v2:Dp.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return hf.primitive({v1:"UINT",v2:Dp.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return hf.primitive({v1:"UINT_64",v2:Dp.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return hf.primitive({v1:"INTEGER",v2:Dp.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"boolean":{let t=this.context.getAsBoolean(this.schema.const);return t!=null?hf.container(_b.literal(R9.boolean(t))):hf.primitive({v1:"BOOLEAN",v2:Dp.boolean({default:this.schema.default})})}default:return}}getNumberValidation(t){return{max:t.maximum,min:t.minimum,exclusiveMax:typeof t.exclusiveMaximum=="boolean"?t.exclusiveMaximum:void 0,exclusiveMin:typeof t.exclusiveMinimum=="boolean"?t.exclusiveMinimum:void 0,multipleOf:t.multipleOf}}getStringValidation(t){return{minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,format:t.format}}};var DJE=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],HAi=class e extends yb{schema;id;inlined;audiences;nameOverride;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlined:a=!1,nameOverride:u}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n,this.inlined=a,this.nameOverride=u,this.audiences=this.context.getAudiences({operation:this.schema,breadcrumbs:this.breadcrumbs})??[]}convert(){let t=this.tryConvertFernTypeDeclaration();if(t!=null)return t;let r=this.tryConvertEnumSchema();if(r!=null)return r;let i=this.tryConvertSingularAllOfSchema();if(i!=null)return i;let n=this.tryConvertPrimitiveSchema();if(n!=null)return n;let a=this.tryConvertArraySchema();if(a!=null)return a;let u=this.tryConvertTypeArraySchema();if(u!=null)return u;let l=this.tryConvertOneOfAnyOfSchema();if(l!=null)return l;let d=this.tryConvertMapSchema();if(d!=null)return d;let s=this.tryConvertObjectAllOfSchema();if(s!=null)return s;let o=this.tryConvertUntypedSchema();if(o!=null)return o;this.context.errorCollector.collect({message:`Failed to convert schema object: ${JSON.stringify(this.schema,null,2)}`,path:this.breadcrumbs})}tryConvertEnumSchema(){if(!this.schema.enum?.length)return;let r=new pH.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),n=new U9n({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,maybeFernEnum:r}).convert();if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:n.type,referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertSingularAllOfSchema(){if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&this.schema.allOf?.length===1&&this.schema.allOf[0]!=null){let r=this.context.resolveMaybeReference({schemaOrReference:this.schema.allOf[0],breadcrumbs:this.breadcrumbs});if(r!=null){let n=new e({context:this.context,breadcrumbs:[...this.breadcrumbs,"allOf","0"],schema:r,id:this.id,inlined:!0}).convert();if(n?.convertedSchema.typeDeclaration?.shape.type!=="object")return n}}if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&Array.isArray(this.schema.allOf)&&this.schema.allOf.length>=1){let r={};for(let n of this.schema.allOf??[]){if(this.context.isReferenceObject(n))return;r=mIn(r,n,(a,u)=>{if(u===n)return a;if(Array.isArray(a)&&Array.isArray(u))return[...a,...u]})}return new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,id:this.id,inlined:!0}).convert()}}tryConvertPrimitiveSchema(){let r=new H9n({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:lO.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new $9n({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:lO.alias({aliasOf:r.typeReference,resolvedType:r.typeReference}),referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertTypeArraySchema(){if(Array.isArray(this.schema.type)&&this.schema.type.length>0)return this.schema.type.length===1?this.schema.type=this.schema.type[0]:(this.schema.oneOf=this.schema.type.map(t=>({type:t})),this.schema.type=void 0),this.convert()}tryConvertOneOfAnyOfSchema(){if(this.schema.oneOf!=null||this.schema.anyOf!=null){let r=new W9n({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,inlinedTypes:{}}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertMapSchema(){if((typeof this.schema.additionalProperties=="object"||typeof this.schema.additionalProperties=="boolean")&&this.schema.additionalProperties!=null&&!this.schema.properties&&!this.schema.allOf){if(typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties===!1)return;let r=new mko({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReferenceOrBoolean:this.schema.additionalProperties}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertObjectAllOfSchema(){if(this.schema.type==="object"||this.schema.properties!=null||this.schema.allOf!=null){let r=new V9n({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:r.propertiesByAudience},inlinedTypes:r.inlinedTypes}}}tryConvertUntypedSchema(){if(this.isUntypedSchema())return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:lO.alias({aliasOf:hf.unknown(),resolvedType:hf.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new pH.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let i=FB_(r);if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:lO.alias({aliasOf:i,resolvedType:i}),referencedTypes:new Set,omitV2Examples:!0}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}createTypeDeclaration({shape:t,referencedTypes:r,omitV2Examples:i}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:r,source:void 0,inline:this.inlined,v2Examples:i?void 0:this.convertSchemaExamples()}}convertDeclaredTypeName(){return{typeId:this.id,fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(this.id),displayName:this.nameOverride}}schemaOnlyHasAllowedKeys(t){let r=[...DJE,...t];return Object.keys(this.schema).every(n=>r.includes(n))}isUntypedSchema(){return!!(this.schema&&typeof this.schema=="object"&&!("oneOf"in this.schema)&&!("anyOf"in this.schema)&&!("allOf"in this.schema)&&!("items"in this.schema)&&!("properties"in this.schema))}convertSchemaExamples(){let t={userSpecifiedExamples:{},autogeneratedExamples:{}},r=this.context.getExamplesFromSchema({schema:this.schema,breadcrumbs:this.breadcrumbs});if(r.length===0){let i=this.generateOrValidateExample({example:void 0,ignoreErrors:!0});return t.autogeneratedExamples={[`${this.id}_example_autogenerated`]:i},t}return t.userSpecifiedExamples=this.convertUserSpecifiedExamples(r),t}convertUserSpecifiedExamples(t){let r={};for(let[i,n]of t.entries()){let a=this.context.resolveExample(n),u=this.generateOrValidateExample({example:a});r[`${this.id}_example_${i}`]=u}return r}generateOrValidateExample({example:t,ignoreErrors:r}){let i=new VFe({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n,errors:a}=i.convert();return r||a.forEach(u=>{this.context.errorCollector.collect({message:u.message,path:u.path})}),n}};var SJ=class extends yb{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:i,schemaIdOverride:n,wrapAsOptional:a=!1,wrapAsNullable:u=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=i,this.schemaIdOverride=n,this.wrapAsOptional=a,this.wrapAsNullable=u}convert(){let t=this.maybeConvertReferenceObject({schemaOrReference:this.schemaOrReference});if(t!=null)return t;let r=this.maybeConvertSingularAllOfReferenceObject();return r??this.convertSchemaObject({schema:this.schemaOrReference})}maybeConvertReferenceObject({schemaOrReference:t}){if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:r.inlinedTypes??{}}}}maybeConvertSingularAllOfReferenceObject(){if(this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null||this.schemaOrReference.allOf.length!==1)return;let t=this.schemaOrReference.allOf[0];if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:{}}}}convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),i=new HAi({context:this.context,breadcrumbs:this.breadcrumbs,schema:t,id:r}),n=this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs}),a=i.convert();if(a!=null){let u=a.convertedSchema.typeDeclaration.shape;return u.type==="alias"?{type:this.wrapTypeReference(u.aliasOf),schema:a.convertedSchema,inlinedTypes:a.inlinedTypes,availability:n}:{type:this.wrapTypeReference(this.context.createNamedTypeReference(r)),schema:a.convertedSchema,inlinedTypes:{...a.inlinedTypes,[r]:a.convertedSchema},availability:n}}}wrapTypeReference(t){return this.wrapAsOptional&&this.wrapAsNullable?this.wrapInOptional(this.wrapInNullable(t)):this.wrapAsOptional?this.wrapInOptional(t):this.wrapAsNullable?this.wrapInNullable(t):t}wrapInOptional(t){return hf.container(_b.optional(t))}wrapInNullable(t){return hf.container(_b.nullable(t))}};var $9n=class e extends yb{static LIST_UNKNOWN=hf.container(_b.list(hf.unknown()));schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){if(this.schema.items!=null){Array.isArray(this.schema.items)&&(this.schema.items={oneOf:this.schema.items});let r=new SJ({context:this.context,breadcrumbs:[...this.breadcrumbs,"items"],schemaOrReference:this.schema.items}).convert();if(r!=null){let i=new Set;for(let n of r.schema?.typeDeclaration.referencedTypes??[])i.add(n);return r.inlinedTypes!=null&&Object.values(r.inlinedTypes).forEach(n=>{n.typeDeclaration.referencedTypes.forEach(a=>{i.add(a)})}),{typeReference:hf.container(_b.list(r.type)),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var Pko=class extends yb{group;method;constructor({context:t,breadcrumbs:r,group:i,method:n}){super({context:t,breadcrumbs:r}),this.group=i,this.method=n}parseMediaTypeObject({mediaTypeObject:t,resolveSchema:r,contentType:i,schemaId:n}){if(t.schema==null)return;if(r){let d=this.context.resolveMaybeReference({schemaOrReference:t.schema,breadcrumbs:[...this.breadcrumbs,"content",i]});if(d==null)return;t.schema=d}let u=new SJ({context:this.context,breadcrumbs:[...this.breadcrumbs,"content",i,"schema"],schemaOrReference:t.schema,schemaIdOverride:n}).convert();if(u==null)return;let l=t.examples!=null?Object.fromEntries(Object.entries(t.examples).map(([d,s])=>{if(this.context.isReferenceObject(s)){let o=this.context.resolveReference({reference:s,breadcrumbs:[...this.breadcrumbs,"content",i,"examples"],skipErrorCollector:!0});return o.resolved?[d,o.value]:null}return[d,s]}).filter(d=>d!=null)):void 0;return{...u,examples:l}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let n=new SJ({context:this.context,breadcrumbs:[...this.breadcrumbs],schemaOrReference:t,schemaIdOverride:r}).convert();if(n!=null)return{...n,examples:void 0}}convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:r,exampleGenerationStrategy:i}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},a=t?.schema,u=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`});for(let[l,d]of u){let s=this.context.resolveExampleWithValue(d),o=this.context.isExampleWithSummary(d)?d.summary:l;s!=null&&(a!=null?n.userSpecifiedExamples[o]=this.generateOrValidateExample({schema:a,example:s,exampleGenerationStrategy:i}):n.userSpecifiedExamples[o]=s)}if(Object.keys(n.userSpecifiedExamples).length===0&&a!=null){let l=T_(`${[...this.group,this.method].join("_")}_example`);n.autogeneratedExamples[l]=this.generateOrValidateExample({schema:a,example:void 0,ignoreErrors:!0,generateOptionalProperties:r,exampleGenerationStrategy:i})}return n}generateOrValidateExample({schema:t,example:r,ignoreErrors:i,generateOptionalProperties:n,exampleGenerationStrategy:a}){let u=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(u==null)return;let l=this.context.getExamplesFromSchema({schema:u,breadcrumbs:this.breadcrumbs}),d=new VFe({breadcrumbs:this.breadcrumbs,context:this.context,schema:u,example:r??l[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:a}),{validExample:s,errors:o}=d.convert();return i||o.forEach(c=>{this.context.errorCollector.collect({message:c.message,path:c.path})}),s}};var jko=class extends yb{parameter;constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r}),this.parameter=i}convertToOutput({schema:t,typeReference:r,inlinedTypes:i}){let n=this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs}),a=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs}),u=this.getParameterSchemaWithExampleOverride({schema:a});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??yb.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,v2Examples:this.convertParameterExamples({schema:u??t}),availability:n},inlinedTypes:i};case"header":return{type:"header",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??yb.OPTIONAL_STRING,env:void 0,v2Examples:this.convertParameterExamples({schema:u??t}),availability:n},inlinedTypes:i};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:this.parameter.description,valueType:r??yb.STRING,location:"ENDPOINT",variable:void 0,v2Examples:this.convertParameterExamples({schema:u??t})},inlinedTypes:i};default:return}}getParameterSchemaWithExampleOverride({schema:t}){if(t!=null)return t.type==="string"&&t.example==null?{...t,example:this.parameter.name}:t}convertParameterExamples({schema:t}){let r={userSpecifiedExamples:{},autogeneratedExamples:{}},i=this.parameter.example,n=this.parameter.examples;for(let[a,u]of Object.entries(n??{})){let l=this.context.resolveExampleWithValue(u);l!=null&&(r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:l}))}if(i!=null){let a=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(r.userSpecifiedExamples)});r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:i})}if(Object.keys(r.userSpecifiedExamples).length===0){let a=`${this.parameter.name}_example`;r.autogeneratedExamples[a]=this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0})}return r}generateOrValidateExample({schema:t,ignoreErrors:r,example:i}){let n=new VFe({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:i}),{validExample:a,errors:u}=n.convert();return r||u.forEach(l=>{this.context.errorCollector.collect({message:l.message,path:l.path})}),a}};var wko=class extends Pm{server;key="x-fern-server-name";constructor({breadcrumbs:t,server:r,context:i}){super({breadcrumbs:t,context:i}),this.server=r}convert(){let t=this.getExtensionValue(this.server,"x-name");if(!(t==null||typeof t!="string"))return t}};var LB_="Base",LMe=class e extends yb{servers;endpointLevelServers;constructor({breadcrumbs:t,context:r,servers:i,endpointLevelServers:n}){super({breadcrumbs:t,context:r}),this.servers=i,this.endpointLevelServers=n}convert(){if(this.servers==null||this.servers.length===0||this.servers[0]==null)return;if(this.endpointLevelServers!=null&&this.endpointLevelServers.length>0){let r=this.getDefaultBaseUrlName(),i={id:r,name:this.context.casingsGenerator.generateName(r)},n=this.endpointLevelServers.map(l=>{let d=e.getServerName({server:l,context:this.context});return{id:d,name:this.context.casingsGenerator.generateName(d)}}).filter((l,d,s)=>s.findIndex(o=>o.id===l.id)===d),a=[i,...n],u=this.servers.map(l=>{let d=e.getServerName({server:l,context:this.context}),s=this.endpointLevelServers?.map(o=>[e.getServerName({server:o,context:this.context}),this.getServerUrl(o)]);return{id:d,name:this.context.casingsGenerator.generateName(d),urls:{[r]:this.getServerUrl(l),...Object.fromEntries(s??[])},docs:l.description}});return{value:{defaultEnvironment:u[0]?.id,environments:cx.multipleBaseUrls({baseUrls:a,environments:u})},defaultUrl:i.id}}let t=this.withExplodedServers(this.servers).map(r=>{let i=e.getServerName({server:r,context:this.context});return{id:i,name:this.context.casingsGenerator.generateName(i),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(r)),docs:r.description}}).filter(V0);return{value:{defaultEnvironment:t[0]?.id,environments:cx.singleBaseUrl({environments:t})},defaultUrl:t[0]?.id}}static getServerExtensionName({server:t,context:r}){return new wko({breadcrumbs:[],server:t,context:r}).convert()}static getServerName({server:t,context:r}){return t.name!=null?t.name:e.getServerExtensionName({server:t,context:r})??t.description??t.url}getServerUrl(t){if(t.variables==null)return t.url;let r=t.url;for(let[i,n]of Object.entries(t.variables))n.default!=null&&(r=r.replace(`{${i}}`,encodeURIComponent(n.default)));return r}withExplodedServers(t){return t.flatMap(r=>{if(r.variables==null)return[r];let i=Object.entries(r.variables).filter(([l,d])=>d.enum!=null&&d.enum.length>0);if(i.length===0)return[r];let n=i[0];if(n==null)return[r];let[a,u]=n;return u.enum==null?[r]:u.enum.map(l=>{let d=r.url.replace(`{${a}}`,encodeURIComponent(l)),s={};for(let[c,b]of Object.entries(r.variables??{}))c!==a&&(s[c]=b);let o={...r,url:d,variables:Object.keys(s).length>0?s:void 0,"x-fern-server-name":r.description?`${r.description}_${l}`:`${l}`,description:r.description};return this.withExplodedServers([o])[0]})}).filter(V0)}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?LB_:e.getServerExtensionName({server:this.servers[0],context:this.context})??LB_}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}};var xRa={400:"BadRequestError",401:"UnauthorizedError",402:"PaymentRequiredError",403:"ForbiddenError",404:"NotFoundError",405:"MethodNotAllowedError",406:"NotAcceptableError",407:"ProxyAuthenticationRequiredError",408:"RequestTimeoutError",409:"ConflictError",410:"GoneError",411:"LengthRequiredError",412:"PreconditionFailedError",413:"ContentTooLargeError",414:"URITooLongError",415:"UnsupportedMediaTypeError",416:"RangeNotSatisfiableError",417:"ExpectationFailedError",418:"ImATeapotError",419:"AuthenticationTimeoutError",420:"MethodFailureError",421:"MisdirectedRequestError",422:"UnprocessableEntityError",423:"LockedError",424:"FailedDependencyError",425:"TooEarlyError",426:"UpgradeRequiredError",428:"PreconditionError",429:"TooManyRequestsError",430:"RequestHeaderFieldsTooLargeError",431:"RequestHeaderFieldsTooLargeError",444:"NoResponseError",449:"RetryWithError",450:"BlockedByWindowsParentalControlsError",451:"UnavailableForLegalReasonsError",498:"InvalidTokenError",499:"ClientClosedRequestError",500:"InternalServerError",501:"NotImplementedError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError",505:"HTTPVersionNotSupportedError",506:"VariantAlsoNegotiatesError",507:"InsufficientStorageError",508:"LoopDetectedError",509:"BandwidthLimitExceededError",510:"NotExtendedError",511:"NetworkAuthenticationRequiredError"},EJE=new Set(Object.values(xRa));var MJE=hu.object({type:hu.string(),channelId:hu.string().optional(),messageId:hu.string(),value:hu.any()}),AJE=hu.object({summary:hu.string().optional(),description:hu.string().optional(),"query-parameters":hu.record(hu.string()).optional(),headers:hu.record(hu.string()).optional(),messages:hu.array(MJE)}),UB_=hu.array(AJE);var Sko=class extends Pm{channel;key="x-fern-examples";constructor({breadcrumbs:t,channel:r,context:i}){super({breadcrumbs:t??[],context:i}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(t==null)return;let r=UB_.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-examples extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data.map(i=>({summary:i.summary,description:i.description,queryParameters:i["query-parameters"],headers:i.headers,messages:i.messages.map(n=>({type:n.type,channelId:n.channelId,messageId:n.messageId,value:n.value}))}))}};var G9n=class extends yb{channel;channelPath;inlinedTypes={};websocketGroup;constructor({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a}){super({context:t,breadcrumbs:r}),this.websocketGroup=i,this.channel=n,this.channelPath=a}convertExamples({fullPath:t,baseUrl:r,asyncApiVersion:i}){let a=new Sko({context:this.context,breadcrumbs:this.breadcrumbs,channel:this.channel}).convert();return a==null?{}:Object.fromEntries(a.map((u,l)=>[l.toString(),{channel:{method:"GET",path:t},baseUrl:t,environment:r,auth:void 0,pathParameters:{},queryParameters:u.queryParameters,headers:u.headers,messages:u.messages.map(d=>({type:i==="v2"?d.type:d.messageId,body:d.value}))}]))}transformToValidPath(t){return t.startsWith("/")?t:"/"+t}};var $Ai=class extends TM.AbstractConverters.AbstractParameterConverter{parameterNamePrefix;constructor({context:t,breadcrumbs:r,parameter:i,parameterNamePrefix:n}){super({context:t,breadcrumbs:r,parameter:i}),this.parameterNamePrefix=n}convert(){let t,r={},n=new pH.FernOptionalExtension({breadcrumbs:this.breadcrumbs,parameter:this.parameter,context:this.context}).convert()??this.parameter.required===!1,a=this.parameter.schema??{...this.parameter,type:"string",enum:this.parameter.enum,default:this.parameter.default,example:this.parameter.example??this.parameter.name,examples:Object.values(this.parameter.examples??{}),deprecated:this.parameter.deprecated,required:void 0},l=new TM.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaIdOverride:this.parameterNamePrefix?`${this.parameterNamePrefix}_${this.parameter.name}`:this.parameter.name,schemaOrReference:a,wrapAsOptional:n}).convert();return l!=null&&(t=l.type,r=l.inlinedTypes??{}),this.convertToOutput({schema:a,typeReference:t,inlinedTypes:r})}};var Dko=class extends Pm{channel;key="x-fern-address";constructor({breadcrumbs:t,channel:r,context:i}){super({breadcrumbs:t,context:i}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(!(t==null||typeof t!="string"))return t}};var Q9n=class extends Pm{channel;key="x-fern-display-name";constructor({breadcrumbs:t,channel:r,context:i}){super({breadcrumbs:t,context:i}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(!(t==null||typeof t!="string"))return t}};var Eko=class extends G9n{inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a}){super({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a})}convert(){let t=[],r=[],i=[],a=new Q9n({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".");this.channel.parameters&&this.convertPathParameters({context:this.context,pathParameters:t}),this.channel.bindings?.ws!=null&&(this.convertHeaders({context:this.context,headers:i}),this.convertBindingQueryParameters({context:this.context,queryParameters:r}));let u;this.channel.subscribe!=null&&(u=this.convertMessage({context:this.context,operation:this.channel.subscribe,origin:"server"}));let l;this.channel.publish!=null&&(l=this.convertMessage({context:this.context,operation:this.channel.publish,origin:"client"}));let d=[];u!=null&&d.push(u),l!=null&&d.push(l);let o=new Dko({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert(),c=this.transformToValidPath(o??this.channelPath),b=this.channel.servers?.[0]??Object.keys(this.context.spec.servers??{})[0],g=fF(c),O=T_(this.channelPath),m=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[];return{channel:{name:this.context.casingsGenerator.generateName(O),displayName:a,baseUrl:b,path:g,auth:!1,headers:i,queryParameters:r,pathParameters:t,messages:d,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:c,baseUrl:b,asyncApiVersion:"v2"})}},audiences:m,inlinedTypes:this.inlinedTypes}}convertMessage({context:t,operation:r,origin:i}){let n,a=i==="server"?"subscribe":"publish",u=[...this.breadcrumbs,a],l=t.resolveMaybeReference({schemaOrReference:r.message,breadcrumbs:u});l!=null&&(r.message=l);let d=TVi(T_(`${this.channelPath}_${a}`)).replace(/ /g,"");if("oneOf"in r.message){let o=new TM.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:u,schemaOrReference:r.message,schemaIdOverride:d}).convert();o!=null&&o.schema!=null&&(n=o.schema,this.inlinedTypes={...this.inlinedTypes,...o.inlinedTypes})}else if(t.isMessageWithPayload(r.message)){let s=t.resolveMaybeReference({schemaOrReference:r.message.payload,breadcrumbs:u});if(s!=null){let c=new TM.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:u,schemaOrReference:s,schemaIdOverride:d}).convert();c!=null&&c.schema!=null&&(n=c.schema,this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes})}}if(n!=null){let s=n,o=hf.named({fernFilepath:t.createFernFilepath(),name:s.typeDeclaration.name.name,typeId:s.typeDeclaration.name.typeId,displayName:void 0,default:void 0,inline:!1}),c=N9.reference({bodyType:o,docs:r.description}),b=i==="server"?"subscribe":"publish";return{type:b,displayName:b,origin:i,body:c,availability:t.getAvailability({node:r,breadcrumbs:this.breadcrumbs}),docs:r.description}}}convertPathParameters({context:t,pathParameters:r}){for(let[i,n]of Object.entries(this.channel.parameters??{})){let a=t.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs});if(a==null)continue;let l=new $Ai({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...a,name:i,in:"path",description:a.description,required:a.required??!0}}).convert();l!=null&&(this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes},l.type==="path"&&r.push(l.parameter))}}convertHeaders({context:t,headers:r}){if(this.channel.bindings?.ws?.headers!=null){let i=this.channel.bindings.ws.headers.required??[];for(let[n,a]of Object.entries(this.channel.bindings.ws.headers.properties??{})){let u=t.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,n]});if(u==null)continue;let d=new $Ai({context:this.context,breadcrumbs:[...this.breadcrumbs,n],parameter:{name:n,in:"header",required:i.includes(n),schema:u,description:"description"in u?u.description:void 0}}).convert();d!=null&&d.type==="header"&&(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},r.push(d.parameter))}}}convertBindingQueryParameters({context:t,queryParameters:r}){if(this.channel.bindings?.ws?.query!=null){let i=this.channel.bindings.ws.query.required??[];for(let[n,a]of Object.entries(this.channel.bindings.ws.query.properties??{})){let u=t.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,n]});if(u==null)continue;let d=new $Ai({context:this.context,breadcrumbs:[...this.breadcrumbs,n],parameter:{name:n,in:"query",required:i.includes(n),schema:u,description:"description"in u?u.description:void 0,deprecated:u.deprecated??!1}}).convert();d!=null&&d.type==="query"&&(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},r.push(d.parameter))}}}};var J9n=class extends yb{servers;constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r}),this.servers=i}convert(){if(this.servers==null||Object.keys(this.servers).length===0)return;let t=[],r;for(let[i,n]of Object.entries(this.servers)){let a=this.buildSingleBaseUrlEnvironment(this.context,i,n);t.push(a),r==null&&(r=a.id)}return{defaultEnvironment:r,environments:cx.singleBaseUrl({environments:t})}}constructServerUrl(t,r){return r.includes("://")?r:`${t}://${r}`}};var Mko=class extends J9n{constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r,servers:i})}buildSingleBaseUrlEnvironment(t,r,i){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(i.protocol,i.url),docs:void 0}}};var njc="$message.",VB_="#/channels/",WB_="#/servers/",Ako=class extends G9n{operations;inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a,operations:u}){super({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a}),this.operations=u}convert(){let t=[],r=[],i=[],a=new Q9n({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".")??this.channelPath;this.channel.parameters&&this.convertChannelParameters({pathParameters:t,queryParameters:r,headers:i,channelPath:this.channelPath});let u=Object.entries(this.operations).reduce((b,[g,O])=>{try{this.getChannelPathFromOperation(O)===this.channelPath&&(b[g]=O)}catch{}return b},{}),l=[];for(let[b,g]of Object.entries(u))for(let O of g.messages){let m=this.context.convertReferenceToTypeReference({reference:O});if(m.ok){let P=N9.reference({bodyType:m.reference,docs:g.description});l.push({type:b,displayName:b,origin:g.action==="send"?"client":"server",body:P,availability:this.context.getAvailability({node:g,breadcrumbs:this.breadcrumbs}),docs:g.description})}}let d=this.resolveChannelServersFromReference(this.channel.servers??[])??Object.keys(this.context.spec.servers??{})[0],s=this.transformToValidPath(this.channel.address??this.channelPath),o=fF(s),c=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[];return{channel:{name:this.context.casingsGenerator.generateName(a),displayName:a,baseUrl:d,path:o,auth:!1,headers:i,queryParameters:r,pathParameters:t,messages:l,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:s,baseUrl:d,asyncApiVersion:"v3"})}},audiences:c,inlinedTypes:this.inlinedTypes}}convertChannelParameters({pathParameters:t,queryParameters:r,headers:i,channelPath:n}){for(let a of Object.values(this.channel.parameters??{})){let u=this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,"parameters"]});if(u==null)continue;let l=this.convertChannelParameterLocation(u.location);if(l==null)continue;let{type:d,parameterKey:s}=l,c=new $Ai({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...u,name:s,in:d},parameterNamePrefix:this.channelPath}).convert();if(c!=null)switch(this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes},c.type){case"path":t.push(c.parameter);break;case"query":r.push(c.parameter);break;case"header":i.push(c.parameter);break}}}convertChannelParameterLocation(t){try{let[r,i]=t.split("#/");if(r==null||i==null){this.context.errorCollector.collect({message:`Invalid location format: ${t}; unable to parse message type and parameter key`,path:this.breadcrumbs});return}if(!r.startsWith(njc)){this.context.errorCollector.collect({message:`Invalid location format: ${t}; expected ${njc} prefix`,path:this.breadcrumbs});return}let n=r.substring(njc.length);if(n!=="header"&&n!=="path"&&n!=="payload"){this.context.errorCollector.collect({message:`Invalid message type: ${n}. Must be one of: header, path, payload`,path:this.breadcrumbs});return}return n==="payload"?{type:"query",parameterKey:i}:{type:n,parameterKey:i}}catch{this.context.errorCollector.collect({message:`Invalid location format: ${t}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`,path:this.breadcrumbs});return}}resolveChannelServersFromReference(t){if(t==null||t.length===0||t[0]==null)return;let r=t[0];if(!r.$ref.startsWith(WB_)){this.context.errorCollector.collect({message:`Failed to resolve server name from server ref ${r.$ref}`,path:this.breadcrumbs});return}let i=r.$ref.substring(WB_.length);if(i==null){this.context.errorCollector.collect({message:`Failed to find server with name ${i}`,path:this.breadcrumbs});return}return i}getChannelPathFromOperation(t){if(!t.channel.$ref.startsWith(VB_))throw new Error(`Failed to resolve channel path from operation ${t.channel.$ref}`);return t.channel.$ref.substring(VB_.length)}};var qko=class extends J9n{constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r,servers:i})}buildSingleBaseUrlEnvironment(t,r,i){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(i.protocol,i.host),docs:void 0}}};var RRa=class extends qpi{constructor({context:t,breadcrumbs:r,audiences:i}){super({context:t,breadcrumbs:r,audiences:i})}async convert(){return this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec}),this.isAsyncAPIV3(this.context)?this.convertChannelMessages():this.convertComponentMessages(),this.convertSchemas(),this.convertServers(),this.convertChannels(),this.finalizeIr()}isAsyncAPIV3(t){return parseFloat(t.spec.asyncapi)>=3}convertChannelMessages(){let t=this.context.spec;for(let[r,i]of Object.entries(t.channels??{}))for(let[n,a]of Object.entries(i.messages??{})){if(!this.context.isMessageWithPayload(a)&&!this.context.isReferenceObject(a))continue;let u=["channels",r,"messages",n],l=this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:u});if(!this.context.isMessageWithPayload(l))continue;let d=this.context.resolveMaybeReference({schemaOrReference:l.payload,breadcrumbs:u});if(d==null)continue;let s=`${r}_${n}`;this.convertSchema({id:s,breadcrumbs:u,schema:d})}}convertComponentMessages(){for(let[t,r]of Object.entries(this.context.spec.components?.messages??{})){if(r.payload==null)continue;let i=["components","messages",t],n=this.context.resolveMaybeReference({schemaOrReference:r.payload,breadcrumbs:i});n!=null&&this.convertSchema({id:t,breadcrumbs:i,schema:n})}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{}))this.convertSchema({id:t,breadcrumbs:["components","schemas",t],schema:r})}convertSchema({id:t,breadcrumbs:r,schema:i}){let a=new TM.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:r,schema:i}).convert();a!=null&&(this.addTypeToRootPackage(t),this.addTypesToIr({...a.inlinedTypes,[t]:a.convertedSchema}))}convertServers(){let t;if(this.isAsyncAPIV3(this.context)){let r=this.context.spec.servers;t=new qko({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}else{let r=this.context.spec.servers;t=new Mko({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}this.addEnvironmentsToIr({environmentConfig:t})}convertChannels(){for(let[t,r]of Object.entries(this.context.spec.channels??{})){let n=new pH.SdkGroupNameExtension({breadcrumbs:["channels",t],operation:r,context:this.context}).convert()?.groups,a;if(this.isAsyncAPIV3(this.context)){let l=this.context.spec.operations??{};a=new Ako({context:this.context,breadcrumbs:["channels",t],websocketGroup:n,channel:r,channelPath:t,operations:l}).convert()}else a=new Eko({context:this.context,breadcrumbs:["channels",t],websocketGroup:n,channel:r,channelPath:t}).convert();a!=null&&(this.addWebsocketChannelToIr({websocketChannel:a.channel,channelPath:t,audiences:a.audiences,websocketGroup:n}),this.addTypesToIr(a.inlinedTypes))}}};var NRa=class extends f8{isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}getTypeIdFromMessageReference(t){let r=t.$ref.match(/\/messages\/(.+)$/);if(!(!r||!r[1]))return r[1]}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n}){let a,u=t.$ref.match(/^.*\/schemas\/(.+)$/),l=t.$ref.match(/^.*\/channels\/([^/]+)\/messages\/(.+)$/),d=t.$ref.match(/^.*\/messages\/(.+)$/);if(u&&u[1])return a=u[1],this.convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a});if(l&&l[2]){let s=l[1],o=l[2];return a=`${s}_${o}`,this.convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a})}else return d&&d[1]?(a=d[1],this.convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a})):{ok:!1}}convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a}){let u=this.resolveReference({reference:t,breadcrumbs:r});if(!u.resolved)return{ok:!1};let l;return n==="reference_identifier"?l=i??u.value.title:(n==="discriminator_key"||n==="schema_identifier")&&(l=u.value.title??i),{ok:!0,reference:hf.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(a),typeId:a,displayName:l,default:void 0,inline:!1})}}convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a}){let u=this.resolveReference({reference:t,breadcrumbs:r});if(!u.resolved)return{ok:!1};let l;return n==="reference_identifier"?l=i??u.value.name:(n==="discriminator_key"||n==="schema_identifier")&&(l=u.value.name??i),{ok:!0,reference:hf.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(a),typeId:a,displayName:l,default:void 0,inline:!1})}}convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a}){let u=this.resolveReference({reference:t,breadcrumbs:r});if(!u.resolved)return{ok:!1};let l;return n==="reference_identifier"?l=i??u.value.messageId??u.value.name:(n==="discriminator_key"||n==="schema_identifier")&&(l=u.value.messageId??u.value.name??i),{ok:!0,reference:hf.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(a),typeId:a,displayName:l,default:void 0,inline:!1})}}};var JB_=ci(ajc(),1);var Tko=class extends Pm{document;key="x-fern-global-headers";constructor({breadcrumbs:t,document:r,context:i}){super({breadcrumbs:t,context:i}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected non-array value for x-fern-global-headers",path:this.breadcrumbs});return}return t}}};function HB_({globalHeaders:e,context:t}){return e.map(r=>({name:t.casingsGenerator.generateNameAndWireValue({name:r.name??"",wireValue:r.header}),valueType:r.optional?yb.OPTIONAL_STRING:yb.STRING,env:r.env,v2Examples:r.optional?void 0:CJE({header:r,context:t}),availability:void 0,docs:void 0}))}function CJE({header:e,context:t}){let r=new VFe({breadcrumbs:[],context:t,schema:{type:"string"},example:e.header}),{validExample:i}=r.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{globalHeaderExample:i}}}var sjc=ci(ajc(),1);var $B_=["get","post","put","delete","patch","head"];var Cko=class extends Pm{operation;key="x-fern-idempotent";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-idempotent",path:this.breadcrumbs});return}return t}}};var BJE=hu.object({cursor:hu.string(),next_cursor:hu.string(),results:hu.string()}),IJE=hu.object({offset:hu.string(),results:hu.string(),step:hu.string().optional(),"has-next-page":hu.string().optional()}),ojc=hu.union([hu.boolean(),BJE,IJE]);var ujc="$request.",Bko="$response.",Iko=class extends Pm{operation;document;key="x-fern-pagination";constructor({breadcrumbs:t,operation:r,document:i,context:n}){super({breadcrumbs:t,context:n}),this.operation=r,this.document=i}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=ojc.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean"){let i=this.getExtensionValue(this.document);if(i==null)return;if(typeof i=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.",path:this.breadcrumbs});return}let n=ojc.safeParse(i);if(!n.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${n.error.message}`,path:this.breadcrumbs});return}if(typeof n.data=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:n.data})}if(typeof r.data=="boolean"){this.context.errorCollector.collect({message:"Pagination extension is a boolean with no global configuration.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:r.data})}convertPaginationConfig({config:t}){let r=t;if("cursor"in r)return{type:"cursor",cursor:f8.maybeTrimPrefix(r.cursor,ujc),nextCursor:f8.maybeTrimPrefix(r.next_cursor,Bko),results:f8.maybeTrimPrefix(r.results,Bko)};let i=t;return{type:"offset",offset:f8.maybeTrimPrefix(i.offset,ujc),results:f8.maybeTrimPrefix(i.results,Bko),step:i.step!=null?f8.maybeTrimPrefix(i.step,ujc):void 0,hasNextPage:i["has-next-page"]!=null?f8.maybeTrimPrefix(i["has-next-page"],Bko):void 0}}};var zJE="$request.",xJE=hu.object({"stream-condition":hu.string().optional(),format:hu.enum(["sse","json"]).optional(),"stream-description":hu.string().optional(),"response-stream":hu.any(),response:hu.any()}),RJE=hu.union([hu.boolean(),xJE]),zko=class extends Pm{operation;key="x-fern-streaming";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=RJE.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-streaming extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean")return r.data?{type:"stream",format:"json"}:void 0;if(r.data["stream-condition"]==null&&r.data.format!=null)return{type:"stream",format:r.data.format};if(r.data["stream-condition"]==null){this.context.errorCollector.collect({message:"Missing stream-condition property without specified format.",path:this.breadcrumbs});return}return{type:"streamCondition",format:r.data.format??"json",streamDescription:r.data["stream-description"],streamConditionProperty:f8.maybeTrimPrefix(r.data["stream-condition"],zJE),responseStream:r.data["response-stream"],response:r.data.response}}};var xko=class extends Pm{operation;key="x-fern-webhook";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-webhook",path:this.breadcrumbs});return}return t}}};var Rko=class extends Pm{operation;key="x-fern-examples";constructor({context:t,breadcrumbs:r,operation:i}){super({breadcrumbs:r,context:t}),this.operation=i}convert(){let t=this.getExtensionValue(this.operation);return t==null?void 0:(Array.isArray(t)?t:[]).filter(n=>{let a=JN.serialization.ExampleEndpointCallSchema.parse(n);return a.ok||this.context.errorCollector.collect({message:`Failed to parse x-fern-example in ${this.breadcrumbs.join(".")}`,path:this.breadcrumbs}),a.ok})}};var Nko=class extends TM.AbstractConverters.AbstractMediaTypeObjectConverter{responseBody;statusCode;streamingExtension;constructor({context:t,breadcrumbs:r,responseBody:i,group:n,method:a,statusCode:u,streamingExtension:l}){super({context:t,breadcrumbs:r,group:n,method:a}),this.responseBody=i,this.statusCode=u,this.streamingExtension=l}convert(){return this.shouldConvertAsStreaming()?this.convertStreamingResponseBody():this.convertNonStreamingResponseBody()}convertStreamingResponseBody(){if(this.streamingExtension!=null){if(this.streamingExtension.type=="streamCondition"){let t=this.streamingExtension.responseStream,r=this.streamingExtension.response,i=[...this.group,this.method,"Response",this.statusCode].join("_"),n=`${i}_streaming`,a=this.parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:n}),u=this.parseMediaTypeSchemaOrReference({schemaOrReference:r,schemaId:i});return this.convertStreamConditionResponse({convertedStreamingSchema:a,convertedNonStreamingSchema:u})}if(this.streamingExtension.type==="stream"){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{});for(let i of r){let n=this.responseBody.content?.[i];if(n==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:n,schemaId:t,contentType:this.streamingExtension.format});if(a!=null)return this.convertStreamingResponse({mediaTypeObject:n,convertedSchema:a})}}}}convertNonStreamingResponseBody(){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{}).filter(n=>n.includes("json"));for(let n of r){let a=this.responseBody.content?.[n];if(a==null)continue;let u=this.parseMediaTypeObject({mediaTypeObject:a,schemaId:t,contentType:n});if(u!=null&&this.shouldReturnJsonResponse(n))return this.returnJsonResponse({mediaTypeObject:a,convertedSchema:u})}let i=Object.keys(this.responseBody.content??{}).filter(n=>!n.includes("json"));for(let n of i){let a=this.responseBody.content?.[n];if(a==null)continue;let u=this.parseMediaTypeObject({mediaTypeObject:a,schemaId:t,contentType:n});if(u!=null){if(this.isBinarySchema(u))return this.shouldReturnBytesResponse()?this.returnBytesResponse({mediaTypeObject:a}):this.returnFileDownloadResponse({mediaTypeObject:a});if(this.shouldReturnTextResponse(n))return this.returnTextResponse({mediaTypeObject:a})}}}convertStreamConditionResponse({convertedStreamingSchema:t,convertedNonStreamingSchema:r}){if(!(t==null||r==null))return{responseBody:NS.json(IQ.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:r.schema?.typeDeclaration.v2Examples})),streamResponseBody:NS.streaming(x9.json({docs:this.responseBody.description,payload:t.type,terminator:void 0,v2Examples:t.schema?.typeDeclaration.v2Examples})),inlinedTypes:{...t.inlinedTypes,...r.inlinedTypes}}}convertStreamingResponse({mediaTypeObject:t,convertedSchema:r}){if(this.streamingExtension==null)return;switch(this.streamingExtension.format){case"json":return{responseBody:NS.streaming(x9.json({docs:this.responseBody.description,payload:r.type,terminator:void 0,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples};case"sse":return{responseBody:NS.streaming(x9.sse({docs:this.responseBody.description,payload:r.type,terminator:void 0,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples};default:return}}returnJsonResponse({mediaTypeObject:t,convertedSchema:r}){return{responseBody:NS.json(IQ.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples}}returnBytesResponse({mediaTypeObject:t}){return{responseBody:NS.bytes({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{}}}returnFileDownloadResponse({mediaTypeObject:t}){return{responseBody:NS.fileDownload({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{}}}returnTextResponse({mediaTypeObject:t}){return{responseBody:NS.text({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{}}}isBinarySchema(t){let r=t.type;switch(r.type){case"container":case"named":case"unknown":return!1;case"primitive":return r.primitive.v2==null?!1:r.primitive.v2.type==="string"&&r.primitive.v2.validation?.format==="binary";default:return!1}}shouldConvertAsStreaming(){return this.streamingExtension!=null}shouldReturnJsonResponse(t){return t.includes("json")}shouldReturnBytesResponse(){return this.context.settings.useBytesForBinaryResponse&&this.streamingExtension==null}shouldReturnTextResponse(t){return mM.parse(t)?.isText()??!1}};var Fko=class extends TM.AbstractConverters.AbstractMediaTypeObjectConverter{responseError;statusCode;methodName;constructor({context:t,breadcrumbs:r,responseError:i,group:n,method:a,methodName:u,statusCode:l}){super({context:t,breadcrumbs:r,group:n,method:a}),this.responseError=i,this.statusCode=l,this.methodName=u}convert(){if(!this.responseError.content){let i=xRa[this.statusCode];if(i==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}let n=this.getErrorIdFromErrorName(i);return{error:{error:{name:this.context.casingsGenerator.generateName(n),fernFilepath:{allParts:[],packagePath:[],file:void 0},errorId:n},docs:this.responseError.description},errorType:hf.unknown(),displayName:i,statusCode:this.statusCode,inlinedTypes:{},examples:{}}}let t=Object.keys(this.responseError.content).filter(i=>i.includes("json")),r=xRa[this.statusCode];if(r==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}for(let i of[...t]){let n=this.responseError.content?.[i];if(n==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:n,schemaId:GB_(`${this.methodName}Request${r}`),contentType:i});if(a==null)continue;let u=this.getErrorIdFromErrorName(r);if(a.schema!=null)return this.constructErrorConverterOutput({errorName:r,errorId:u,fernFilepath:a.schema.typeDeclaration.name.fernFilepath,convertedSchema:a});if(a.type.type==="named")return this.constructErrorConverterOutput({errorName:r,errorId:u,fernFilepath:a.type.fernFilepath,convertedSchema:a})}}constructErrorConverterOutput({errorName:t,errorId:r,fernFilepath:i,convertedSchema:n}){return{error:{error:{name:this.context.casingsGenerator.generateName(r),fernFilepath:i,errorId:r},docs:this.responseError.description},errorType:n.type,displayName:t,statusCode:this.statusCode,inlinedTypes:n.inlinedTypes,examples:n.examples}}getErrorIdFromErrorName(t){return this.context.enableUniqueErrorsPerEndpoint?GB_(`${this.methodName}Request${t}`):t}};function GB_(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}var Lko=class extends TM.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r,parameter:i})}convert(){let t,r={};if(this.parameter.schema!=null){let i=this.context.convertBreadcrumbsToName([...this.breadcrumbs,this.parameter.name]),a=new TM.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,this.parameter.name,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required,schemaIdOverride:i}).convert();a!=null&&(t=a.type,r=a.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}};var Uko=class extends TM.AbstractConverters.AbstractMediaTypeObjectConverter{requestBody;schemaId;streamingExtension;constructor({context:t,breadcrumbs:r,requestBody:i,group:n,method:a,streamingExtension:u}){super({context:t,breadcrumbs:r,group:n,method:a}),this.requestBody=i,this.schemaId=[...this.group,this.method,"Request"].join("_"),this.streamingExtension=u}convert(){if(this.requestBody.content)return this.streamingExtension?.type=="streamCondition"?this.convertStreamConditionRequestBody():this.convertNonStreamConditionRequestBody()}convertStreamConditionRequestBody(){let t=this.getOrderedJsonOrFormContentTypes();for(let r of t){let i=this.handleStreamConditionJsonOrFormContent({contentType:r});if(i!=null)return i}}convertNonStreamConditionRequestBody(){let t=this.getOrderedJsonOrFormContentTypes();for(let n of t){let a=this.handleJsonOrFormContent({contentType:n});if(a!=null)return a}let r=Object.keys(this.requestBody.content).filter(n=>mM.parse(n)?.isMultipart());for(let n of r){let a=this.handleMultipartContent({contentType:n});if(a!=null)return a}let i=Object.keys(this.requestBody.content).filter(n=>mM.parse(n)?.isOctetStream());for(let n of i){let a=this.handleOctetStreamContent({contentType:n});if(a!=null)return a}}getOrderedJsonOrFormContentTypes(){let t=Object.keys(this.requestBody.content).filter(n=>mM.parse(n)?.isJSON()),r=Object.keys(this.requestBody.content).filter(n=>mM.parse(n)?.isURLEncoded()),i=Object.keys(this.requestBody.content).filter(n=>mM.parse(n)?.isPlainText());return[...t,...r,...i]}handleJsonOrFormContent({contentType:t}){let r=this.requestBody.content[t];if(r==null)return;let i=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});if(i==null)return;let n=i.schema?.typeDeclaration.shape;return n?.type==="object"?{requestBody:pC.inlinedRequestBody({contentType:t,docs:this.requestBody.description,name:this.context.casingsGenerator.generateName(this.schemaId),extendedProperties:n.extendedProperties,extends:n.extends,properties:n.properties,extraProperties:n.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:i.inlinedTypes})}:{requestBody:pC.reference({contentType:t,docs:this.requestBody.description,requestBodyType:i.type,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:i.inlinedTypes??{}}}handleMultipartContent({contentType:t}){let r=this.requestBody.content[t];if(r==null||r.schema==null)return;let i=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,resolveSchema:!0,contentType:t});if(i==null)return;let n=i.schema?.typeDeclaration.shape;if(n?.type==="object")return{requestBody:pC.fileUpload({contentType:t,docs:this.requestBody.description,name:this.context.casingsGenerator.generateName(this.schemaId),properties:n.properties.map(a=>this.convertRequestBodyProperty({property:a,contentType:t})),v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:i.inlinedTypes}),examples:i.examples}}handleOctetStreamContent({contentType:t}){let r=this.requestBody.content[t];if(r==null)return;let i=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});return{requestBody:pC.bytes({contentType:t,isOptional:this.requestBody.required===!1,docs:this.requestBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:i?.inlinedTypes??{}}}convertRequestBodyProperty({property:t,contentType:r}){let{isFile:i,isOptional:n,isArray:a}=this.recursivelyCheckTypeReferenceIsFile({typeReference:t.valueType});return i?a?z9.file(Jne.fileArray({key:t.name,isOptional:n,contentType:r,docs:t.docs})):z9.file(Jne.file({key:t.name,isOptional:n,contentType:r,docs:t.docs})):z9.bodyProperty({...t,contentType:r,style:void 0,name:t.name})}handleStreamConditionJsonOrFormContent({contentType:t}){if(this.streamingExtension?.type!=="streamCondition")return;let r=this.requestBody.content[t];if(r==null||r.schema==null)return;let i=this.context.resolveMaybeReference({schemaOrReference:r.schema,breadcrumbs:[...this.breadcrumbs,"content",t,"schema"]});if(i==null)return;let n=i.properties?.[this.streamingExtension.streamConditionProperty];if(n==null||this.context.isReferenceObject(n))return;let a=this.buildStreamConditionInlinedRequestBody({streamConditionProperty:n,resolvedMediaTypeSchema:i,isStreaming:!0,contentType:t,mediaTypeObject:r}),u=this.buildStreamConditionInlinedRequestBody({streamConditionProperty:n,resolvedMediaTypeSchema:i,isStreaming:!1,contentType:t,mediaTypeObject:r});if(!(a==null||u==null))return{requestBody:u.requestBody,streamRequestBody:a.requestBody,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:{...a.inlinedTypes,...u.inlinedTypes}})}}buildStreamConditionInlinedRequestBody({streamConditionProperty:t,resolvedMediaTypeSchema:r,isStreaming:i,contentType:n,mediaTypeObject:a}){if(this.streamingExtension==null||this.streamingExtension.type!=="streamCondition")return;let u={...r,properties:{...r.properties,[this.streamingExtension.streamConditionProperty]:{type:"boolean",const:i,...t}},required:[...r.required??[],this.streamingExtension.streamConditionProperty]},l={...a,schema:u},d=this.parseMediaTypeObject({mediaTypeObject:l,schemaId:this.schemaId,contentType:n});if(d==null)return;let s=d.schema?.typeDeclaration.shape;if(s?.type==="object")return{requestBody:pC.inlinedRequestBody({contentType:n,docs:void 0,name:this.context.casingsGenerator.generateName(i?`${this.schemaId}_streaming`:this.schemaId),extendedProperties:s.extendedProperties,extends:s.extends,properties:s.properties,extraProperties:s.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:l,exampleGenerationStrategy:"request"})}),inlinedTypes:d.inlinedTypes}}recursivelyCheckTypeReferenceIsFile({typeReference:t,isOptional:r,isArray:i}){return this.context.isList(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.list,isOptional:r,isArray:!0}):this.context.isOptional(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.optional,isOptional:!0,isArray:i}):this.context.isNullable(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.nullable,isOptional:r,isArray:i}):{isFile:this.context.isFile(t),isOptional:r??!1,isArray:i??!1}}};var NJE=/{([^}]+)}/g,FJE=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]),K9n=class extends yb{operation;method;path;inlinedTypes={};constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a}){super({context:t,breadcrumbs:r}),this.operation=i,this.method=n,this.path=a}convertHttpMethod(){switch(this.method){case"get":return fR.Get;case"post":return fR.Post;case"put":return fR.Put;case"delete":return fR.Delete;case"patch":return fR.Patch;case"head":return fR.Head;default:return}}convertParameters({breadcrumbs:t}){let r=[],i=[],n=[];if(!this.operation.parameters)return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:i,headers:n};for(let a of this.operation.parameters){let u=this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:t});if(u==null)continue;let d=new Lko({context:this.context,breadcrumbs:t,parameter:u}).convert();if(d!=null)switch(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},d.type){case"path":r.push(d.parameter);break;case"query":i.push(d.parameter);break;case"header":{let s=d.parameter.name.name.originalName,o=d.parameter.name.wireValue,c=!1,b=this.context.authOverrides?.["auth-schemes"];if(b!=null){for(let g of Object.values(b))if(WJE(g)&&g.header.toLowerCase()===o.toLowerCase()){c=!0;break}}!FJE.has(s.toLowerCase())&&!c&&!this.context.globalHeaderNames?.includes(o)&&n.push(d.parameter);break}}}return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:i,headers:n}}checkMissingPathParameters(t){let i=[...this.path.matchAll(NJE)].map(n=>n[1]).filter(n=>!t.some(a=>a.name.originalName===n));for(let n of i){if(n==null)continue;let a=`${n}_example`;t.push({name:this.context.casingsGenerator.generateName(n),valueType:yb.STRING,docs:void 0,location:"ENDPOINT",variable:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{[a]:this.generateStringParameterExample({example:n})}}})}}convertRequestBody({breadcrumbs:t,group:r,method:i,streamingExtension:n}){if(this.operation.requestBody==null)return;let a=this.context.resolveMaybeReference({schemaOrReference:this.operation.requestBody,breadcrumbs:t});if(a==null)return null;let l=new Uko({context:this.context,breadcrumbs:t,requestBody:a,group:r??[],method:i,streamingExtension:n}).convert();if(l!=null)return this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes},{requestBody:l.requestBody,streamRequestBody:l.streamRequestBody,examples:l.examples}}computeGroupNameAndLocationFromExtensions(){let r=new pH.SdkMethodNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.methodName,n=new pH.SdkGroupNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.groups??[];if(r!=null)return{group:n,method:r}}evaluateMethodNameFromOperation(){let t=this.operation.operationId;return t??(this.operation.summary!=null?T_(this.operation.summary):T_(`${this.method}_${this.path.split("/").join("_")}`))}computeGroupNameFromTagAndOperationId(){let t=this.operation.tags?.[0],r=this.evaluateMethodNameFromOperation();if(t==null)return{method:r};let i=QB_(t),n=QB_(r);return mEe(i,n)?{method:t}:this.computeGroupAndMethodFromTokens({tag:t,tagTokens:i,methodName:r,methodNameTokens:n})}computeGroupAndMethodFromTokens({tag:t,tagTokens:r,methodName:i,methodNameTokens:n}){if(r.some((l,d)=>l!==n[d]))return{group:[t],method:i};let u=n.slice(r.length);return{group:[t],method:T_(u.join("_"))}}generateStringParameterExample({example:t}){let r=new TM.ExampleConverter({breadcrumbs:this.breadcrumbs,context:this.context,schema:{type:"string"},example:t}),{validExample:i}=r.convert();return i}};function QB_(e){let t=LJE(e)?UJE(e):VJE(e);return t=t.map(r=>r.toLowerCase()),t=Mxe(t),t}function LJE(e){return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)}function UJE(e){return e.split(/(?=[A-Z])/)}function VJE(e){return e.split(/[^a-zA-Z0-9]+/)}function WJE(e){return e?.header!=null}var Vko=class e extends K9n{idempotent;idToAuthScheme;topLevelServers;streamingExtension;static AUTHORIZATION_HEADER="Authorization";constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a,idempotent:u,idToAuthScheme:l,topLevelServers:d,streamingExtension:s}){super({context:t,breadcrumbs:r,operation:i,method:n,path:a}),this.idempotent=u,this.idToAuthScheme=l,this.topLevelServers=d,this.streamingExtension=s}convert(){let t=this.convertHttpMethod();if(t==null)return;let{group:r,method:i}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),n=this.getGroupDisplayName(r),{headers:a,pathParameters:u,queryParameters:l}=this.convertParameters({breadcrumbs:[...this.breadcrumbs,"parameters"]}),d=this.convertRequestBody({breadcrumbs:[...this.breadcrumbs,"requestBody"],group:r,method:i,streamingExtension:this.streamingExtension}),s=d?.requestBody,o=d?.streamRequestBody,c=this.convertResponseBody({breadcrumbs:[...this.breadcrumbs,"responses"],group:r,method:i,streamingExtension:this.streamingExtension}),b=c?.response,g=c?.streamResponse,O=c!=null?c.errors:[],m={},P=O.map(V=>V.error),E=fF(this.path),q=this.getEndpointBaseUrl(),M=this.getEndpointBaseUrls(),D=this.convertExamples({httpPath:E,httpMethod:t,baseUrl:q}),T=new Set(this.operation.security?.flatMap(V=>Object.keys(V))??[]),x=this.authSchemeToHeaders(Array.from(T));x.length>0&&a.push(...x);for(let V of O){let X=V.error,K=V.errorType,k=X.error.errorId;m[k]={name:X.error,displayName:V.displayName,discriminantValue:{name:X.error.name,wireValue:k},type:K,statusCode:V.statusCode,docs:X.docs,examples:[],v2Examples:void 0}}let $={displayName:this.operation.summary,method:t,baseUrl:q,v2BaseUrls:M,path:E,pathParameters:u,queryParameters:l,headers:a.filter((V,X,K)=>X===K.findIndex(k=>k.name.wireValue===V.name.wireValue)),sdkRequest:void 0,errors:P,auth:this.operation.security!=null||this.context.spec.security!=null,availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:this.idempotent??!1,basePath:void 0,fullPath:E,allPathParameters:u,pagination:void 0,transport:void 0,source:Qne.openapi()},I=this.context.namespace!=null?[this.context.namespace]:[],L=r?.map(V=>T_(V));return I.push(...L??[]),{audiences:this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],group:r,groupDisplayName:n,errors:m,endpoint:{...$,id:`endpoint_${I.join("/")}.${i}`,name:this.context.casingsGenerator.generateName(i),requestBody:s,response:b,docs:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:D.examples}},streamEndpoint:g!=null&&g.body!=null?{...$,id:`endpoint_${I.join("/")}.${i}_stream`,name:this.context.casingsGenerator.generateName(`${i}_stream`),requestBody:o,response:g,docs:this.streamingExtension?.type==="streamCondition"?this.streamingExtension.streamDescription??this.operation.description:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:D.streamExamples}}:void 0,inlinedTypes:this.inlinedTypes,servers:this.filterOutTopLevelServers(this.operation.servers??[])}}convertResponseBody({breadcrumbs:t,group:r,method:i,streamingExtension:n}){if(this.operation.responses==null)return;let a,u=!1;for(let[l,d]of Object.entries(this.operation.responses)){let s=parseInt(l);if(!(isNaN(s)||s<200||s>=300&&s<400)){if(a==null&&(a={response:void 0,streamResponse:void 0,errors:[],examples:{}}),s>=200&&s<300&&!u){let o=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:[...t,l]});if(o==null)continue;let b=new Nko({context:this.context,breadcrumbs:[...t,l],responseBody:o,group:r??[],method:i,statusCode:l,streamingExtension:n}).convert();b!=null&&(u=!0,this.inlinedTypes={...this.inlinedTypes,...b.inlinedTypes},a.response={statusCode:s,body:b.responseBody},a.streamResponse={statusCode:s,body:b.streamResponseBody})}if(s>=400&&s<600){let o=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:[...t,l]});if(o==null)continue;let b=new Fko({context:this.context,breadcrumbs:[...t,l],responseError:o,group:r??[],method:i,methodName:this.evaluateMethodNameFromOperation(),statusCode:s}).convert();b!=null&&(this.inlinedTypes={...this.inlinedTypes,...b.inlinedTypes},a.errors.push(b))}}}return a}authSchemeToHeaders(t){let r=[];for(let i of t){let n=this.idToAuthScheme?.[i];if(n==null)continue;let a={valueType:yb.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0};switch(n.type){case"bearer":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...a});break;case"basic":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...a});break;case"header":r.push({name:n.name,...a});break}}return r}convertExamples({httpPath:t,httpMethod:r,baseUrl:i}){let a=new Rko({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation}).convert();return a==null?{examples:{},streamExamples:{}}:this.streamingExtension?.type==="streamCondition"?this.convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:a}):{examples:this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:a}),streamExamples:{}}}convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:n}){let a=n.filter(s=>!(s.response!=null&&"stream"in s.response)),u=n.filter(s=>s.response!=null&&"stream"in s.response),l=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:a}),d=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:u});return{examples:l,streamExamples:d}}convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:n}){return Object.fromEntries(n.map((a,u)=>[this.getExampleName({example:a,exampleIndex:u}),{request:a.request!=null?{docs:void 0,endpoint:{method:r,path:this.buildExamplePath(t,a["path-parameters"]??{})},baseUrl:void 0,environment:i,auth:void 0,pathParameters:a["path-parameters"]??{},queryParameters:a["query-parameters"]??{},headers:a.headers??{},requestBody:a.request}:void 0,response:a.response!=null?{docs:void 0,statusCode:void 0,body:this.getExampleResponseBody({example:a})}:void 0,codeSamples:a["code-samples"]?.map(l=>{let d=("language"in l?l.language:l.sdk)??void 0;return{name:l.name,docs:void 0,language:d,code:l.code}})}]))}getExampleName({example:t,exampleIndex:r}){return t.name??t["code-samples"]?.[0]?.name??`Example_${r}`}getExampleResponseBody({example:t}){if(t.response!=null){if("stream"in t.response)return Ws.V2HttpEndpointResponseBody.stream(t.response.stream);if("body"in t.response)return Ws.V2HttpEndpointResponseBody.json(t.response.body)}}getEndpointBaseUrl(){let t=this.operation.servers?.[0];if(t==null)return;let i=this.topLevelServers?.find(n=>n.url===t.url)??t;return LMe.getServerName({server:i,context:this.context})}getEndpointBaseUrls(){let t=this.operation.servers;return t?.map(i=>{let a=this.topLevelServers?.find(u=>u.url===i.url)??i;return LMe.getServerName({server:a,context:this.context})})}buildExamplePath(t,r){return t.head+t.parts.map(i=>`${r[i.pathParameter]?.toString()??i.pathParameter}${i.tail}`).join("")}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers?.some(i=>i.url===r.url))}getGroupDisplayName(t){let r=this.operation.tags?.[0],i=t?.[t.length-1];if(i!=null&&r!=null)return r.toLowerCase().replaceAll(" ","")===i?r:void 0}};var Y9n=class extends K9n{constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a}){super({context:t,breadcrumbs:r,operation:i,method:n,path:a})}convert(){if(this.operation.requestBody==null){this.context.errorCollector.collect({message:"Skipping webhook because no request body present",path:this.breadcrumbs});return}let t=this.convertHttpMethod();if(t==null)return;if(t!=="POST"&&t!=="GET"){this.context.errorCollector.collect({message:"Skipping webhook because non-POST or GET method",path:this.breadcrumbs});return}let{group:r,method:i}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),n=[...this.breadcrumbs,"Payload"],{headers:a}=this.convertParameters({breadcrumbs:n}),u=this.convertRequestBody({breadcrumbs:n,group:r,method:i,streamingExtension:void 0});if(u==null)return;let{requestBody:l}=u,d;if(l.type==="inlinedRequestBody")d=EW.inlinedPayload({name:l.name,extends:l.extends,properties:l.properties});else if(l.type==="reference")d=EW.reference({payloadType:l.requestBodyType,docs:l.docs});else return;return{audiences:this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],group:r,webhook:{id:`${r?.join(".")??""}.${i}`,name:this.context.casingsGenerator.generateName(i),displayName:this.operation.summary,method:t,headers:a,payload:d,examples:[],availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),docs:this.operation.description,v2Examples:{autogeneratedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(l.v2Examples?.autogeneratedExamples??{}),userSpecifiedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(l.v2Examples?.userSpecifiedExamples??{})}},inlinedTypes:this.inlinedTypes}}getWebhookV2ExamplesFromRequestBodyV2Examples(t){return Object.fromEntries(Object.entries(t).map(([r,i])=>[r,{name:r,payload:i}]))}};var Wko=class extends yb{pathItem;path;idToAuthScheme;topLevelServers;constructor({context:t,breadcrumbs:r,pathItem:i,path:n,idToAuthScheme:a,topLevelServers:u}){super({context:t,breadcrumbs:r}),this.pathItem=i,this.path=n,this.idToAuthScheme=a,this.topLevelServers=u}convert(){let t=[],r=[],i={};for(let n of $B_){let a=this.pathItem[n];if(a==null)continue;let u=[...this.breadcrumbs,n],l=this.tryParseAsWebhook({operationBreadcrumbs:u,operation:a,method:n,context:this.context});if(l!=null){r.push(l),Object.assign(i,l.inlinedTypes);continue}let s=new zko({breadcrumbs:u,operation:a,context:this.context}).convert(),o=this.tryParseAsHttpEndpoint({operationBreadcrumbs:u,operation:a,method:n,streamingExtension:s});o!=null&&(t.push(o),Object.assign(i,o.inlinedTypes))}return{endpoints:t,webhooks:r,inlinedTypes:i}}tryParseAsWebhook({operation:t,method:r,operationBreadcrumbs:i,context:n}){return new xko({breadcrumbs:i,operation:t,context:n}).convert()?new Y9n({context:this.context,breadcrumbs:i,operation:t,method:sjc.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path}).convert():void 0}tryParseAsHttpEndpoint({operation:t,method:r,operationBreadcrumbs:i,streamingExtension:n}){new Iko({breadcrumbs:i,operation:t,document:this.context.spec,context:this.context}).convert()!=null;let d=new Cko({breadcrumbs:i,operation:t,context:this.context}).convert();return new Vko({context:this.context,breadcrumbs:i,operation:t,method:sjc.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,idempotent:d,idToAuthScheme:this.idToAuthScheme,topLevelServers:this.topLevelServers,streamingExtension:n}).convert()}};var Hko=class extends yb{securityScheme;constructor({context:t,breadcrumbs:r,securityScheme:i}){super({context:t,breadcrumbs:r}),this.securityScheme=i}convert(){switch(this.securityScheme.type){case"http":{if(this.securityScheme.scheme==="bearer")return CB.bearer({token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:this.securityScheme.description});if(this.securityScheme.scheme==="basic")return CB.basic({username:this.context.casingsGenerator.generateName("username"),password:this.context.casingsGenerator.generateName("password"),usernameEnvVar:void 0,passwordEnvVar:void 0,docs:this.securityScheme.description});break}case"apiKey":{if(this.securityScheme.in==="header")return CB.header({name:{name:this.context.casingsGenerator.generateName("apiKey"),wireValue:this.securityScheme.name},valueType:yb.OPTIONAL_STRING,prefix:void 0,headerEnvVar:void 0,docs:this.securityScheme.description});break}case"oauth2":return CB.bearer({token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:this.securityScheme.description})}}};var FRa=class extends qpi{constructor({breadcrumbs:t,context:r,audiences:i}){super({breadcrumbs:t,context:r,audiences:i})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec});let t=this.convertSecuritySchemes();this.convertGlobalHeaders(),this.convertSchemas(),this.convertWebhooks();let{endpointLevelServers:r,errors:i}=this.convertPaths({idToAuthScheme:t});this.addErrorsToIr(i);let{defaultUrl:n}=this.convertServers({endpointLevelServers:r});return this.updateEndpointsWithDefaultUrl(n),this.finalizeIr()}convertGlobalHeaders(){this.context.globalHeaderOverrides;let r=new Tko({breadcrumbs:["x-fern-global-headers"],document:this.context.spec,context:this.context}).convert();if(r!=null){let i=HB_({globalHeaders:r,context:this.context});this.addGlobalHeadersToIr(i),this.context.setGlobalHeaders(i)}}convertSecuritySchemes(){if(this.context.authOverrides)return this.addAuthToIR(XPc({rawApiFileSchema:this.context.authOverrides,casingsGenerator:this.context.casingsGenerator})),{};let t={},r=[];for(let[i,n]of Object.entries(this.context.spec.components?.securitySchemes??{})){let a=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:["components","securitySchemes",i]});if(a==null)continue;let l=new Hko({context:this.context,breadcrumbs:["components","securitySchemes",i],securityScheme:a}).convert();l!=null&&(this.shouldAddAuthSchemeToIr({authScheme:l,schemeId:i,currentSecuritySchemes:r})?r.push(l):t[i]=l)}return r.length>0&&this.addAuthToIR({requirement:r.length===1?"ALL":"ANY",schemes:r,docs:void 0}),t}convertServers({endpointLevelServers:t}){if(this.context.environmentOverrides){let n=BRa({rawApiFileSchema:this.context.environmentOverrides,casingsGenerator:this.context.casingsGenerator});return n!=null&&this.addEnvironmentsToIr({environmentConfig:n.environmentsConfig,audiences:n.audiences}),{defaultUrl:this.context.environmentOverrides["default-url"]}}let i=new LMe({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();return this.addEnvironmentsToIr({environmentConfig:i?.value}),{defaultUrl:i?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let n=new TM.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();n!=null&&(this.addTypeToPackage(t),this.addTypesToIr({...n.inlinedTypes,[t]:n.convertedSchema}))}}convertWebhooks(){for(let[,t]of Object.entries(this.context.spec.webhooks??{})){if(t==null){this.context.errorCollector.collect({message:"Skipping empty webhook",path:this.breadcrumbs});continue}if(!("post"in t)){this.context.errorCollector.collect({message:"Skipping webhook as it is not a POST method",path:this.breadcrumbs});continue}if(t.post?.operationId==null){this.context.errorCollector.collect({message:"Skipping webhook as no operationId is present",path:this.breadcrumbs});continue}let r=t.post.operationId,n=new Y9n({context:this.context,breadcrumbs:["webhooks",r],operation:t.post,method:JB_.OpenAPIV3.HttpMethods.POST,path:r}).convert();n!=null&&(this.addWebhookToIr({webhook:n.webhook,operationId:r,audiences:n.audiences,group:n.group}),this.addTypesToIr(n.inlinedTypes))}}convertPaths({idToAuthScheme:t}){let r=[],i={};for(let[n,a]of Object.entries(this.context.spec.paths??{})){if(a==null)continue;let l=new Wko({context:this.context,breadcrumbs:["paths",n],topLevelServers:this.context.spec.servers,pathItem:a,path:n}).convert();if(l!=null){for(let d of l.endpoints){if(d.streamEndpoint!=null&&this.addEndpointToIr({endpoint:d.streamEndpoint,audiences:d.audiences,endpointGroup:d.group,endpointGroupDisplayName:d.groupDisplayName}),this.addEndpointToIr({endpoint:d.endpoint,audiences:d.audiences,endpointGroup:d.group,endpointGroupDisplayName:d.groupDisplayName}),d.servers)for(let s of d.servers)this.shouldAddServerToCollectedServers({server:s,currentServers:r})&&r.push(s);if(d.errors)for(let[s,o]of Object.entries(d.errors))i[s]=o}for(let d of l.webhooks){let s=this.context.getGroup({groupParts:d.group,namespace:this.context.namespace});this.addWebhookToIr({webhook:d.webhook,operationId:s.join("."),group:s,audiences:d.audiences})}this.addTypesToIr(l.inlinedTypes)}}return{endpointLevelServers:r,errors:i}}shouldAddAuthSchemeToIr({authScheme:t,schemeId:r,currentSecuritySchemes:i}){let n=i.some(u=>u.type===t.type&&u.type==="bearer"&&t.type==="bearer"?u.token===t.token:!1),a=new Set(this.context.spec.security?.flatMap(u=>Object.keys(u))??[]);return(a.size===0||a.has(r))&&!n}};var LRa=class extends f8{globalHeaderNames;isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n}){let a=this.getTypeIdFromSchemaReference(t);if(a==null)return{ok:!1};let u=this.resolveReference({reference:t,breadcrumbs:r});if(!u.resolved)return{ok:!1};let l;n==="reference_identifier"?l=i??u.value.title:(n==="discriminator_key"||n==="schema_identifier")&&(l=u.value.title??i);let d;if(a.includes("/")){let o=new TM.SchemaConverters.SchemaConverter({context:this,breadcrumbs:r??[],schema:u.value,id:a}).convert();o!=null&&(d={[a]:o.convertedSchema})}return{ok:!0,reference:hf.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(a),typeId:a,default:void 0,inline:!1,displayName:l}),inlinedTypes:d}}setGlobalHeaders(t){this.globalHeaderNames=t.map(r=>r.name.wireValue)}};var $ko=class extends TM.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r,parameter:i})}convert(){let t,r={};if(this.parameter.schema!=null){let n=new TM.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required}).convert();n!=null&&(t=n.type,r=n.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}};var HJE=hu.object({description:hu.string().optional(),required:hu.boolean().optional(),deprecated:hu.boolean().optional(),allowEmptyValue:hu.boolean().optional(),style:hu.string().optional(),explode:hu.boolean().optional(),allowReserved:hu.boolean().optional(),schema:hu.any().optional(),example:hu.any().optional(),examples:hu.record(hu.string(),hu.any()).optional(),content:hu.record(hu.string(),hu.any()).optional()}),$JE=HJE.extend({name:hu.string(),in:hu.string()}),GJE=hu.array($JE),Gko=class extends Pm{operation;key="x-fern-parameters";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null)try{return GJE.parse(t)}catch(r){this.context.errorCollector.collect({message:`Failed to parse x-fern-parameters extension: ${r instanceof Error?r.message:String(r)}`,path:this.breadcrumbs});return}}};var Qko=class extends yb{method;pathParameters;queryParameters;headers;topLevelServers;constructor({context:t,breadcrumbs:r,method:i,pathParameters:n=[],queryParameters:a=[],headers:u=[],topLevelServers:l=[]}){super({context:t,breadcrumbs:r}),this.method=i,this.pathParameters=n,this.queryParameters=a,this.headers=u,this.topLevelServers=l}convert(){let t={},r="";for(let s of this.pathParameters)r+=`/{${s.name.originalName}}`;let i=fF(r),n=[];for(let[s,o]of this.method.params.entries()){let c;if(this.context.isReferenceObject(o)){let m=this.context.resolveReference({reference:o});if(m.resolved)c=m.value;else continue}else c=o;let b=[this.method.name,"Param",c.name].join("_"),O=new TM.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"Param",c.name],schemaIdOverride:b,context:this.context,schemaOrReference:c.schema,wrapAsOptional:!c.required}).convert();O!=null&&(n.push({docs:c.description,availability:this.context.getAvailability({node:o,breadcrumbs:[...this.breadcrumbs,"parameters"]}),name:this.context.casingsGenerator.generateNameAndWireValue({name:c.name,wireValue:c.name}),valueType:O.type,v2Examples:O.schema?.typeDeclaration.v2Examples}),t={...O.inlinedTypes,...t,...O.schema!=null?{[b]:O.schema}:{}})}let a;if(this.method.result!=null){let s=this.context.resolveMaybeReference({schemaOrReference:this.method.result,breadcrumbs:[...this.breadcrumbs,"result"]});if(s!=null){let o=new TM.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"result"],context:this.context,schemaOrReference:s.schema}),c=[this.method.name,"Result"].join("_"),b=o.convert();b!=null&&(a={docs:s.description,v2Examples:b.schema?.typeDeclaration.v2Examples,responseBodyType:b.type},t={...b.inlinedTypes,...t,...b.schema!=null?{[c]:b.schema}:{}})}}let u=this.getEndpointBaseUrls(),l=this.context.getAudiences({operation:this.method,breadcrumbs:this.breadcrumbs})??[];return{endpoint:{baseUrl:void 0,v2BaseUrls:u,basePath:void 0,auth:!1,method:"POST",id:this.method.name,docs:this.method.description,name:this.context.casingsGenerator.generateName(this.method.name),headers:this.headers,displayName:this.method.name,pathParameters:this.pathParameters,queryParameters:this.queryParameters,allPathParameters:this.pathParameters,path:i,fullPath:i,requestBody:n.length>0?pC.inlinedRequestBody({name:this.context.casingsGenerator.generateName([this.method.name,"Request"].join("_")),docs:void 0,properties:n,extends:[],extendedProperties:[],contentType:"application/json",extraProperties:!1,v2Examples:void 0}):void 0,sdkRequest:void 0,response:a!=null?{body:NS.json(IQ.response(a)),statusCode:void 0}:void 0,errors:[],idempotent:!1,pagination:void 0,userSpecifiedExamples:[],autogeneratedExamples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples()},transport:void 0,availability:void 0,source:Qne.openrpc()},audiences:l,inlinedTypes:t,servers:this.filterOutTopLevelServers(this.method.servers??[])}}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers.some(i=>i.url===r.url))}getEndpointBaseUrls(){let t=this.method.servers;return t?.map(i=>{if(this.topLevelServers.find(l=>l.name===i.name&&l.url!==i.url)!=null)return i.url;let u=this.topLevelServers.find(l=>l.url===i.url)??i;return LMe.getServerName({server:u,context:this.context})})}convertExamples(){let t={},r=0;if(this.method.examples&&this.method.examples.length>0){for(let i of this.method.examples??[]){let n;if(this.context.isReferenceObject(i)){let d=this.context.resolveReference({reference:i});if(d.resolved)n=d.value;else continue}else n=i;let a;if(n.result)if(this.context.isReferenceObject(n.result)){let d=this.context.resolveReference({reference:n.result});d.resolved&&(a=d.value)}else a=n.result;let u=n.name??`Example ${r+1}`,l=[];if(n.params&&Array.isArray(n.params)){l=[];for(let d of n.params)if(this.context.isReferenceObject(d)){let s=this.context.resolveReference({reference:d});if(s.resolved)l.push(s.value);else continue}else l.push(d)}t[u]={request:{docs:void 0,endpoint:{method:"POST",path:"/{apiKey}"},baseUrl:void 0,environment:void 0,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:l.map(d=>d.value)??void 0},response:{docs:void 0,statusCode:void 0,body:a?.value?Ws.V2HttpEndpointResponseBody.json({jsonrpc:"2.0",id:n.examplePairedRequest?.id||"1",result:a.value}):void 0},codeSamples:[]}}++r}return t}};var URa=class extends qpi{constructor({context:t,breadcrumbs:r,audiences:i}){super({context:t,breadcrumbs:r,audiences:i})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.convertSchemas();let{endpointLevelServers:t}=this.convertMethods(),{defaultUrl:r}=this.convertServers({endpointLevelServers:t});return this.updateEndpointsWithDefaultUrl(r),this.finalizeIr()}convertServers({endpointLevelServers:t}){let i=new LMe({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();return this.addEnvironmentsToIr({environmentConfig:i?.value}),{defaultUrl:i?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let n=new TM.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();n!=null&&(this.addTypeToPackage(t),this.addTypesToIr({...n.inlinedTypes,[t]:n.convertedSchema}))}}convertMethods(){let t=[],i=new Gko({context:this.context,breadcrumbs:["methods"],operation:this.context.spec}).convert(),n=[],a=[],u=[];if(i&&i.length>0)for(let[d,s]of i.entries()){let c=new $ko({context:this.context,breadcrumbs:[...this.breadcrumbs,`x-fern-parameters[${d}]`],parameter:s}).convert();if(c!=null)switch(c.type){case"path":{n.push(c.parameter);break}case"query":{a.push(c.parameter);break}case"header":{u.push(c.parameter);break}}}let l=this.context.getGroup({groupParts:[],namespace:this.context.namespace});for(let d of this.context.spec.methods??[]){let s=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:["methods"]});if(s==null)continue;let c=new Qko({context:this.context,breadcrumbs:["methods"],method:s,pathParameters:n,queryParameters:a,headers:u,topLevelServers:this.context.spec.servers}).convert();if(c!=null&&(this.addEndpointToIr({endpoint:c.endpoint,audiences:c.audiences,endpointGroup:l,serviceName:"service_root"}),this.addTypesToIr(c.inlinedTypes),c.servers))for(let b of c.servers)this.shouldAddServerToCollectedServers({server:b,currentServers:t,specType:"openrpc"})&&t.push(this.maybeDeduplicateServerName(b))}return{endpointLevelServers:t}}maybeDeduplicateServerName(t){return this.context.spec.servers?.find(i=>i.name===t.name&&i.url!==t.url)?{...t,name:t.url}:t}};var VRa=class extends f8{isReferenceObject(t){return t!=null&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n}){let a=this.getTypeIdFromSchemaReference(t);if(a==null)return{ok:!1};let u=this.resolveReference({reference:t,breadcrumbs:r});if(!u.resolved)return{ok:!1};let l;return n==="reference_identifier"?l=i??u.value.title:(n==="discriminator_key"||n==="schema_identifier")&&(l=u.value.title??i),{ok:!0,reference:hf.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(a),typeId:a,displayName:l,default:void 0,inline:!1})}}};var KB_={[hy.GenerationLanguage.PHP]:new Set(["abstract","and","as","break","callable","case","catch","class","clone","const","continue","declare","default","do","echo","else","elseif","enddeclare","endfor","endforeach","endif","endswitch","endwhile","extends","final","finally","fn","for","foreach","function","global","goto","list","if","implements","include","include_once","instanceof","insteadof","interface","match","namespace","new","or","parent","Parent","print","private","protected","public","readonly","require","require_once","return","static","switch","throw","trait","try","use","var","while","xor","yield"].flatMap(e=>[e,iz(e)])),[hy.GenerationLanguage.TYPESCRIPT]:new Set(["any","as","boolean","break","case","catch","class","const","constructor","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","let","module","new","null","number","of","package","private","protected","public","require","return","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","Date","Error","File","Object","Record"]),[hy.GenerationLanguage.JAVA]:new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","false","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","true","try","void","volatile","while"]),[hy.GenerationLanguage.PYTHON]:new Set(["False","None","True","and","as","assert","async","","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","float","int","complex","bool","uuid","list","set","map","long","self","all"]),[hy.GenerationLanguage.GO]:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[hy.GenerationLanguage.RUBY]:new Set(["__ENCODING__","__LINE__","__FILE__","alias","and","begin","break","case","class","def","defined","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield","Object","JSON","Date","DateTime"]),[hy.GenerationLanguage.CSHARP]:new Set(["abstract","as","base","bool","break","byte","case","catch","char","checked","class","const","continue","decimal","default","delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","goto","if","implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","operator","out","override","params","private","protected","public","readonly","ref","return","sbyte","sealed","short","sizeof","stackalloc","static","string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","ushort","using","virtual","void","volatile","while","add","and","alias","ascending","args","async","","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","managed","nameof","nint","not","notnull","nuint","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value","var","when","where","with","yield"]),[hy.GenerationLanguage.SWIFT]:new Set([])};var QJE=["go","ruby"];function cjc({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let u=c=>({unsafeName:c,safeName:JJE({name:c,keywords:KJE({generationLanguage:e,keywords:t})})}),l=T_(n),d=iz(l),s=qVi(n),o=DVi(l);return r&&(!ZJE(o)&&(e==null||QJE.includes(e))&&(l=o.map((c,b)=>{if(b>0){let g=Jko(c);if(g!=null)return g;if(Kko(c))return c.toUpperCase()}return c}).join(""),d=o.map((c,b)=>{let g=Jko(c);return g??(Kko(c)?c.toUpperCase():b===0?iz(c):c)}).join("")),s=n.split(" ").map(c=>c.split(/(\d+)/).map(qVi).join("")).join("_")),{originalName:n,camelCase:u(a?.casingOverrides?.camel??l),snakeCase:u(a?.casingOverrides?.snake??s),screamingSnakeCase:u(a?.casingOverrides?.["screaming-snake"]??s.toUpperCase()),pascalCase:u(a?.casingOverrides?.pascal??d)}},generateNameAndWireValue:({name:n,wireValue:a,opts:u})=>({name:i.generateName(n,u),wireValue:a})};return i}function JJE({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":XJE(e)?"_"+e:e}function KJE({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return KB_[e]}var YJE=/^[0-9]/;function XJE(e){return YJE.test(e)}function ZJE(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=Jko(i)!=null||Kko(i),a=Jko(t)!=null||Kko(t);return n&&a})}function Jko(e){return eKE.get(e.toUpperCase())}function Kko(e){return kJE.has(e.toUpperCase())}var kJE=new Set(["ACL","API","ASCII","CPU","CSS","DNS","EOF","GUID","HTML","HTTP","HTTPS","ID","IP","JSON","LHS","QPS","RAM","RHS","RPC","SAML","SCIM","SLA","SMTP","SQL","SSH","SSO","TCP","TLS","TTL","UDP","UI","UID","UUID","URI","URL","UTF8","VM","XML","XMPP","XSRF","XSS"]),eKE=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);var YB_=require("fs/promises");async function ljc({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let i=(await(0,YB_.readFile)(t)).toString(),n;try{n=JSON.parse(i)}catch{n=qd.load(i)}return r!=null?await n9n({absoluteFilePathToOverrides:r,context:e,data:n}):n}var SR=class extends ZIa{type="oss";allSpecs;specs;sources;loader;constructor({allSpecs:t,specs:r,...i}){super({...i,respectReadonlySchemas:r.every(n=>n.settings?.respectReadonlySchemas),respectNullableSchemas:r.every(n=>n.settings?.respectNullableSchemas),onlyIncludeReferencedSchemas:r.every(n=>n.settings?.onlyIncludeReferencedSchemas),inlinePathParameters:r.every(n=>n.settings?.inlinePathParameters),objectQueryParameters:r.every(n=>n.settings?.objectQueryParameters),useBytesForBinaryResponse:r.filter(n=>n.type==="openapi"&&n.source.type==="openapi").some(n=>n.settings?.useBytesForBinaryResponse),respectForwardCompatibleEnums:r.filter(n=>n.type==="openapi"&&n.source.type==="openapi").some(n=>n.settings?.respectForwardCompatibleEnums),exampleGeneration:r[0]?.settings?.exampleGeneration}),this.specs=r,this.allSpecs=t,this.sources=this.convertSpecsToIdentifiableSources(r),this.loader=new MHt(this.absoluteFilePath)}async getOpenAPIIr({context:t,relativePathToDependency:r},i){let n=await zFe({context:t,specs:this.specs,relativePathToDependency:r});return PJi({context:t,documents:await this.loader.loadDocuments({context:t,specs:n}),options:{...i,respectReadonlySchemas:i?.respectReadonlySchemas??this.respectReadonlySchemas,respectNullableSchemas:i?.respectNullableSchemas??this.respectNullableSchemas,onlyIncludeReferencedSchemas:i?.onlyIncludeReferencedSchemas??this.onlyIncludeReferencedSchemas,inlinePathParameters:i?.inlinePathParameters??this.inlinePathParameters,objectQueryParameters:i?.objectQueryParameters??this.objectQueryParameters,exampleGeneration:i?.exampleGeneration??this.exampleGeneration,useBytesForBinaryResponse:i?.useBytesForBinaryResponse??this.useBytesForBinaryResponse}})}async getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:i,generateV1Examples:n}){let a=await zFe({context:t,specs:this.specs}),u=await this.loader.loadDocuments({context:t,specs:a}),l=this.generatorsConfiguration?.api?.auth!=null?{...this.generatorsConfiguration?.api}:void 0;l&&t.logger.trace("Using auth overrides from generators configuration");let d=this.generatorsConfiguration?.api?.environments!=null?{...this.generatorsConfiguration?.api}:void 0;d&&t.logger.trace("Using environment overrides from generators configuration");let s=this.generatorsConfiguration?.api?.headers!=null?{...this.generatorsConfiguration?.api}:void 0;s&&t.logger.trace("Using global header overrides from generators configuration");let o,c=[];for(let b of u){let g=Vu(this.absoluteFilePath,Qa.of(b.source?.file??"")),O=lne(oR(),g),m=new x9n({logger:t.logger,relativeFilepathToSpec:O});c.push(m);let P;switch(b.type){case"openapi":{let q=new LRa({namespace:b.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:b.value,exampleGenerationArgs:{disabled:!1},errorCollector:m,authOverrides:l,environmentOverrides:d,globalHeaderOverrides:s,enableUniqueErrorsPerEndpoint:i,generateV1Examples:n,settings:aza({options:b.settings})});P=await new FRa({context:q,audiences:r}).convert();break}case"asyncapi":{let q=new NRa({namespace:b.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:b.value,exampleGenerationArgs:{disabled:!1},errorCollector:m,enableUniqueErrorsPerEndpoint:i,settings:aza({options:b.settings}),generateV1Examples:n});P=await new RRa({context:q,audiences:r}).convert();break}default:m.collect({message:`Unsupported document type: ${b}`,path:[]});break}let E=cjc({generationLanguage:"typescript",keywords:void 0,smartCasing:!1});P!=null&&(o=o===void 0?P:lko(o,P,E))}for(let b of this.allSpecs)if(b.type==="openrpc"){let g=b.absoluteFilepath,O=lne(oR(),g),m=new x9n({logger:t.logger,relativeFilepathToSpec:O});c.push(m);let P=new VRa({namespace:b.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:await ljc({context:t,absoluteFilePath:b.absoluteFilepath,absoluteFilePathToOverrides:b.absoluteFilepathToOverrides}),exampleGenerationArgs:{disabled:!1},errorCollector:m,enableUniqueErrorsPerEndpoint:i,generateV1Examples:n,settings:aza()}),q=await new URa({context:P,audiences:r}).convert(),M=cjc({generationLanguage:"typescript",keywords:void 0,smartCasing:!1});q!=null&&(o=o===void 0?q:lko(o,q,M))}for(let b of c)if(b.hasErrors()){let g=b.getErrorStats(),O=b.relativeFilepathToSpec?` for ${b.relativeFilepathToSpec}`:"";g.numErrors>0?t.logger.log("error",`API validation${O} completed with ${g.numErrors} errors and ${g.numWarnings} warnings.`):g.numWarnings>0?t.logger.log("warn",`API validation${O} completed with ${g.numWarnings} warnings.`):t.logger.log("info",`All checks passed when parsing OpenAPI${O}.`),t.logger.log("info",""),await b.logErrors({logWarnings:!1})}if(o===void 0)throw new Error("Failed to generate intermediate representation");return o}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new EMe({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:i,cliVersion:this.cliVersion,sources:this.sources})}getAbsoluteFilePaths(){return[this.absoluteFilePath,...this.specs.flatMap(t=>[t.type==="protobuf"?t.absoluteFilepathToProtobufTarget:t.absoluteFilepath,t.absoluteFilepathToOverrides]).filter(V0)]}getSources(){return this.sources}convertSpecsToIdentifiableSources(t){let r=new Set,i=[];return t.reduce((n,a)=>{let u=a.type==="protobuf"?a.absoluteFilepathToProtobufRoot:a.absoluteFilepath;return r.has(u)||(r.add(u),n.push({type:a.type,id:zae(),absoluteFilePath:u})),n},i)}};var XB_={None:"none",Header:"header"};var beu={};jo(beu,{ConjureAliasDeclaration:()=>reu,ConjureArgument:()=>heu,ConjureArgumentWithParamType:()=>_eu,ConjureAuthDefinition:()=>eLn,ConjureAuthDefinitionType:()=>deu,ConjureDefinitions:()=>leu,ConjureEndpointDefinition:()=>yeu,ConjureEnumDeclaration:()=>seu,ConjureEnumVariant:()=>ueu,ConjureEnumWithDocs:()=>oeu,ConjureObjectDeclaration:()=>aeu,ConjureParamType:()=>peu,ConjurePrimitive:()=>teu,ConjureService:()=>veu,ConjureServiceName:()=>eeu,ConjureType:()=>KAi,ConjureTypeDeclaration:()=>ceu,ConjureTypeReference:()=>YAi,ConjureTypeWithDocs:()=>ieu,ConjureTypes:()=>feu,ConjureUnionDeclaration:()=>neu,DefinitionFile:()=>SI_,WithDocs:()=>$ir,commons:()=>hjc,conjure:()=>yjc,services:()=>vjc,types:()=>bjc});var hjc={};jo(hjc,{WithDocs:()=>$ir});var ip={};jo(ip,{JsonError:()=>X9n,ParseError:()=>Z9n,any:()=>dI_,bigint:()=>kB_,boolean:()=>pI_,booleanLiteral:()=>fI_,date:()=>eI_,discriminant:()=>PI_,enum_:()=>Xko,getObjectLikeUtils:()=>THt,getObjectUtils:()=>DKi,getSchemaUtils:()=>Qq,isProperty:()=>JAi,lazy:()=>tI_,lazyObject:()=>sI_,list:()=>kko,number:()=>_I_,object:()=>Zko,objectWithoutOptionalProperties:()=>uI_,optional:()=>fjc,property:()=>iI_,record:()=>bI_,set:()=>gI_,string:()=>hI_,stringLiteral:()=>lI_,transform:()=>djc,undiscriminatedUnion:()=>mI_,union:()=>wI_,unknown:()=>yI_,withParsedProperties:()=>_jc});var qj={BIGINT:"bigint",DATE:"date",ENUM:"enum",LIST:"list",STRING_LITERAL:"stringLiteral",BOOLEAN_LITERAL:"booleanLiteral",OBJECT:"object",ANY:"any",BOOLEAN:"boolean",NUMBER:"number",STRING:"string",UNKNOWN:"unknown",RECORD:"record",SET:"set",UNION:"union",UNDISCRIMINATED_UNION:"undiscriminatedUnion",OPTIONAL:"optional"};function vA(e,t){return`Expected ${t}. Received ${tKE(e)}.`}function tKE(e){if(Array.isArray(e))return"list";if(e===null)return"null";if(e instanceof BigInt)return"BigInt";switch(typeof e){case"string":return`"${e}"`;case"bigint":case"number":case"boolean":case"undefined":return`${e}`}return typeof e}function _L(e){return{...e,json:ZB_(e.json),parse:ZB_(e.parse)}}function ZB_(e){return(t,r)=>{let i=e(t,r),{skipValidation:n=!1}=r??{};return!i.ok&&n?(console.warn(["Failed to validate.",...i.errors.map(a=>" - "+(a.path.length>0?`${a.path.join(".")}: ${a.message}`:a.message))].join(`
1960
+ `}async function zFe({context:e,specs:t,relativePathToDependency:r}){let i=new XXo({context:e}),n=t.filter(l=>l.type==="openapi").map(l=>({...l,relativePathToDependency:r})),a=t.filter(l=>l.type==="protobuf"),u=await Promise.all(a.map(async l=>NHE({generator:i,protobufSpec:l,relativePathToDependency:r})));return[...n,...u]}async function NHE({generator:e,protobufSpec:t,relativePathToDependency:r}){return{type:"openapi",absoluteFilepath:await e.generate({absoluteFilepathToProtobufRoot:t.absoluteFilepathToProtobufRoot,absoluteFilepathToProtobufTarget:t.absoluteFilepathToProtobufTarget,relativeFilepathToProtobufRoot:t.relativeFilepathToProtobufRoot,local:t.generateLocally}),absoluteFilepathToOverrides:t.absoluteFilepathToOverrides,settings:t.settings,source:{type:"protobuf",relativePathToDependency:r,root:t.absoluteFilepathToProtobufRoot,file:t.absoluteFilepathToProtobufTarget}}}var kC_=require("fs"),B9n=require("fs/promises");var eB_=require("os"),tB_=ci(require("path"),1),rB_=require("stream/promises"),iB_=ci(ako(),1),nB_=ci(dne(),1);var RPc=ci(e$i(),1);var xP;(function(e){e.FILE_READ="FILE_READ",e.FILE_PARSE="FILE_PARSE",e.FILE_MISSING="FILE_MISSING",e.STRUCTURE_VALIDATION="STRUCTURE_VALIDATION",e.JSONSCHEMA_VALIDATION="JSONSCHEMA_VALIDATION",e.DEPENDENCY_NOT_LISTED="DEPENDENCY_NOT_LISTED",e.FAILED_TO_LOAD_DEPENDENCY="FAILED_TO_LOAD_DEPENDENCY",e.EXPORTING_PACKAGE_MARKER_OTHER_KEYS="EXPORTING_PACKAGE_MARKER_OTHER_KEYS",e.EXPORT_PACKAGE_HAS_DEFINITIONS="EXPORT_PACKAGE_HAS_DEFINITIONS",e.MISCONFIGURED_DIRECTORY="MISCONFIGURED_DIRECTORY"})(xP||(xP={}));var _QE=Mfi();async function aB_({dependencyName:e,dependenciesConfiguration:t,context:r,rootApiFile:i,cliVersion:n,settings:a,loadAPIWorkspace:u}){let l,d={type:xP.FAILED_TO_LOAD_DEPENDENCY,dependencyName:e},s=t.dependencies[e];return s==null?d={type:xP.DEPENDENCY_NOT_LISTED,dependencyName:e}:await r.runInteractiveTask({name:`Download ${mQE(s)}`},async o=>{switch(s.type){case"version":l=await gQE({context:o,dependency:s,cliVersion:n,settings:a,loadAPIWorkspace:u});return;case"local":l=await bQE({context:o,dependency:s,cliVersion:n,settings:a,loadAPIWorkspace:u});return;default:mo(s)}}),l!=null?{didSucceed:!0,definition:l}:{didSucceed:!1,failure:d}}var oB_="dependencies";var hQE="metadata.json",yQE=".fern";function vQE(e){return Vu(hl.of((0,eB_.homedir)()),Qa.of(yQE),Qa.of(oB_),Qa.of(e.organization),Qa.of(e.apiName),Qa.of(e.version))}async function bQE({dependency:e,context:t,cliVersion:r,settings:i,loadAPIWorkspace:n}){if(n==null){t.failWithoutThrowing("Failed to load api definition");return}t.logger.info("Parsing...");let a=await n({absolutePathToWorkspace:e.absoluteFilepath,context:t,cliVersion:r,workspaceName:void 0});if(!a.didSucceed){t.failWithoutThrowing("Failed to load api definition",a.failures);return}t.logger.info("Modifying source filepath ...");let u=await a.workspace.getDefinition({context:t,relativePathToDependency:Qa.of(e.path)},i);return t.logger.info("Loaded..."),u}async function gQE({dependency:e,context:t,cliVersion:r,settings:i,loadAPIWorkspace:n}){let a=vQE(e),u=Vu(a,Qa.of(oB_)),l=Vu(a,Qa.of(hQE)),d;if(!await Sf(u)||!await Sf(l)){t.logger.info("Downloading manifest...");let c=await _QE.definitionRegistry.get(RPc.FernFiddle.OrganizationId(e.organization),RPc.FernFiddle.ApiId(e.apiName),e.version);if(!c.ok){c.error._visit({orgDoesNotExistError:()=>{t.failWithoutThrowing("Organization does not exist")},apiDoesNotExistError:()=>{t.failWithoutThrowing("API does not exist")},versionDoesNotExistError:()=>{t.failWithoutThrowing("Version does not exist")},_other:m=>{t.failWithoutThrowing("Failed to download API manifest",m)}});return}let b=c.body.yamlSchemaVersion!=null?parseInt(c.body.yamlSchemaVersion):void 0,g=sJi(r),O=sJi(c.body.cliVersion);if(b!=null){if(b>1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a higher version of fern. Upgrade this workspace to ${c.body.cliVersion}`);return}else if(b<1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a lower version of fern. Upgrade it to ${r}`);return}}else if(g.major!==O.major||g.minor!==O.minor){t.failWithoutThrowing(`CLI version is ${c.body.cliVersion}. Expected ${g.major}.${g.minor}.x (to match current workspace).`);return}t.logger.info("Downloading..."),t.logger.debug("Remote URL: "+c.body.definitionS3DownloadUrl),await(0,B9n.mkdir)(u,{recursive:!0});try{await OQE({s3PreSignedReadUrl:c.body.definitionS3DownloadUrl,absolutePathToLocalOutput:u})}catch(m){t.failWithoutThrowing("Failed to download API",m);return}d=c.body,await(0,B9n.writeFile)(l,JSON.stringify(d))}else d=JSON.parse((await(0,B9n.readFile)(l)).toString());if(t.logger.info("Parsing..."),n==null){t.failWithoutThrowing("Failed to load API");return}let s=await n({absolutePathToWorkspace:u,context:t,cliVersion:d.cliVersion,workspaceName:void 0});if(!s.didSucceed){t.failWithoutThrowing("Failed to parse dependency after downloading",s.failures);return}if(s.workspace.type==="oss"){t.failWithoutThrowing("Dependency must be a fern workspace.");return}return await s.workspace.getDefinition({context:t},i)}async function OQE({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}){let r=await rF.get(e,{responseType:"stream"}),i=await nB_.default.dir(),n=tB_.default.join(i.path,"api.tgz");await(0,rB_.pipeline)(r.data,(0,kC_.createWriteStream)(n)),await(0,iB_.extract)({file:n,cwd:t})}function mQE(e){switch(e.type){case"version":return`@${e.organization}/${e.apiName}`;case"local":return`${e.path}`;default:mo(e)}}var gB_=ci(dB_(),1);function oko(e,t){for(let[r,i]of r3(e))jQE({relativeFilepath:r,failure:i,logger:t})}function jQE({relativeFilepath:e,failure:t,logger:r}){switch(t.type){case xP.MISCONFIGURED_DIRECTORY:r.error("Misconfigured fern directory: please see the docs at https://buildwithfern.com/learn/api-definition/introduction/what-is-the-fern-folder");break;case xP.FILE_READ:r.error("Failed to open file: "+e);break;case xP.FILE_MISSING:r.error("Missing file: "+e);break;case xP.FILE_PARSE:t.error instanceof bSa?r.error(OFe({title:`Failed to parse ${e}: ${t.error.reason}`,subtitle:t.error.mark.snippet})):r.error("Failed to parse file: "+e);break;case xP.STRUCTURE_VALIDATION:for(let i of t.error.issues)for(let{title:n,subtitle:a}of wQE(i))r.error(OFe({title:n,subtitle:a,breadcrumbs:[e,...i.path]}));break;case xP.FAILED_TO_LOAD_DEPENDENCY:r.error("Failed to load dependency: "+t.dependencyName);break;case xP.DEPENDENCY_NOT_LISTED:r.error(`Dependency is not listed in ${GOo}: `+t.dependencyName);break;case xP.EXPORT_PACKAGE_HAS_DEFINITIONS:r.error("Exported package contains API definitions: "+t.pathToPackage);break;case xP.EXPORTING_PACKAGE_MARKER_OTHER_KEYS:r.error(`${t.pathOfPackageMarker} has an export so it cannot define other keys.`);break;case xP.JSONSCHEMA_VALIDATION:t.error.error!=null&&r.error(OFe({title:t.error.error.message??"Unknown error",breadcrumbs:[e,...t.error.error.instancePath.split("/").filter(i=>i!=="")]}));for(let i of t.error.allErrors)i!==t.error.error&&r.debug(OFe({title:i.message??"Unknown error",breadcrumbs:[e,...i.instancePath.split("/").filter(n=>n!=="")]}));break;default:mo(t)}}function wQE(e){switch(e.code){case Jl.invalid_type:return[{title:"Incorrect type",subtitle:`Expected ${Gs.underline(e.expected)} but received ${Gs.underline(e.received)}`}];case Jl.unrecognized_keys:return e.keys.map(t=>({title:"Unexpected key",subtitle:`Encountered unexpected key ${Gs.underline(t)}`}));case Jl.invalid_enum_value:return[{title:"Unrecognized value",subtitle:`Allowed values: ${e.options.map(t=>Gs.underline(t)).join(", ")}`}];case Jl.invalid_union:case Jl.invalid_arguments:case Jl.invalid_return_type:case Jl.invalid_date:case Jl.invalid_string:case Jl.too_small:case Jl.too_big:case Jl.invalid_intersection_types:case Jl.not_multiple_of:case Jl.custom:default:return[{title:e.message}]}}var pB_=require("fs/promises");async function _B_(e,t){let r=[];for(let i of await Vxe(e,t))r.push(await SQE({relativeFilepath:xq(e,i),absoluteFilepath:i}));return r}async function SQE({relativeFilepath:e,absoluteFilepath:t}){return{relativeFilepath:e,absoluteFilepath:t,fileContents:(await(0,pB_.readFile)(t)).toString()}}async function hB_(e){let t={},r={};function i(n){try{t[n.relativeFilepath]={defaultUrl:void 0,contents:qd.load(n.fileContents,{schema:qd.CORE_SCHEMA}),rawContents:n.fileContents}}catch(a){r[n.relativeFilepath]={type:xP.FILE_PARSE,error:a}}}return await Promise.all(e.map(i)),Object.keys(r).length>0?{didSucceed:!1,failures:r}:{didSucceed:!0,files:t}}async function yB_({dependenciesConfiguration:e,structuralValidationResult:t,context:r,cliVersion:i,settings:n,loadAPIWorkspace:a}){let u={},l={},d={};return await Promise.all(r3(t.packageMarkers).map(async([s,o])=>{if(o.contents.export==null)u[s]=o;else{let{export:c,...b}=o.contents;if(pZ(b)>0)d[s]={type:xP.EXPORTING_PACKAGE_MARKER_OTHER_KEYS,pathOfPackageMarker:s};else{let g=Ud(s);if(fVt(t.namedDefinitionFiles).some(m=>m!==s&&m.startsWith(g)))d[s]={type:xP.EXPORT_PACKAGE_HAS_DEFINITIONS,pathToPackage:g};else{let m=await aB_({dependencyName:typeof o.contents.export=="string"?o.contents.export:o.contents.export.dependency,dependenciesConfiguration:e,context:r,rootApiFile:t.rootApiFile.contents,cliVersion:i,settings:n,loadAPIWorkspace:a});m.didSucceed?l[Ud(s)]={definition:m.definition,url:typeof o.contents.export=="object"?o.contents.export.url:void 0}:d[s]=m.failure}}}})),pZ(d)>0?{didSucceed:!1,failures:d}:{didSucceed:!0,packageMarkers:u,importedDefinitions:l}}var vB_=ci(require("path"),1);var LPc={};jo(LPc,{additionalProperties:()=>AQE,default:()=>TQE,definitions:()=>qQE,properties:()=>EQE,required:()=>MQE,type:()=>DQE});var DQE="object",EQE={docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"default-url":{oneOf:[{type:"string"},{type:"null"}]},"default-environment":{oneOf:[{type:"string"},{type:"null"}]},environments:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/environments.EnvironmentSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/auth.ApiAuthSchema"},{type:"null"}]},"auth-schemes":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/auth.AuthSchemeDeclarationSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},name:{type:"string"},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},"error-discrimination":{oneOf:[{$ref:"#/definitions/file.ErrorDiscriminationSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},errors:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"idempotency-headers":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},variables:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/variables.VariableDeclarationSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"null"}]},product:{oneOf:[{$ref:"#/definitions/products.ProductDeclarationSchema"},{type:"null"}]},version:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},MQE=["name"],AQE=!1,qQE={"environments.SingleBaseUrlEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},url:{type:"string"}},required:["url"],additionalProperties:!1},"environments.MultipleBaseUrlsEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},urls:{type:"object",additionalProperties:{type:"string"}}},required:["urls"],additionalProperties:!1},"environments.EnvironmentSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/environments.SingleBaseUrlEnvironmentSchema"},{$ref:"#/definitions/environments.MultipleBaseUrlsEnvironmentSchema"}]},"auth.AuthSchemeReferenceSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{type:"string"}},required:["scheme"],additionalProperties:!1},"auth.AnyAuthItem":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"}]},"auth.AnyAuthSchemesSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},any:{type:"array",items:{$ref:"#/definitions/auth.AnyAuthItem"}}},required:["any"],additionalProperties:!1},"auth.ApiAuthSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"},{$ref:"#/definitions/auth.AnyAuthSchemesSchema"}]},"auth.OAuthAccessTokenRequestPropertiesSchema":{type:"object",properties:{"client-id":{oneOf:[{type:"string"},{type:"null"}]},"client-secret":{oneOf:[{type:"string"},{type:"null"}]},scopes:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthAccessTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthGetTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthRefreshTokenRequestPropertiesSchema":{type:"object",properties:{"refresh-token":{type:"string"}},required:["refresh-token"],additionalProperties:!1},"auth.OAuthRefreshTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthRefreshTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"oauth"},type:{const:"client-credentials"},scopes:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"client-id-env":{oneOf:[{type:"string"},{type:"null"}]},"client-secret-env":{oneOf:[{type:"string"},{type:"null"}]},"token-prefix":{oneOf:[{type:"string"},{type:"null"}]},"token-header":{oneOf:[{type:"string"},{type:"null"}]},"get-token":{$ref:"#/definitions/auth.OAuthGetTokenEndpointSchema"},"refresh-token":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenEndpointSchema"},{type:"null"}]}},required:["scheme","type","get-token"],additionalProperties:!1},"auth.HeaderAuthSchemeSchema":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},header:{type:"string"},type:{oneOf:[{type:"string"},{type:"null"}]},prefix:{oneOf:[{type:"string"},{type:"null"}]}},required:["header"],additionalProperties:!1},"auth.AuthVariable":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.BasicAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"basic"},username:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]},password:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.BearerAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"bearer"},token:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.AuthSchemeDeclarationSchema":{anyOf:[{$ref:"#/definitions/auth.OAuthSchemeSchema"},{$ref:"#/definitions/auth.HeaderAuthSchemeSchema"},{$ref:"#/definitions/auth.BasicAuthSchemeSchema"},{$ref:"#/definitions/auth.BearerAuthSchemeSchema"}]},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"file.PropertyBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"property"},"property-name":{type:"string"}},required:["strategy","property-name"],additionalProperties:!1},"file.StatusCodeBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"status-code"}},required:["strategy"],additionalProperties:!1},"file.ErrorDiscriminationSchema":{anyOf:[{$ref:"#/definitions/file.PropertyBasedErrorDiscrimination"},{$ref:"#/definitions/file.StatusCodeBasedErrorDiscrimination"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"variables.VariableDeclarationDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"variables.VariableDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/variables.VariableDeclarationDetailed"}]},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"versioning.VersionValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionValue":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionValueDetailed"}]},"versioning.VersionDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionDeclarationHeaderObjectSchema"}]},"versioning.VersionDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/versioning.VersionValue"}},header:{$ref:"#/definitions/versioning.VersionDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1},"products.ProductValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},versions:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"products.ProductValue":{anyOf:[{type:"string"},{$ref:"#/definitions/products.ProductValueDetailed"}]},"products.ProductDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"products.ProductDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/products.ProductDeclarationHeaderObjectSchema"}]},"products.ProductDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/products.ProductValue"}},header:{$ref:"#/definitions/products.ProductDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1}},TQE={type:DQE,properties:EQE,required:MQE,additionalProperties:AQE,definitions:qQE};var UPc={};jo(UPc,{additionalProperties:()=>IQE,default:()=>xQE,definitions:()=>zQE,properties:()=>BQE,type:()=>CQE});var CQE="object",BQE={docs:{oneOf:[{type:"string"},{type:"null"}]},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]}},IQE=!1,zQE={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{type:"boolean"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1}},xQE={type:CQE,properties:BQE,additionalProperties:IQE,definitions:zQE};var VPc={};jo(VPc,{additionalProperties:()=>FQE,default:()=>UQE,definitions:()=>LQE,properties:()=>NQE,type:()=>RQE});var RQE="object",NQE={imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},navigation:{oneOf:[{$ref:"#/definitions/file.Navigation"},{type:"null"}]},export:{oneOf:[{$ref:"#/definitions/file.Export"},{type:"null"}]}},FQE=!1,LQE={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{type:"boolean"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1},"file.Navigation":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"file.ExportDetailed":{type:"object",properties:{dependency:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]}},required:["dependency"],additionalProperties:!1},"file.Export":{anyOf:[{type:"string"},{$ref:"#/definitions/file.ExportDetailed"}]}},UQE={type:RQE,properties:NQE,additionalProperties:FQE,definitions:LQE};function bB_({files:e,absolutePathToDefinition:t}){let r,i={},n={},a={};for(let[u,l]of r3(e)){let d=l.contents,s=o=>{a[u]={type:xP.JSONSCHEMA_VALIDATION,error:o}};if(u===n3){let o=vVt(d,LPc);if(o.success){let c=JN.serialization.RootApiFileSchema.parseOrThrow(d);r={defaultUrl:c["default-url"],contents:c,rawContents:l.rawContents}}else s(o)}else if(vB_.default.basename(u)===zS){let o=vVt(d,VPc);if(o.success){let c=JN.serialization.PackageMarkerFileSchema.parseOrThrow(d);n[u]={defaultUrl:typeof c.export=="object"?c.export.url:void 0,contents:c,rawContents:l.rawContents}}else s(o)}else{let o=vVt(d,UPc);if(o.success){let c=JN.serialization.DefinitionFileSchema.parseOrThrow(d);i[u]={defaultUrl:void 0,contents:c,rawContents:l.rawContents,absoluteFilePath:Vu(t,u)}}else s(o)}}return r==null?{didSucceed:!1,failures:{[Qa.of(n3)]:{type:xP.FILE_MISSING},...a}}:Object.keys(a).length>0?{didSucceed:!1,failures:a}:{didSucceed:!0,namedDefinitionFiles:i,rootApiFile:r,packageMarkers:n}}var Vir=class extends fHt{type="fern";context;fernWorkspaces={};loadAPIWorkspace;constructor({context:t,loadAPIWorkspace:r,...i}){super(i),this.context=t,this.loadAPIWorkspace=r}async getDefinition({context:t},r){return(await this.toFernWorkspace({context:t},r)).definition}async toFernWorkspace({context:t},r){let i=(0,gB_.default)(r??{}),n=this.fernWorkspaces[i];if(n==null){let a=t||this.context,u=Vu(this.absoluteFilePath,Qa.of(v9)),l=await U2s({absolutePathToWorkspace:this.absoluteFilePath,context:a}),d=await _B_(u,"{yml,yaml}"),s=await hB_(d);if(!s.didSucceed)return oko(s.failures,a.logger),a.failAndThrow();let o=bB_({files:s.files,absolutePathToDefinition:u});if(!o.didSucceed)return oko(o.failures,a.logger),a.failAndThrow();let c=await yB_({dependenciesConfiguration:l,structuralValidationResult:o,context:a,cliVersion:this.cliVersion,settings:r,loadAPIWorkspace:this.loadAPIWorkspace});if(!c.didSucceed)return oko(c.failures,a.logger),a.failAndThrow();let b={absoluteFilePath:u,rootApiFile:o.rootApiFile,namedDefinitionFiles:o.namedDefinitionFiles,packageMarkers:c.packageMarkers,importedDefinitions:c.importedDefinitions};r?.auth!=null&&(b={...b,rootApiFile:{...b.rootApiFile,contents:{...b.rootApiFile.contents,auth:r?.auth}}}),n=new EMe({absoluteFilePath:this.absoluteFilePath,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:l,workspaceName:this.workspaceName,definition:b,cliVersion:this.cliVersion,sources:[]}),this.fernWorkspaces[i]=n}return n}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};var yb=class e{breadcrumbs=[];context;static STRING=Ws.TypeReference.primitive({v1:"STRING",v2:Ws.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Ws.TypeReference.container(Ws.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}};var OB_={[hy.GenerationLanguage.PHP]:new Set(["abstract","and","as","break","callable","case","catch","class","clone","const","continue","declare","default","do","echo","else","elseif","enddeclare","endfor","endforeach","endif","endswitch","endwhile","extends","final","finally","fn","for","foreach","function","global","goto","list","if","implements","include","include_once","instanceof","insteadof","interface","match","namespace","new","or","parent","Parent","print","private","protected","public","readonly","require","require_once","return","static","switch","throw","trait","try","use","var","while","xor","yield"].flatMap(e=>[e,iz(e)])),[hy.GenerationLanguage.TYPESCRIPT]:new Set(["any","as","boolean","break","case","catch","class","const","constructor","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","let","module","new","null","number","of","package","private","protected","public","require","return","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","Date","Error","File","Object","Record"]),[hy.GenerationLanguage.JAVA]:new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","false","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","true","try","void","volatile","while"]),[hy.GenerationLanguage.PYTHON]:new Set(["False","None","True","and","as","assert","async","","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","float","int","complex","bool","uuid","list","set","map","long","self","all"]),[hy.GenerationLanguage.GO]:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[hy.GenerationLanguage.RUBY]:new Set(["__ENCODING__","__LINE__","__FILE__","alias","and","begin","break","case","class","def","defined","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield","Object","JSON","Date","DateTime"]),[hy.GenerationLanguage.CSHARP]:new Set(["abstract","as","base","bool","break","byte","case","catch","char","checked","class","const","continue","decimal","default","delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","goto","if","implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","operator","out","override","params","private","protected","public","readonly","ref","return","sbyte","sealed","short","sizeof","stackalloc","static","string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","ushort","using","virtual","void","volatile","while","add","and","alias","ascending","args","async","","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","managed","nameof","nint","not","notnull","nuint","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value","var","when","where","with","yield"]),[hy.GenerationLanguage.SWIFT]:new Set([])};var VQE=["go","ruby"];function NMe({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let u=c=>({unsafeName:c,safeName:WQE({name:c,keywords:HQE({generationLanguage:e,keywords:t})})}),l=T_(n),d=iz(l),s=qVi(n),o=DVi(l);return r&&(!QQE(o)&&(e==null||VQE.includes(e))&&(l=o.map((c,b)=>{if(b>0){let g=uko(c);if(g!=null)return g;if(sko(c))return c.toUpperCase()}return c}).join(""),d=o.map((c,b)=>{let g=uko(c);return g??(sko(c)?c.toUpperCase():b===0?iz(c):c)}).join("")),s=n.split(" ").map(c=>c.split(/(\d+)/).map(qVi).join("")).join("_")),{originalName:n,camelCase:u(a?.casingOverrides?.camel??l),snakeCase:u(a?.casingOverrides?.snake??s),screamingSnakeCase:u(a?.casingOverrides?.["screaming-snake"]??s.toUpperCase()),pascalCase:u(a?.casingOverrides?.pascal??d)}},generateNameAndWireValue:({name:n,wireValue:a,opts:u})=>({name:i.generateName(n,u),wireValue:a})};return i}function WQE({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":GQE(e)?"_"+e:e}function HQE({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return OB_[e]}var $QE=/^[0-9]/;function GQE(e){return $QE.test(e)}function QQE(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=uko(i)!=null||sko(i),a=uko(t)!=null||sko(t);return n&&a})}function uko(e){return KQE.get(e.toUpperCase())}function sko(e){return JQE.has(e.toUpperCase())}var JQE=new Set(["ACL","API","ASCII","CPU","CSS","DNS","EOF","GUID","HTML","HTTP","HTTPS","ID","IP","JSON","LHS","QPS","RAM","RHS","RPC","SAML","SCIM","SLA","SMTP","SQL","SSH","SSO","TCP","TLS","TTL","UDP","UI","UID","UUID","URI","URL","UTF8","VM","XML","XMPP","XSRF","XSS"]),KQE=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);var PB_=require("fs/promises");var WPc=class{_map;_path;_lastScalar;_fragments;_count;constructor(){this._map={},this._path=[],this._lastScalar="",this._fragments=[],this._count=0}get map(){return this._map}resolveNode(t,r){if(t.path==="."&&(r="."),!this._map[r]){let{line:i,position:n,lineStart:a}=t;this._map[r]={line:i,position:n,lineStart:a}}t.children&&t.children.length>0&&t.children.forEach(i=>{this.resolveNode(i,(r==="."?"":r)+"."+i.path)})}iterFragments(t,r){for(let i=this._fragments.length-1;i>=0;i--){if(!this._fragments[i].path.startsWith(t)||this._fragments[i].path===t)continue;let n=this._fragments.pop();r(n)}}handleState(t,r){if(t==="close"){let i=r.result,n=r.kind,a=this._path.join(".");if(n==="scalar"){this._path.pop(),this._lastScalar=`${i}`;let{line:u,position:l,lineStart:d}=r;this._path.length===0?this._map["."+i]={line:u,position:l,lineStart:d}:this._fragments.push({path:this._path.join(".")+"."+i,line:u,position:l,lineStart:d})}else if(n==="mapping"){let u={path:a,children:[],line:0,position:0,lineStart:0},l=0;this.iterFragments(a,d=>{l++,!((!d.children||d.children.length===0)&&l%2===1)&&(this._path.length===1?this.resolveNode(d,d.path):(u.children.push({...d,path:d.path.slice(a.length+1)}),u.line=d.line,u.position=d.position,u.lineStart=d.lineStart))}),u.children&&u.children.length>0&&this._fragments.push(u),this._path.pop()}else if(n==="sequence"){let u={path:a,children:[],line:0,position:0,lineStart:0},l=new Set,d=i.length;this.iterFragments(a,s=>{l.has(s.position)||(d--,l.add(s.position),this._path.length===1?this.resolveNode(s,`${a}.${d}`):(u.children.push({...s,path:d.toString()}),u.line=s.line,u.position=s.position,u.lineStart=s.lineStart))}),u.children&&u.children.length>0&&this._fragments.push(u),this._path.pop()}else this._path.pop()}if(t==="open"){if(this._count===0){let{line:i,position:n,lineStart:a}=r;this._map["."]={line:i,position:n,lineStart:a}}this._path.push(this._lastScalar),this._count++}}listen(){return this.handleState.bind(this)}lookup(t){let r=t instanceof Array?t.map(n=>`${n}`).join("."):`${t}`;r.startsWith(".")||(r="."+r),r.startsWith("..")&&(r=r.slice(1)),r=r.replace(/\[/g,".").replace(/\]/g,"");let i=this._map[r];if(i)return{line:i.line+1,column:i.position-i.lineStart+1,position:i.position}}},mB_=WPc;var Api;(function(e){e.WARNING="warning",e.ERROR="error"})(Api||(Api={}));var x9n=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new HPc({logger:t,relativePathToFile:Qa.of(r)}))}collect(t){this.errors.push(t)}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}dedupe(){let t=[],r=new Set,i=0;for(let n of this.errors){let a=n.path?n.path.join("->"):"",u=`${n.message}|${n.level||Api.WARNING}|${a}`;r.has(u)?i++:(r.add(u),t.push(n))}return this.errors=t,i}getErrorStats(){this.dedupe();let t=0,r=0;for(let i of this.errors)i.level===Api.ERROR?t++:r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors)if(!(r.level===Api.WARNING&&!t))switch(r.level){case Api.ERROR:if(this.logger.log(M0.Error,r.message),r.path&&r.path.length>0){let i=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),n=i?`${this.relativeFilepathToSpec}:${i.line}:${i.column}`:r.path.join(" -> ");this.logger.log(M0.Error,` - at location (${n})`)}break}}},HPc=class{logger;relativePathToFile;map=new mB_;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,PB_.readFile)(this.relativePathToFile,"utf-8");qd.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(M0.Warn,`Failed to initialize line number mapping for ${this.relativePathToFile}: ${JSON.stringify(t)}`)}}async getSourceLocation(t){return this.initialized||await this.initialize(),this.map.lookup(t)}};var f8=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;authOverrides;environmentOverrides;globalHeaderOverrides;enableUniqueErrorsPerEndpoint;generateV1Examples;constructor(t){this.args=t,this.spec=t.spec,this.settings=t.settings,this.errorCollector=t.errorCollector,this.logger=t.logger,this.generationLanguage=t.generationLanguage,this.smartCasing=t.smartCasing,this.namespace=t.namespace,this.casingsGenerator=NMe({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs,this.authOverrides=t.authOverrides,this.environmentOverrides=t.environmentOverrides,this.globalHeaderOverrides=t.globalHeaderOverrides,this.enableUniqueErrorsPerEndpoint=t.enableUniqueErrorsPerEndpoint,this.generateV1Examples=t.generateV1Examples}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=t.filter((n,a)=>!(/^\d+$/.test(n)||e.BREADCRUMBS_TO_IGNORE.includes(n)||a===0&&n==="components"||a===1&&n==="schemas"||t[0]==="paths"&&(a===0||a===1&&["get","post","put","delete","patch"].includes(n)||a===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&n==="parameters"))),i=T_(r.join("_"));return i.charAt(0).toUpperCase()+i.slice(1)}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],i=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:i?[...r,i]:r,packagePath:r,file:i}}resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:i}){let n=this.spec,a=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(u=>u.replace(/~1/g,"/"));for(let u of a){if(typeof n!="object"||n==null)return i||this.errorCollector.collect({level:Api.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};n=n[u]}return n==null?(i||this.errorCollector.collect({level:Api.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1}):{resolved:!0,value:n}}getErrorMessageForMissingRef({reference:t}){let r=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/");return r.length>=3&&r[0]==="components"&&r[1]==="schemas"?`Schema ${r[2]} does not exist`:`${t.$ref} does not exist`}async resolveMaybeExternalReference(t){let r=this.spec,i,n=!1,a=null,u;if(this.isExternalReference(t.$ref)){n=!0;let s=t.$ref.split("#"),o=s[0];if(i=s[1],!o)return{resolved:!1};u=o;let c=await fetch(o);if(!c.ok)return{resolved:!1};try{let b=await c.text();try{a=JSON.parse(b),r=a}catch{a=qd.load(b),r=a}if(r==null)return{resolved:!1}}catch{return{resolved:!1}}if(!i)return{resolved:!0,value:r}}let l=i??t.$ref;if(l==null||typeof l!="string")return{resolved:!1};let d=l.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(s=>s.replace(/~1/g,"/"));for(let s of d){if(typeof r!="object"||r==null)return{resolved:!1};r=r[s]}if(r==null)return{resolved:!1};if(n&&typeof r=="object"&&r!==null){let s=new Set;s.add(t.$ref),r=await this.resolveNestedExternalReferences(r,a,s,u)}return{resolved:!0,value:r}}async resolveNestedExternalReferences(t,r,i,n){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let u=[];for(let l of t)u.push(await this.resolveNestedExternalReferences(l,r,i,n));return u}if(this.isReferenceObject(t)){let u=t.$ref;if(this.isExternalReference(u)){if(i.has(u))return t;i.add(u);let l=await this.resolveMaybeExternalReference({$ref:u});if(i.delete(u),l.resolved)return l.value}else{let l=`${n}${u}`;if(i.has(l))return t;i.add(l);let d=r,s=u.substring(2).split("/").map(o=>o.replace(/~1/g,"/").replace(/~0/g,"~"));for(let o of s){if(typeof d!="object"||d===null)return t;d=d[o]}if(d!=null){let o=await this.resolveNestedExternalReferences(d,r,i,n);return i.delete(u),o}i.delete(u)}return t}let a={};for(let[u,l]of Object.entries(t))typeof l=="object"&&l!==null?a[u]=await this.resolveNestedExternalReferences(l,r,i,n):a[u]=l;return a}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let i=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?i.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),i}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:i}){if(t==null)return[];let n=[];if(t.example!=null){let a=this.generateUniqueName({prefix:i??`${r.join("_")}_example`,existingNames:[]});n.push([a,t.example])}return t.examples!=null&&n.push(...Object.entries(t.examples)),n}resolveMaybeReference({schemaOrReference:t,breadcrumbs:r,skipErrorCollector:i}){if(this.isReferenceObject(t)){let n=this.resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:i});return n.resolved?n.value:void 0}return t}resolveExample(t){if(!this.isReferenceObject(t))return t;let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}resolveExampleWithValue(t){if(!this.isReferenceObject(t))return this.returnExampleValue(t);let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}returnExampleValue(t){return this.isExampleWithValue(t)?t.value:t}getPropertyAccess(t){let r=t;for(;this.isReferenceObject(r);){let i=this.resolveReference({reference:r});if(!i.resolved)return;r=i.value}if(!(r.readOnly&&r.writeOnly)){if(r.readOnly)return Lkt.ReadOnly;if(r.writeOnly)return Lkt.WriteOnly}}getAudiences({operation:t,breadcrumbs:r}){let n=new pH.AudienceExtension({operation:t,breadcrumbs:r,context:this}).convert();if(n!=null)return n.audiences}getAvailability({node:t,breadcrumbs:r}){for(;this.isReferenceObject(t);){let a=this.resolveReference({reference:t});if(!a.resolved)return;t=a.value}let n=new pH.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(n!=null)return{status:n,message:void 0};if(t.deprecated===!0)return{status:B9.Deprecated,message:void 0}}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return hf.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t),typeId:t,displayName:r,default:void 0,inline:!1})}typeReferenceToDeclaredTypeName(t){if(t.type!=="named")return;let r=t.typeId;return{typeId:r,fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(r),displayName:t.displayName}}removeSchemaFromInlinedTypes({id:t,inlinedTypes:r}){return Object.fromEntries(Object.entries(r).filter(([i])=>i!==t))}static maybeTrimPrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}generateUniqueName({prefix:t,existingNames:r}){if(!r.includes(t))return t;let i=0;for(;r.includes(`${t}_${i}`);)i++;return`${t}_${i}`}isReferenceObject(t){return typeof t=="object"&&t!==null&&"$ref"in t}isExternalReference(t){return typeof t=="string"&&(t.startsWith("http://")||t.startsWith("https://"))}isReferenceObjectWithIdentifier(t){return this.isReferenceObject(t)&&("title"in t||"name"in t||"messageId"in t)}isExampleWithSummary(t){return typeof t=="object"&&t!=null&&"summary"in t}isExampleWithValue(t){return typeof t=="object"&&t!=null&&"value"in t}isOptional(t){return t.type==="container"&&t.container.type==="optional"}isNullable(t){return t.type==="container"&&t.container.type==="nullable"}isList(t){return t.type==="container"&&t.container.type==="list"}isFile(t){return t.type==="primitive"&&t.primitive.v2?.type==="string"&&t.primitive.v2.validation?.format==="binary"}getAsString(t){if(typeof t=="string")return t}getAsInteger(t){if(typeof t=="number"&&Number.isInteger(t))return t}getAsNumber(t){if(typeof t=="number")return t}getAsBoolean(t){if(typeof t=="boolean")return t}getAsArray(t){if(Array.isArray(t))return t}getAsObject(t){if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}getGroup({groupParts:t,namespace:r}){let i=[];return r!=null&&i.push(r),i.push(...t??[]),i}isObjectSchemaType(t){return t.type==="object"||t.properties!=null}};var Pm=class{breadcrumbs;context;constructor(t){this.breadcrumbs=t.breadcrumbs,this.context=t.context}getExtensionValue(t,r){if(typeof t!="object"||t==null)return;let i=t[this.key];if(i!=null)return i;if(r!=null)return t[r]}};function fF(e){let t=XQE(e),{value:r,done:i}=$Pc(t,"{");return i?{head:r,parts:[]}:{head:r,parts:[...YQE(t)]}}function*YQE(e){let t;do{let{value:r}=$Pc(e,"}"),i=$Pc(e,"{");t=i.done,yield{pathParameter:r,tail:i.value}}while(!t)}function*XQE(e){for(let t of e)yield t}function $Pc(e,t){let r="",i=e.next();for(;i.done!==!0&&i.value!==t;)r+=i.value,i=e.next();return{value:r,done:i.done??!1}}function ARa(e){let t=2166136261;function r(n,a){if(typeof n=="object"&&n!=null){if(a>64){i("[MaxDepthExceeded]");return}if(Array.isArray(n)){i("[");for(let u=0;u<n.length;u++)u>0&&i(","),r(n[u],a+1);i("]")}else i("{"),Object.keys(n).sort().forEach((l,d)=>{d>0&&i(","),i(l),i(":"),r(n[l],a+1)}),i("}")}else i(String(n))}function i(n){for(let a=0;a<n.length;a++){let u=n.charCodeAt(a);t^=u,t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24),t>>>=0}}return r(e,0),t.toString(16)}function Wir({typeReference:e,typeDeclarations:t}){if(e.type==="container"&&e.container.type==="optional")return!0;if(e.type==="named"){let r=t?.[e.typeId];if(r?.shape.type==="alias"&&r?.shape.resolvedType.type==="container"&&r?.shape.resolvedType.container.type==="optional")return!0}return!1}function jB_({fieldName:e,containerType:t,maxDepth:r,currentDepth:i,typeDeclarations:n,skipOptionalProperties:a}){if(i>=r)return Hir({containerType:t});switch(t.type){case"list":{let u=Gq({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?Hir({containerType:t}):{type:"success",example:bm.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:bm.literal({literal:t.literal._visit({boolean:u=>Rd.boolean(u),string:u=>Rd.string({original:u}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:t.literal._visit({boolean:u=>u,string:u=>u,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":{if(a)return Hir({containerType:t});let u=Gq({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?Hir({containerType:t}):{type:"success",example:bm.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"nullable":{if(a)return Hir({containerType:t});let u=Gq({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?Hir({containerType:t}):{type:"success",example:bm.nullable({nullable:u.example,valueType:t.nullable}),jsonExample:u.jsonExample}}case"set":{let u=Gq({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?Hir({containerType:t}):{type:"success",example:bm.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=Gq({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a}),l=Gq({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"||l.type==="failure"?Hir({containerType:t}):{type:"success",example:bm.map({map:[{key:u.example,value:l.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:l.jsonExample}}}default:mo(t)}}function Hir({containerType:e}){switch(e.type){case"list":return{type:"success",example:bm.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:bm.literal({literal:e.literal._visit({boolean:t=>Rd.boolean(t),string:t=>Rd.string({original:t}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:e.literal._visit({boolean:t=>t,string:t=>t,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":return{type:"success",example:bm.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:bm.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:bm.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:bm.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:mo(e)}}function SB_({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return rJE({fieldName:e,default_:ZQE(t.v2),validation:kQE(t.v2)});case"BASE_64":return{type:"success",example:Rd.base64(Gy.BASE64),jsonExample:Gy.BASE64};case"BOOLEAN":return{type:"success",example:Rd.boolean(Gy.BOOLEAN),jsonExample:Gy.BOOLEAN};case"DATE":return{type:"success",example:Rd.date(Gy.DATE),jsonExample:Gy.DATE};case"DATE_TIME":return{type:"success",example:Rd.datetime({datetime:new Date(Gy.DATE_TIME),raw:Gy.DATE_TIME}),jsonExample:Gy.DATE_TIME};case"DOUBLE":return iJE({fieldName:e,validation:eJE(t.v2)});case"FLOAT":return{type:"success",example:Rd.float(Gy.FLOAT),jsonExample:Gy.FLOAT};case"INTEGER":return nJE({fieldName:e,validation:tJE(t.v2)});case"UINT_64":return{type:"success",example:Rd.uint64(Gy.INT64),jsonExample:Gy.INT64};case"UINT":return{type:"success",example:Rd.uint(Gy.UINT),jsonExample:Gy.UINT};case"BIG_INTEGER":return{type:"success",example:Rd.bigInteger(Gy.INT64.toString()),jsonExample:`${Gy.INT64}`};case"LONG":return{type:"success",example:Rd.long(Gy.INT64),jsonExample:Gy.INT64};case"UUID":return{type:"success",example:Rd.uuid(Gy.UUID),jsonExample:Gy.UUID};default:mo(t.v1)}}function ZQE(e){if(e?.type==="string")return e.default}function kQE(e){if(e?.type==="string")return e.validation}function eJE(e){if(e?.type==="double")return e.validation}function tJE(e){if(e?.type==="integer")return e.validation}function wB_(e){if(e<=Gy.SAMPLE_STRINGS.length){let t=Gy.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return Gy.SAMPLE_STRINGS[Gy.SAMPLE_STRINGS.length-1]+".".repeat(e-Gy.SAMPLE_STRINGS.length)}function rJE({fieldName:e,default_:t,validation:r}){if(t!=null)return{type:"success",example:Rd.string({original:t}),jsonExample:t};if(r){let n=r.minLength,a=r.maxLength;if(n){let u=wB_(n);return{type:"success",example:Rd.string({original:u}),jsonExample:u}}else if(a){let u=wB_(a);return{type:"success",example:Rd.string({original:u}),jsonExample:u}}}let i=e??Gy.STRING;return{type:"success",example:Rd.string({original:i}),jsonExample:i}}function iJE({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Rd.double(r),jsonExample:r};if(i)return{type:"success",example:Rd.double(i),jsonExample:i}}return{type:"success",example:Rd.double(Gy.DOUBLE),jsonExample:Gy.DOUBLE}}function nJE({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Rd.integer(r),jsonExample:r};if(i)return{type:"success",example:Rd.integer(i),jsonExample:i}}return{type:"success",example:Rd.integer(Gy.INT),jsonExample:Gy.INT}}function R9n({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=Gq({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:l,jsonExample:d}=u;return{type:"success",example:Iw.alias({value:l}),jsonExample:d}}case"enum":{let u=r.shape.values[0];return u==null?{type:"failure",message:"No enum values present"}:{type:"success",example:Iw.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u={},l=[];if((r.shape.extendedProperties==null||r.shape.extendedProperties.length===0)&&r.shape.extends!=null)for(let c of r.shape.extends){let b=t[c.typeId];if(b==null)continue;let g=R9n({fieldName:e,typeDeclaration:b,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});g!=null&&g.type==="success"&&g.example.type==="object"&&(Object.assign(u,g.jsonExample),l.push(...g.example.properties))}let d=aJE({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:n,maxDepth:i,skipOptionalProperties:a});if(d.type==="failure")return d;let{example:s,jsonExample:o}=d;return{type:"success",example:Iw.object({properties:[...l,...s.properties]}),jsonExample:Object.assign({},u,o)}}case"undiscriminatedUnion":{let u=0;for(let l of r.shape.members){let d=Gq({fieldName:e,typeReference:l.type,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});if(d.type==="failure"){++u;continue}let{example:s,jsonExample:o}=d;return{type:"success",example:Iw.undiscriminatedUnion({index:u,singleUnionType:s}),jsonExample:o}}break}case"union":{let u=r.shape.discriminant,l={};if(r.shape.baseProperties!=null)for(let d of r.shape.baseProperties){let s=Gq({fieldName:d.name.wireValue,typeReference:d.valueType,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});s.type==="success"&&(l[d.name.wireValue]=s.jsonExample)}for(let d of r.shape.types){let s=d.shape._visit({noProperties:()=>({type:"success",example:Iw.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:y3.noProperties()}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,...l}}),samePropertiesAsObject:o=>{let c=t[o.typeId];if(c==null)return{type:"failure",message:`Failed to find type declaration with id ${o.typeId}`};let b=R9n({currentDepth:n,maxDepth:i,fieldName:e,typeDeclaration:c,typeDeclarations:t,skipOptionalProperties:a});if(b==null)return{type:"failure",message:"Failed to generate example for type reference"};if(b.type==="failure")return b;let{example:g,jsonExample:O}=b;return{type:"success",example:Iw.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:y3.samePropertiesAsObject({typeId:c.name.typeId,object:g.type==="object"?g:{properties:[]}})}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,...typeof O=="object"?O:{},...l}}},singleProperty:o=>{let c=Gq({currentDepth:n+1,maxDepth:i,fieldName:e,typeReference:o.type,typeDeclarations:t,skipOptionalProperties:a});if(c.type==="failure")return c;let{example:b,jsonExample:g}=c;return{type:"success",example:Iw.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:y3.singleProperty(b)}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,[o.name.wireValue]:g,...l}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(s.type!=="failure")return s}}}return{type:"failure",message:"Failed to generate example for type reference"}}function aJE({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:i,maxDepth:n,currentDepth:a,skipOptionalProperties:u}){let l={},d=[];for(let s of[...r.properties??[],...r.extendedProperties??[]]){let o=Gq({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:i,currentDepth:a+1,maxDepth:n,skipOptionalProperties:u});if(o.type==="failure"&&!Wir({typeDeclarations:i,typeReference:s.valueType}))return{type:"failure",message:`Failed to generate required property ${s.name.wireValue} b/c ${o.message}`};if(o.type==="failure")continue;let{example:c,jsonExample:b}=o;d.push({name:s.name,originalTypeDeclaration:t.name,value:c}),l[s.name.wireValue]=b}return{type:"success",example:Iw.object({properties:d}),jsonExample:l}}function Gq({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){if(n>i)return{type:"failure",message:"Exceeded max depth"};switch(t.type){case"named":{let u=r[t.typeId];if(u==null)return{type:"failure",message:`Failed to find type declaration with id ${t.typeId}`};let l=R9n({fieldName:e,typeDeclaration:u,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(l==null)return{type:"failure",message:"Failed to generate example for type declaration"};if(l.type==="failure")return l;let{example:d,jsonExample:s}=l;return{type:"success",example:{jsonExample:s,shape:Nh.named({shape:d,typeName:u.name})},jsonExample:s}}case"container":{let u=jB_({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure"){let{example:s,jsonExample:o}=Hir({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:Nh.container(s)},jsonExample:o}}let{example:l,jsonExample:d}=u;return{type:"success",example:{jsonExample:d,shape:Nh.container(l)},jsonExample:d}}case"primitive":{let{jsonExample:u,example:l}=SB_({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:Nh.primitive(l)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:Nh.unknown(u)},jsonExample:u}}}}function PKi(e,t){let r=[];for(let i of e){let n=Gq({fieldName:i.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,value:n.example})}return{type:"success",example:r,jsonExample:void 0}}function N9n(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&Wir({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=Gq({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,value:n.example})}return{type:"success",example:r,jsonExample:void 0}}function cko(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&Wir({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=Gq({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??10,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,shape:i.allowMultiple?$2.exploded():$2.single(),value:n.example})}return{type:"success",example:r,jsonExample:void 0}}var GPc=hf.primitive({v1:hb.String,v2:Dp.string({default:void 0,validation:void 0})});function qRa({ir:e,endpoint:t,service:r,typeDeclarations:i,skipOptionalRequestProperties:n,generationResponse:a}){let u={name:void 0,endpointHeaders:[],endpointPathParameters:[],queryParameters:[],servicePathParameters:[],serviceHeaders:[],rootPathParameters:[],request:void 0,response:RT.ok(kC.body(void 0)),docs:void 0},l=PKi(t.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(l.type==="failure")return l;u.endpointPathParameters=l.example;let d=PKi(r.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(d.type==="failure")return d;u.servicePathParameters=d.example;let s=PKi(e.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(s.type==="failure")return s;u.rootPathParameters=s.example;let o=cko(t.queryParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:10});if(o.type==="failure")return o;u.queryParameters=o.example;let c=N9n(t.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(c.type==="failure")return c;u.endpointHeaders=c.example;let b=N9n(r.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(b.type==="failure")return b;if(u.serviceHeaders=b.example,t.requestBody!=null)switch(t.requestBody.type){case"bytes":return{type:"failure",message:"Bytes request unsupported"};case"fileUpload":return{type:"failure",message:"File upload unsupported"};case"inlinedRequestBody":{let g={},O=[];if(t.requestBody.extends!=null)for(let m of t.requestBody.extends){let P=i[m.typeId];if(P==null)throw new Error(`Failed to find extended type declaration with id ${m.typeId}`);let E=R9n({typeDeclaration:P,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});E!=null&&E.type==="success"&&Object.assign(g,E.jsonExample)}for(let m of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let P=Gq({fieldName:m.name.wireValue,typeReference:m.valueType,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});if(P.type==="failure"&&!Wir({typeDeclarations:i,typeReference:m.valueType}))return{type:"failure",message:`Failed to generate required property ${m.name.wireValue} b/c ${P.message}`};if(P.type==="failure")continue;let{example:E,jsonExample:q}=P;O.push({name:m.name,originalTypeDeclaration:void 0,value:E}),g[m.name.wireValue]=q}u.request=xQ.inlinedRequestBody({jsonExample:g,properties:O});break}case"reference":{let g=Gq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.request=xQ.reference(O);break}default:mo(t.requestBody)}if(a.type==="success"&&t.response?.body!=null)switch(t.response.body.type){case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":{let g=Gq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RT.ok(kC.body({...O,jsonExample:m}));break}case"streamParameter":{let g;switch(t.response.body.nonStreamResponse.type){case"bytes":return{type:"failure",message:"Bytes unsupported"};case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":g=Gq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":g=Gq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:GPc,skipOptionalProperties:!1});break;default:mo(t.response.body.nonStreamResponse)}if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RT.ok(kC.body({...O,jsonExample:m}));break}case"streaming":{let g;switch(t.response.body.value.type){case"sse":{if(g=Gq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RT.ok(kC.sse([{data:{...O,jsonExample:m},event:""}]));break}case"json":{if(g=Gq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RT.ok(kC.stream([{...O,jsonExample:m}]));break}case"text":{if(g=Gq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:GPc,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RT.ok(kC.stream([{...O,jsonExample:m}]));break}default:mo(t.response.body.value)}break}case"text":{let g=Gq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:GPc,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RT.ok(kC.body({...O,jsonExample:m}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:mo(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=RT.error({body:void 0,error:a.declaration.name});else{let g=Gq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:a.declaration.type,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.response=RT.error({body:O,error:a.declaration.name})}try{return{type:"success",example:{id:ARa(u),url:oJE(t,u),...u},jsonExample:void 0}}catch(g){return{type:"failure",message:`Parse failure with exceptions ${g}`}}}function oJE(e,t){let r={};[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.fullPath.head+e.fullPath.parts.map(n=>encodeURIComponent(`${r[n.pathParameter]}`)+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function QPc({ir:e,channel:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let n={name:void 0,pathParameters:[],headers:[],queryParameters:[],messages:[],docs:void 0},a=PKi(t.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(a.type==="failure")return a;n.pathParameters.push(...a.example);let u=PKi(e.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(u.type==="failure")return u;n.pathParameters.push(...u.example);let l=cko(t.queryParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:10});if(l.type==="failure")return l;n.queryParameters=l.example;let d=N9n(t.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(d.type==="failure")return d;n.headers.push(...d.example);let s=N9n(e.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(s.type==="failure")return s;n.headers.push(...s.example);let c=t.messages.filter(O=>O.origin==="client")[0];if(c!=null){let O=DB_({message:c,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:c.type,body:O})}let g=t.messages.filter(O=>O.origin==="server")[0];if(g!=null){let O=DB_({message:g,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:g.type,body:O})}return{type:"success",example:{...n,url:uJE(t,n)},jsonExample:void 0}}function DB_({message:e,typeDeclarations:t,skipOptionalRequestProperties:r}){if(e.body.type==="inlinedBody")return;let i=Gq({currentDepth:0,maxDepth:10,typeDeclarations:t,typeReference:e.body.bodyType,skipOptionalProperties:r});if(i.type==="success")return KEe.reference(i.example)}function uJE(e,t){let r={};[...t.pathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.path.head+e.path.parts.map(n=>encodeURIComponent(`${r[n.pathParameter]}`)+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function F9n(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{},i=Object.values(t)[0],n=Object.values(r)[0];return{userExample:i,autoExample:n}}function WAi(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{};return{userExamples:t,autoExamples:r}}function EB_({ir:e,endpoint:t,skipOptionalRequestProperties:r}){let i=e.types,n={pathParameters:{},queryParameters:{},headers:{}};for(let u of t.pathParameters){let{userExample:l,autoExample:d}=F9n(u.v2Examples);l!==void 0?n.pathParameters[u.name.originalName]=l:d!==void 0&&(n.pathParameters[u.name.originalName]=d)}for(let u of t.queryParameters){let{userExample:l,autoExample:d}=F9n(u.v2Examples);if(l!==void 0)n.queryParameters[u.name.name.originalName]=l;else if(d!==void 0){if(r&&Wir({typeReference:u.valueType,typeDeclarations:i}))continue;n.queryParameters[u.name.name.originalName]=d}}let a=[...t.headers,...e.headers,...e.idempotencyHeaders];for(let u of a){let{userExample:l,autoExample:d}=F9n(u.v2Examples);if(l!==void 0)n.headers[u.name.name.originalName]=l;else if(d!==void 0){if(r&&Wir({typeReference:u.valueType,typeDeclarations:i}))continue;n.headers[u.name.name.originalName]=d}}return n}function MB_({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let{pathParameters:i,queryParameters:n,headers:a}=EB_({endpoint:e,ir:t,skipOptionalRequestProperties:r}),u={},l={},d={endpoint:{method:e.method,path:sJE(e)},baseUrl:void 0,environment:e.baseUrl,auth:void 0,pathParameters:i,queryParameters:n,headers:a,requestBody:void 0,docs:void 0};if(e.requestBody!=null)switch(e.requestBody.type){case"bytes":break;case"fileUpload":{let{userExamples:s,autoExamples:o}=WAi(e.requestBody.v2Examples);for(let[c,b]of Object.entries(s))u[c]={...d,requestBody:b};for(let[c,b]of Object.entries(o))l[c]={...d,requestBody:b};break}case"inlinedRequestBody":{let{userExamples:s,autoExamples:o}=WAi(e.requestBody.v2Examples);for(let[c,b]of Object.entries(s))u[c]={...d,requestBody:b};for(let[c,b]of Object.entries(o))l[c]={...d,requestBody:b};break}case"reference":{let{userExamples:s,autoExamples:o}=WAi(e.requestBody.v2Examples);for(let[c,b]of Object.entries(s))u[c]={...d,requestBody:b};for(let[c,b]of Object.entries(o))l[c]={...d,requestBody:b};break}default:mo(e.requestBody)}return{userRequestExamples:u,autoRequestExamples:l,baseExample:d}}function sJE(e){let t={};[...e.pathParameters,...e.allPathParameters].forEach(i=>{let{userExample:n,autoExample:a}=F9n(i.v2Examples),u=n??a,l;u==null?l=i.name.originalName:l=typeof u=="string"?u:JSON.stringify(u),t[i.name.originalName]=l});let r=e.fullPath.head+e.fullPath.parts.map(i=>encodeURIComponent(`${t[i.pathParameter]}`)+i.tail).join("");return r.startsWith("/")||r===""?r:`/${r}`}function AB_({endpoint:e}){let t={},r={},i={statusCode:e.response?.statusCode,body:void 0,docs:void 0};if(e.response==null)return{userResponseExamples:{},autoResponseExamples:{},baseExample:i};if(e.response.body==null)return e.source?.type==="openrpc"?{userResponseExamples:{},autoResponseExamples:{},baseExample:{...i,body:I9.json(TRa(null))}}:{userResponseExamples:{},autoResponseExamples:{},baseExample:i};switch(e.response.body.type){case"bytes":break;case"fileDownload":break;case"text":{let n=e.response.body,{userExamples:a,autoExamples:u}=WAi(n.v2Examples);for(let[l,d]of Object.entries(a)){let s=e.source?.type==="openrpc"?TRa(d):d;t[l]={...i,body:I9.json(s)}}for(let[l,d]of Object.entries(u)){let s=e.source?.type==="openrpc"?TRa(d):d;r[l]={...i,body:I9.json(s)}}break}case"json":{let n=e.response.body.value;if(n.type==="response"){let{userExamples:a,autoExamples:u}=WAi(n.v2Examples);for(let[l,d]of Object.entries(a)){let s=e.source?.type==="openrpc"?TRa(d):d;t[l]={...i,body:I9.json(s)}}for(let[l,d]of Object.entries(u)){let s=e.source?.type==="openrpc"?TRa(d):d;r[l]={...i,body:I9.json(s)}}}break}case"streaming":{let n=e.response.body.value;if(n.type==="json"){let{userExamples:a,autoExamples:u}=WAi(n.v2Examples);for(let[l,d]of Object.entries(a))t[l]={...i,body:I9.stream([d])};for(let[l,d]of Object.entries(u))r[l]={...i,body:I9.stream([d])}}break}case"streamParameter":break;default:mo(e.response.body)}return{userResponseExamples:t,autoResponseExamples:r,baseExample:i}}function TRa(e,t=1){return{id:t,jsonrpc:"2.0",result:e}}function qB_({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let i={},n={},{userRequestExamples:a,autoRequestExamples:u,baseExample:l}=MB_({endpoint:e,ir:t,skipOptionalRequestProperties:r}),{userResponseExamples:d,autoResponseExamples:s,baseExample:o}=AB_({endpoint:e}),c=Object.keys(u)[0],b=Object.values(u)[0],g=Object.values(s)[0];for(let[O,m]of Object.entries(a))i[O]={request:m,response:d[O]??g??o,codeSamples:void 0};for(let[O,m]of Object.entries(d))i[O]={request:a[O]??b??l,response:m,codeSamples:void 0};return Object.keys(i).length===0&&(n[c??T_(`${e.name.originalName}_example`)]={request:b??l,response:g??o,codeSamples:void 0}),{userFullExamples:i,autoFullExamples:n}}function CRa({ir:e,exampleGeneration:t}){for(let[r,i]of Object.entries(e.services))for(let n of i.endpoints){if(n.userSpecifiedExamples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let a=qRa({ir:e,service:i,endpoint:n,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples,generationResponse:{type:"success"}});if(a.type==="failure")continue;let{example:u}=a;n.autogeneratedExamples=[{example:u}]}for(let[r,i]of Object.entries(e.websocketChannels??{})){if(i.examples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let n=QPc({ir:e,channel:i,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});if(n.type==="failure")continue;let{example:a}=n;i.examples=[...i.examples,a]}return e}function JPc({ir:e,exampleGeneration:t}){for(let[r,i]of Object.entries(e.services))for(let n of i.endpoints){n.v2Examples==null&&(n.v2Examples={userSpecifiedExamples:{},autogeneratedExamples:{}});let{userFullExamples:a,autoFullExamples:u}=qB_({endpoint:n,ir:e,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});if(Object.keys(n.v2Examples.userSpecifiedExamples).length>0){if(Object.values(n.v2Examples.userSpecifiedExamples).some(d=>d.request!=null||d.response!=null))continue;let l=Object.values(n.v2Examples.userSpecifiedExamples).filter(d=>d!=null).flatMap(d=>d.codeSamples??[]);for(let[d,s]of Object.entries(u))u[d]={...s,codeSamples:l};for(let[d,s]of Object.entries(a))a[d]={...s,codeSamples:l}}n.v2Examples.autogeneratedExamples=u,n.v2Examples.userSpecifiedExamples=a}for(let[r,i]of Object.entries(e.websocketChannels??{})){if(i.examples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let n=QPc({ir:e,channel:i,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});if(n.type==="failure")continue;let{example:a}=n;i.examples=[...i.examples,a]}return e}function lko(e,t,r){let{environments:i,changedBaseUrlIds1:n,changedBaseUrlIds2:a}=lJE(e.environments,t.environments,r),{services:u,websocketChannels:l}=fJE(e,t,n,a);return{apiName:e.apiName,basePath:e.basePath,selfHosted:e.selfHosted&&t.selfHosted,apiDisplayName:e.apiDisplayName??t.apiDisplayName,apiDocs:e.apiDocs??t.apiDocs,auth:{requirement:e.auth?.requirement??t.auth?.requirement,schemes:t.auth?.schemes?.length!=null&&t.auth.schemes.length>(e.auth?.schemes?.length??0)?t.auth.schemes:e.auth?.schemes??[],docs:e.auth?.docs??t.auth?.docs},headers:[...e.headers??[],...t.headers??[]],environments:i,types:{...e.types??{},...t.types??{}},constants:{...e.constants??{},...t.constants??{}},errors:{...e.errors??{},...t.errors??{}},services:u,webhookGroups:{...e.webhookGroups??{},...t.webhookGroups??{}},subpackages:cJE(e.subpackages,t.subpackages),websocketChannels:l,rootPackage:{service:e.rootPackage.service??t.rootPackage.service,types:[...e.rootPackage.types??[],...t.rootPackage.types??[]],errors:[...e.rootPackage.errors??[],...t.rootPackage.errors??[]],subpackages:[...e.rootPackage.subpackages??[],...(t.rootPackage.subpackages??[]).filter(d=>!e.rootPackage.subpackages?.includes(d))],fernFilepath:e.rootPackage.fernFilepath??t.rootPackage.fernFilepath,webhooks:e.rootPackage.webhooks??t.rootPackage.webhooks,websocket:e.rootPackage.websocket??t.rootPackage.websocket,hasEndpointsInTree:e.rootPackage.hasEndpointsInTree||t.rootPackage.hasEndpointsInTree,navigationConfig:e.rootPackage.navigationConfig??t.rootPackage.navigationConfig,docs:e.rootPackage.docs??t.rootPackage.docs},fdrApiDefinitionId:e.fdrApiDefinitionId??t.fdrApiDefinitionId,apiVersion:e.apiVersion??t.apiVersion,idempotencyHeaders:[...e.idempotencyHeaders??[],...t.idempotencyHeaders??[]],pathParameters:[...e.pathParameters??[],...t.pathParameters??[]],errorDiscriminationStrategy:e.errorDiscriminationStrategy??t.errorDiscriminationStrategy,variables:[...e.variables??[],...t.variables??[]],serviceTypeReferenceInfo:e.serviceTypeReferenceInfo??t.serviceTypeReferenceInfo,readmeConfig:e.readmeConfig??t.readmeConfig,sourceConfig:e.sourceConfig??t.sourceConfig,publishConfig:e.publishConfig??t.publishConfig,dynamic:e.dynamic??t.dynamic,sdkConfig:e.sdkConfig??t.sdkConfig}}function cJE(e,t){let r=e;for(let[i,n]of Object.entries(t))r[i]==null?r[i]=n:r[i]={name:n.name,fernFilepath:n.fernFilepath,hasEndpointsInTree:r[i].hasEndpointsInTree||n.hasEndpointsInTree,navigationConfig:r[i].navigationConfig??n.navigationConfig,docs:r[i].docs??n.docs,service:r[i].service??n.service,subpackages:[...r[i].subpackages??[],...(n.subpackages??[]).filter(a=>!r[i]?.subpackages?.includes(a))],webhooks:r[i].webhooks??n.webhooks,websocket:r[i].websocket??n.websocket,errors:[...r[i].errors??[],...n.errors??[]],types:[...r[i].types??[],...n.types??[]]};return r}function lJE(e,t,r){if(e==null&&t==null)return{environments:void 0,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(t==null)return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(e==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(JSON.stringify(e)===JSON.stringify(t))return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let i=TB_(e),n=TB_(t);if(i&&n&&e.environments.type==="singleBaseUrl"&&t.environments.type==="singleBaseUrl")return{environments:{defaultEnvironment:e.defaultEnvironment??t.defaultEnvironment,environments:cx.singleBaseUrl({environments:[...e.environments.environments,...t.environments.environments]})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let a=i?t.defaultEnvironment:e.defaultEnvironment,u=e.environments,l=t.environments;if(u.type==="singleBaseUrl"&&l.type==="singleBaseUrl"){let d=i?l:u,s=i?u:l,o={},{deconflictedEnvironments2:c,changedBaseUrlIds2:b}=dJE(d,s,r);if(d.environments[0]==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let g="Base",O=r.generateName("Base");return d.environments.forEach(m=>{o[m.id]=g}),{environments:{defaultEnvironment:a,environments:cx.multipleBaseUrls({baseUrls:[{id:g,name:O},...c.environments.map(m=>({id:m.id,name:m.name}))],environments:d.environments.map(m=>({id:m.id,name:m.name,urls:{[g]:m.url,...Object.fromEntries(c.environments.map(P=>[P.id,P.url]))},docs:void 0}))})},changedBaseUrlIds1:i?b:o,changedBaseUrlIds2:i?o:b}}if(u.type==="multipleBaseUrls"&&l.type==="singleBaseUrl"||u.type==="singleBaseUrl"&&l.type==="multipleBaseUrls"){let d=u.type==="singleBaseUrl"?u:l,s=u.type==="multipleBaseUrls"?u:l,{deconflictedEnvironments1:o,changedBaseUrlIds1:c}=pJE(d,s,r);return{environments:{defaultEnvironment:a,environments:cx.multipleBaseUrls({baseUrls:[...s.baseUrls,...o.environments.map(b=>({id:b.id,name:b.name}))],environments:s.environments.map(b=>({...b,urls:{...b.urls,...Object.fromEntries(o.environments.map(g=>[g.id,g.url]))}}))})},changedBaseUrlIds1:u.type==="singleBaseUrl"?c:void 0,changedBaseUrlIds2:u.type==="singleBaseUrl"?void 0:c}}if(u.type==="multipleBaseUrls"&&l.type==="multipleBaseUrls"){let{deconflictedEnvironments:d,changedBaseUrlIds:s}=_JE(u,l,r);return{environments:{defaultEnvironment:a,environments:cx.multipleBaseUrls({baseUrls:[...u.baseUrls,...d.baseUrls],environments:u.environments.flatMap(o=>d.environments.map(c=>({...o,urls:{...o.urls,...c.urls}})))})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:s}}return{environments:e??t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0}}function fJE(e,t,r,i){if(r!=null)for(let[u,l]of Object.entries(r)){for(let d of Object.values(e.services))for(let s of Object.values(d.endpoints))s.baseUrl==u&&(s.baseUrl=l),s.v2BaseUrls?.includes(u)&&(s.v2BaseUrls=s.v2BaseUrls.map(o=>o===u?l:o));for(let d of Object.values(e.websocketChannels??{}))d.baseUrl==u&&(d.baseUrl=l)}if(i!=null)for(let[u,l]of Object.entries(i)){for(let d of Object.values(t.services))for(let s of Object.values(d.endpoints))s.baseUrl==u&&(s.baseUrl=l),s.v2BaseUrls?.includes(u)&&(s.v2BaseUrls=s.v2BaseUrls.map(o=>o===u?l:o));for(let d of Object.values(t.websocketChannels??{}))d.baseUrl==u&&(d.baseUrl=l)}let n=e.services;for(let[u,l]of Object.entries(t.services))n[u]==null?n[u]=l:n[u]={availability:l.availability,name:l.name,displayName:l.displayName,basePath:l.basePath,endpoints:[...n[u].endpoints??[],...l.endpoints],pathParameters:[...n[u].pathParameters??[],...l.pathParameters??[]],headers:[...n[u].headers??[],...l.headers??[]],encoding:l.encoding,transport:l.transport};let a={...e.websocketChannels??{},...t.websocketChannels??{}};return{services:n,websocketChannels:a}}function dJE(e,t,r){let i={},n=new Set(e.environments.map(s=>s.id)),a=new Set(e.environments.map(s=>s.name)),u=new Map(e.environments.map(s=>[s.url,s.id])),l=t.environments.filter(s=>{let o=u.get(s.url);return o!=null?(i[s.id]=o,!1):!0}).map(s=>{if(n.has(s.id)||a.has(s.name)){let o=KPc(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s});return{deconflictedEnvironments2:cx.singleBaseUrl({environments:l}),changedBaseUrlIds2:i}}function pJE(e,t,r){let i={},n=new Set(t.baseUrls.map(d=>d.id)),a=new Set(t.baseUrls.map(d=>d.name)),u=e.environments.map(d=>{if(n.has(d.id)||a.has(d.name)){let s=KPc(d.id,n);return i[d.id]=s,{...d,id:s,name:r.generateName(s)}}return d});return{deconflictedEnvironments1:cx.singleBaseUrl({environments:u}),changedBaseUrlIds1:i}}function _JE(e,t,r){let i={},n=new Set(e.baseUrls.map(s=>s.id)),a=new Set(e.baseUrls.map(s=>s.name)),u=t.baseUrls.map(s=>{if(n.has(s.id)||a.has(s.name)){let o=KPc(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s}),l=t.environments.map(s=>({...s,urls:Object.fromEntries(Object.entries(s.urls).map(([o,c])=>[i[o]??o,c]))}));return{deconflictedEnvironments:cx.multipleBaseUrls({baseUrls:u,environments:l}),changedBaseUrlIds:i}}function TB_(e){return e.environments.type==="singleBaseUrl"?e.environments.environments.some(t=>t.url&&(t.url.startsWith("ws://")||t.url.startsWith("wss://"))):e.environments.type==="multipleBaseUrls"?e.environments.environments.some(t=>Object.values(t.urls).some(r=>r&&(r.startsWith("ws://")||r.startsWith("wss://")))):!1}function KPc(e,t){let r=e,i=1;for(;t.has(r);)r=`${e}-${i}`,i++;return r}function XPc({rawApiFileSchema:e,casingsGenerator:t}){if(e.auth==null)return{docs:void 0,requirement:yRe.All,schemes:[]};let r=typeof e.auth!="string"?e.auth.docs:void 0;return BHi(e.auth,{single:i=>{let n=CB_({reference:i,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t});return{docs:r,requirement:yRe.All,schemes:[n]}},any:({any:i})=>({docs:r,requirement:yRe.Any,schemes:i.map(n=>CB_({reference:n,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t}))})})}function CB_({reference:e,authSchemeDeclarations:t,casingsGenerator:r}){let i=(a,u)=>{let l=t?.[a];if(l==null)throw new Error("Unknown auth scheme: "+a);return IDa(l,{header:d=>CB.header({docs:u,name:r.generateNameAndWireValue({name:d.name??a,wireValue:d.header}),valueType:hf.primitive({v1:hb.String,v2:Dp.string({default:void 0,validation:void 0})}),prefix:d.prefix,headerEnvVar:d.env}),basic:d=>BB_({casingsGenerator:r,docs:u,rawScheme:d}),bearer:d=>YPc({casingsGenerator:r,docs:u,rawScheme:d}),oauth:d=>YPc({casingsGenerator:r,docs:u,rawScheme:void 0})})},n=typeof e=="string"?e:e.scheme;switch(n){case"bearer":case"oauth":return YPc({casingsGenerator:r,docs:void 0,rawScheme:void 0});case"basic":return BB_({casingsGenerator:r,docs:void 0,rawScheme:void 0});default:return i(n,typeof e!="string"?e.docs:void 0)}}function YPc({casingsGenerator:e,docs:t,rawScheme:r}){return CB.bearer({docs:t,token:e.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function BB_({casingsGenerator:e,docs:t,rawScheme:r}){return CB.basic({docs:t,username:e.generateName(r?.username?.name??"username"),usernameEnvVar:r?.username?.env,password:e.generateName(r?.password?.name??"password"),passwordEnvVar:r?.password?.env})}function BRa({rawApiFileSchema:{"default-environment":e,environments:t},casingsGenerator:r}){if(t==null)return;let i=Object.values(t)[0];if(i!=null)return{environmentsConfig:{defaultEnvironment:e??void 0,environments:Jkt(i,{singleBaseUrl:()=>cx.singleBaseUrl(hJE({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>cx.multipleBaseUrls(yJE({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})},audiences:{...Object.fromEntries(Object.entries(t).map(([n,a])=>[n,Jkt(a,{singleBaseUrl:u=>[...typeof u=="string"?[]:u.audiences??[]],multipleBaseUrls:u=>[...u.audiences??[]]})]))}}}function hJE({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>Jkt(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:IB_(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function yJE({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>Jkt(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:dd(a.urls,u=>IB_(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function IB_(e){return e.endsWith("/")?e.slice(0,-1):e}function FMe(e){return e.allParts.map(t=>t.originalName).join("/")}var jm={generateTypeId:e=>`type_${FMe(e.fernFilepath)}:${e.name.originalName}`,generateErrorId:e=>`error_${FMe(e.fernFilepath)}:${e.name.originalName}`,generateServiceId:e=>`service_${FMe(e.fernFilepath)}`,generateServiceIdFromFernFilepath:e=>`service_${FMe(e)}`,generateSubpackageId:e=>`subpackage_${FMe(e)}`,generateEndpointId:(e,t)=>{let r=FMe(e.fernFilepath),i=t.name.originalName;return`endpoint_${r}.${i}`},generateWebhookGroupId:e=>`webhooks_${FMe(e)}`,generateWebhookId:(e,t)=>`webhooks_${FMe(e)}.${t}`,generateWebSocketChannelId:e=>`channel_${FMe(e)}`};function L9n(e){return e.type!=null}var fko=class{environments=new Set;types=new Set;properties;errors=new Set;services=new Set;endpoints=new Set;requestProperties;queryParameters;webhooks=new Set;webhookPayloadProperties;channels=new Set;subpackages=new Set;constructor({types:t,properties:r,errors:i,environments:n,services:a,endpoints:u,webhooks:l,subpackages:d,queryParameters:s,requestProperties:o,webhookPayloadProperties:c,channels:b}){this.environments=n,this.types=t,this.properties=r,this.errors=i,this.services=a,this.endpoints=u,this.webhooks=l,this.webhookPayloadProperties=c,this.subpackages=d,this.requestProperties=o,this.queryParameters=s,this.channels=b}hasTypeId(t){return this.types.has(t)}hasErrorId(t){return this.errors.has(t)}hasServiceId(t){return this.services.has(t)}hasSubpackageId(t){return this.subpackages.has(t)}hasType(t){let r=jm.generateTypeId(t.name);return this.types.has(r)}hasProperty(t,r){let i=this.properties[t];return i==null?!0:i.has(r)}hasError(t){let r=jm.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=jm.generateServiceId(t.name);return this.services.has(r)}hasEnvironmentId(t){return this.environments.has(t)}hasEndpoint(t){return this.endpoints.has(t.id)}hasRequestProperty(t,r){let i=this.requestProperties[t];return i==null?!0:i.has(r)}hasQueryParameter(t,r){let i=this.queryParameters[t];return i==null?!0:i.has(r)}hasSubpackage(t){return this.subpackages.has(t)}hasWebhook(t){return t.id?this.webhooks.has(t.id):!0}hasChannel(t){return t?this.channels.has(t):!0}hasWebhookPayloadProperty(t,r){let i=this.webhookPayloadProperties[t];return i==null?!0:i.has(r)}};function jKi(e){let t={};for(let[r,i]of Object.entries(e))if(typeof i!="string")for(let n of i.audiences??[])t[n]==null&&(t[n]=new Set),t[n]?.add(r);return t}var wKi=class{types={};properties={};queryParameters={};requestProperties={};webhookProperties={};errors={};endpoints={};webhooks={};channels={};audiences;typesReferencedByService={};environmentsNeededForAudience=new Set;typesNeededForAudience=new Set;servicesNeededForAudience=new Set;endpointsNeededForAudience=new Set;webhooksNeededForAudience=new Set;channelsNeededForAudience=new Set;subpackagesNeededForAudience=new Set;constructor(t){this.audiences=vJE(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let u=jm.generateTypeId(t),l={typeId:u,allDescendants:r,descendantsByAudience:n,referencedSubpackages:i};this.types[u]=l,this.typesReferencedByService[u]==null&&(this.typesReferencedByService[u]=new Set),this.properties[u]={typeId:u,propertiesByAudience:a}}markTypeForAudiences(t,r){let i=jm.generateTypeId(t);this.hasAudience(r)&&(this.typesNeededForAudience.add(i),this.addSubpackages(t.fernFilepath),this.types[i]?.referencedSubpackages.forEach(n=>{this.addSubpackages(n)}))}markEnvironmentForAudiences(t,r,i){t&&(this.hasAudience(r)||i)&&this.environmentsNeededForAudience.add(t.id)}getTypesReferencedByService(){for(let t of Object.values(this.endpoints))for(let r of t.referencedTypes)this.markTypeForService(r,t.serviceId);return this.typesReferencedByService}addError(t){let r=jm.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&Px(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=jm.generateServiceId(t.name),a=r.id,u=new Set,l=new Set,d=new Set;for(let s of[...t.headers,...r.headers])Px(s.valueType,u,d);for(let s of[...t.pathParameters,...r.pathParameters])Px(s.valueType,u,d);for(let s of r.queryParameters)Px(s.valueType,u,d);if(i!=null&&i.request!=null&&typeof i.request!="string"){let s=jKi(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:s}}r.requestBody!=null&&pC._visit(r.requestBody,{inlinedRequestBody:s=>{for(let o of s.extends)dko(o,u,d);for(let o of s.properties)Px(o.valueType,u,d);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&ZC(i.request.body)){let o=jKi(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:s})=>{Px(s,u,d)},fileUpload:({properties:s})=>{for(let o of s)z9._visit(o,{file:Go,bodyProperty:({valueType:c})=>{Px(c,u,d)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+o.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&NS._visit(r.response.body,{fileDownload:Go,json:s=>{Px(s.responseBodyType,u,d)},streaming:s=>{s._visit({sse:o=>Px(o.payload,u,d),json:o=>Px(o.payload,u,d),text:Go,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.type)}})},streamParameter:s=>{s.streamResponse._visit({sse:o=>Px(o.payload,u,d),json:o=>Px(o.payload,u,d),text:Go,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.streamResponse.type)}}),s.nonStreamResponse.type==="json"&&Px(s.nonStreamResponse.value.responseBodyType,u,d)},text:Go,bytes:Go,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(s=>{l.add(jm.generateErrorId(s.error)),d.add(s.error.fernFilepath)}),this.endpoints[a]={endpointId:a,serviceId:n,referencedTypes:u,referencedErrors:l,referencedSubpackages:d}}markEndpointForAudience(t,r,i){if(this.hasAudience(i)){let n=jm.generateServiceId(t);this.servicesNeededForAudience.add(n),r.forEach(a=>{let u=a.id;this.endpointsNeededForAudience.add(u),this.endpoints[u]?.referencedSubpackages.forEach(l=>{this.addSubpackages(l)})}),this.servicesNeededForAudience.add(n),this.addSubpackages(t.fernFilepath)}}getFilteredSubpackages(){return this.subpackagesNeededForAudience}getFilteredServices(){return this.servicesNeededForAudience}getFilteredEndpoints(){return this.endpointsNeededForAudience}getFilteredChannels(){return this.channelsNeededForAudience}getFilteredWebhooks(){return this.webhooksNeededForAudience}addWebhook(t,r,i){let n=r.id;if(n==null)return;let a=new Set,u=new Set;r.payload!=null&&EW._visit(r.payload,{inlinedPayload:l=>{for(let d of l.extends)dko(d,a,u);for(let d of l.properties)Px(d.valueType,a,u);if(i?.payload!=null&&typeof i.payload=="object"&&!L9n(i.payload)){let d=jKi(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:d}}},reference:({payloadType:l})=>{Px(l,a,u)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),u.add(t),this.webhooks[n]={webhookId:n,referencedTypes:a,referencedSubpackages:u}}markWebhookForAudiences(t,r,i){let n=r.id;n!=null&&this.hasAudience(i)&&(this.webhooksNeededForAudience.add(n),this.addSubpackages(t))}addChannel(t,r,i,n){if(r==null)return;let a=new Set,u=new Set;for(let l of i.messages)N9._visit(l.body,{reference:({bodyType:d})=>{Px(d,a,u)},inlinedBody:d=>{for(let s of d.extends)dko(s,a,u);for(let s of d.properties)Px(s.valueType,a,u)},_other:()=>{}});for(let l of i.queryParameters)Px(l.valueType,a,u);u.add(t),this.channels[r]={channelId:r,referencedTypes:a,referencedSubpackages:u}}markChannelForAudiences(t,r,i){r!=null&&this.hasAudience(i)&&(this.channelsNeededForAudience.add(r),this.addSubpackages(t))}build(){let t=new Set,r=new Set;for(let l of this.endpointsNeededForAudience.keys()){let d=this.getEndpointNode(l);for(let s of d.referencedErrors){if(r.has(s))continue;r.add(s);let o=this.getErrorNode(s);this.addReferencedTypes(t,o.referencedTypes)}this.addReferencedTypes(t,d.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let l of this.webhooksNeededForAudience.keys()){let d=this.getWebhookNode(l);this.addReferencedTypes(t,d.referencedTypes)}for(let l of this.channelsNeededForAudience.keys()){let d=this.getChannelNode(l);this.addReferencedTypes(t,d.referencedTypes)}let i={},n={},a={},u={};if(this.audiences.type==="filtered"){for(let[l,d]of Object.entries(this.properties)){if(!t.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}s.size>0&&(i[l]=s),i[l]=s.size>0?s:void 0}for(let[l,d]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}n[l]=s.size>0?s:void 0}for(let[l,d]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.parametersByAudience[o];c?.forEach(b=>{s.add(b)})}a[l]=s.size>0?s:void 0}for(let[l,d]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}u[l]=s.size>0?s:void 0}}return new fko({types:t,properties:i,errors:r,requestProperties:n,queryParameters:a,environments:this.environmentsNeededForAudience,services:this.servicesNeededForAudience,endpoints:this.endpointsNeededForAudience,webhooks:this.webhooksNeededForAudience,webhookPayloadProperties:u,subpackages:this.subpackagesNeededForAudience,channels:this.channelsNeededForAudience})}markTypeForService(t,r){let i=this.typesReferencedByService[t]??=new Set;if(i.has(r))return;i.add(r);let n=this.getTypeNode(t);for(let a of n.allDescendants)this.markTypeForService(a,r)}addReferencedTypes(t,r){for(let i of r){if(t.has(i))continue;t.add(i);let n=this.getTypeNode(i);if(this.audiences.type==="filtered")for(let a of this.audiences.audiences){let u=n.descendantsByAudience[a];if(u!=null)u.forEach(l=>{t.add(l)});else{n.allDescendants.forEach(l=>{t.add(l)});break}}else n.allDescendants.forEach(a=>{t.add(a)})}}getTypeNode(t){let r=this.types[t];if(r==null)throw new Error(`Failed to find type node with id ${t}`);return r}getErrorNode(t){let r=this.errors[t];if(r==null)throw new Error(`Failed to find error node with id ${t}`);return r}getEndpointNode(t){let r=this.endpoints[t];if(r==null)throw new Error(`Failed to find endpoint node with id ${t}`);return r}getWebhookNode(t){let r=this.webhooks[t];if(r==null)throw new Error(`Failed to find webhook node with id ${t}`);return r}getChannelNode(t){let r=this.channels[t];if(r==null)throw new Error(`Failed to find channel node with id ${t}`);return r}hasNoAudiences(){return this.audiences.type==="none"}hasAudience(t){let r=this.audiences;switch(r.type){case"none":return!0;case"filtered":return t.some(i=>r.audiences.has(i));default:mo(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(jm.generateSubpackageId(i))}}};function vJE(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:mo(e)}}function Px(e,t,r){hf._visit(e,{container:i=>{bJE(i,t,r)},named:i=>{dko(i,t,r)},primitive:Go,unknown:Go,_other:Go})}function dko(e,t,r){t.add(jm.generateTypeId(e)),r.add(e.fernFilepath)}function bJE(e,t,r){_b._visit(e,{list:i=>{Px(i,t,r)},map:i=>{Px(i.keyType,t,r),Px(i.valueType,t,r)},optional:i=>{Px(i,t,r)},nullable:i=>{Px(i,t,r)},set:i=>{Px(i,t,r)},literal:Go,_other:Go})}var ZPc=class{errors;constructor(){this.errors=[]}add(t){this.errors.push({message:t})}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}},IRa=class{errors;constructor(){this.errors=new ZPc}async check({from:t,to:r}){let i=this.checkBreaking({from:t,to:r});return{bump:i.isBreaking?"major":"minor",isBreaking:i.isBreaking,errors:i.errors}}checkBreaking({from:t,to:r}){this.checkTypeBreakingChanges({from:t.types,to:r.types}),this.checkErrorsBreakingChanges({from:t.errors,to:r.errors}),this.checkServicesBreakingChanges({from:t.services,to:r.services});let i=this.errors.hasErrors();return{bump:i?"major":"minor",isBreaking:i,errors:this.errors.getErrors()}}checkTypeBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){let a=r[i];if(!a){this.errors.add(`Type "${i}" was removed.`);continue}this.areTypeDeclarationsCompatible({from:n,to:a})||this.errors.add(`Type "${i}" has an incompatible change.`)}}checkErrorsBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){let a=Object.values(r).find(u=>u.name.errorId===n.name.errorId);if(!a){this.errors.add(`Error "${n.name.errorId}" with status code "${n.statusCode}" was removed.`);continue}this.checkErrorBreakingChanges({from:n,to:a})}}checkErrorBreakingChanges({from:t,to:r}){if(t.type!=null){if(r.type==null){this.errors.add(`Error "${t.name.errorId}" with status code "${t.statusCode}" had its type removed.`);return}this.areTypeReferencesCompatible({from:t.type,to:r.type})||this.errors.add(`Error "${t.name.errorId}" type reference changed.`)}this.areDeclaredErrorNamesCompatible({from:t.name,to:r.name})||this.errors.add(`Error "${t.name.errorId}" name changed.`),this.areNameAndWireValuesCompatible({from:t.discriminantValue,to:r.discriminantValue})||this.errors.add(`Error "${t.name.errorId}" discriminant value changed.`)}checkServicesBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){let a=r[i];if(!a){this.errors.add(`Service "${i}" was removed.`);continue}this.checkServiceBreakingChanges({id:i,from:n,to:a})}}checkServiceBreakingChanges({id:t,from:r,to:i}){this.checkHeadersBreakingChanges({id:t,from:r.headers,to:i.headers}),this.checkEndpointsBreakingChanges({id:t,from:r,to:i})}checkEndpointsBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.endpoints.map(u=>[u.id,u])),a=Object.fromEntries(i.endpoints.map(u=>[u.id,u]));for(let[u,l]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Endpoint "${u}" was removed.`);continue}this.checkEndpointBreakingChanges({id:u,from:l,to:d})}}checkEndpointBreakingChanges({id:t,from:r,to:i}){this.checkHttpMethodsBreakingChanges({id:t,from:r.method,to:i.method}),this.checkHttpPathsBreakingChanges({id:t,from:r.fullPath,to:i.fullPath}),this.checkPathParametersBreakingChanges({id:t,from:r.pathParameters,to:i.pathParameters}),this.checkQueryParametersBreakingChanges({id:t,from:r.queryParameters,to:i.queryParameters}),this.checkHeadersBreakingChanges({id:t,from:r.headers,to:i.headers}),r.requestBody!=null&&(i.requestBody!=null?this.checkHttpRequestBodiesCompatible({id:t,from:r.requestBody,to:i.requestBody}):this.errors.add(`Request body was removed from endpoint "${r.id}".`)),r.response!=null&&(i.response!=null?this.checkHttpResponseBreakingChanges({id:t,from:r.response,to:i.response}):this.errors.add(`Response was removed from endpoint "${r.id}".`)),(r.pagination!=null&&i.pagination==null||r.pagination==null&&i.pagination!=null)&&this.errors.add(`Pagination was ${r.pagination!=null?"added":"removed"} from endpoint "${r.id}".`)}checkPathParametersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(u=>[u.name.originalName,u])),a=Object.fromEntries(i.map(u=>[u.name.originalName,u]));for(let[u,l]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Path parameter "${u}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:l.valueType,to:d.valueType})||this.errors.add(`Path parameter "${u}" type changed in endpoint "${t}".`)}}checkQueryParametersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(u=>[u.name.wireValue,u])),a=Object.fromEntries(i.map(u=>[u.name.wireValue,u]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(n).map(([u,l])=>[u,l.valueType])),to:Object.fromEntries(Object.entries(a).map(([u,l])=>[u,l.valueType]))});for(let[u,l]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Query parameter "${u}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:l.valueType,to:d.valueType})||this.errors.add(`Query parameter "${u}" type changed in endpoint "${t}".`),l.allowMultiple!==d.allowMultiple&&this.errors.add(`Query parameter "${u}" allow-multiple values changed in endpoint "${t}".`)}}checkHeadersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(u=>[u.name.wireValue,u])),a=Object.fromEntries(i.map(u=>[u.name.wireValue,u]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(n).map(([u,l])=>[u,l.valueType])),to:Object.fromEntries(Object.entries(a).map(([u,l])=>[u,l.valueType]))});for(let[u,l]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Header "${u}" was removed from ${t}.`);continue}this.areTypeReferencesCompatible({from:l.valueType,to:d.valueType})||this.errors.add(`Header "${u}" type changed in ${t}.`)}}checkHttpMethodsBreakingChanges({id:t,from:r,to:i}){r!==i&&this.errors.add(`HTTP method changed in ${t}.`)}checkHttpPathsBreakingChanges({id:t,from:r,to:i}){this.areHttpPathsCompatible({from:r,to:i})||this.errors.add(`HTTP path changed in ${t}.`)}areHttpPathsCompatible({from:t,to:r}){if(t.head!==r.head||t.parts.length!==r.parts.length)return!1;for(let i=0;i<t.parts.length;i++){let n=t.parts[i];if(n==null)return!1;let a=r.parts[i];if(a==null||n.pathParameter!==a.pathParameter||n.tail!==a.tail)return!1}return!0}checkHttpRequestBodiesCompatible({id:t,from:r,to:i}){switch(r.type){case"inlinedRequestBody":if(i.type==="inlinedRequestBody"&&this.areInlinedRequestBodiesCompatible({from:r,to:i}))return;break;case"reference":if(i.type==="reference"&&this.areReferenceRequestBodiesCompatible({from:r,to:i}))return;break;case"fileUpload":if(i.type==="fileUpload"&&this.areFileUploadRequestBodiesCompatible({from:r,to:i}))return;break;case"bytes":if(i.type==="bytes")return;break;default:mo(r)}this.errors.add(`Request body type changed from "${r.type}" to "${i.type}" in endpoint "${t}".`)}areInlinedRequestBodiesCompatible({from:t,to:r}){let i=this.getInlinedRequestBody(t),n=this.getInlinedRequestBody(r);return this.checkForNewInlinedRequestBodyProperties({from:i,to:n}),Object.entries(i).every(([a,u])=>{let l=n[a];return l?this.areTypeReferencesCompatible({from:u,to:l}):(this.errors.add(`Request body property "${a}" was removed.`),!1)})}areReferenceRequestBodiesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.requestBodyType,to:r.requestBodyType})}areFileUploadRequestBodiesCompatible({from:t,to:r}){let i=this.getFileUploadRequest(t.properties),n=this.getFileUploadRequest(r.properties);this.checkForNewFileUploadRequestProperties({from:i,to:n});for(let[a,u]of Object.entries(i)){let l=n[a];if(!l)return this.errors.add(`File upload property "${a}" was removed.`),!1;if(u==="file"&&l!=="file")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(u==="fileArray"&&l!=="fileArray")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(u!=="file"&&u!=="fileArray"&&l!=="file"&&l!=="fileArray"&&!this.areTypeReferencesCompatible({from:u,to:l}))return this.errors.add(`File upload property "${a}" type changed.`),!1}return!0}checkHttpResponseBreakingChanges({id:t,from:r,to:i}){if(r.statusCode!==i.statusCode&&this.errors.add(`Response status code changed from "${r.statusCode}" to "${i.statusCode}".`),!(r.body==null&&i.body==null)){if(r.body==null||i.body==null){this.errors.add(`Response body was ${r.body==null?"added":"removed"}.`);return}switch(r.body.type){case"json":if(i.body.type==="json"){this.areJsonResponsesCompatible({from:r.body.value,to:i.body.value});return}break;case"fileDownload":if(i.body.type==="fileDownload")return;break;case"text":if(i.body.type==="text")return;break;case"bytes":if(i.body.type==="bytes")return;break;case"streaming":if(i.body.type==="streaming"){this.areStreamingResponsesCompatible({from:r.body.value,to:i.body.value});return}break;case"streamParameter":if(i.body.type==="streamParameter"){this.areStreamingResponsesCompatible({from:r.body.streamResponse,to:i.body.streamResponse});return}break;default:mo(r.body)}this.errors.add(`HTTP response type "${r.body.type}" defined for endpoint "${t}" is not compatible with type "${i.body.type}".`)}}areJsonResponsesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.responseBodyType,to:r.responseBodyType})}areStreamingResponsesCompatible({from:t,to:r}){switch(t.type){case"json":if(r.type==="json")return this.areTypeReferencesCompatible({from:t.payload,to:r.payload});break;case"sse":if(r.type==="sse")return this.areTypeReferencesCompatible({from:t.payload,to:r.payload});break;case"text":if(r.type==="text")return!0;break;default:mo(t)}return this.errors.add(`Streaming response type "${t.type}" is not compatible with type "${r.type}".`),!1}areTypeDeclarationsCompatible({from:t,to:r}){return this.areDeclaredTypeNamesCompatible({from:t.name,to:r.name})&&this.areTypeShapesCompatible({from:t.shape,to:r.shape})}areTypeShapesCompatible({from:t,to:r}){switch(t.type){case"alias":if(r.type==="alias")return this.areAliasTypesCompatible({from:t,to:r});break;case"enum":if(r.type==="enum")return this.areEnumTypesCompatible({from:t,to:r});break;case"object":if(r.type==="object")return this.areObjectTypesCompatible({from:t,to:r});break;case"union":if(r.type==="union")return this.areUnionTypesCompatible({from:t,to:r});break;case"undiscriminatedUnion":if(r.type==="undiscriminatedUnion")return this.areUndiscriminatedUnionTypesCompatible({from:t,to:r});break;default:mo(t)}return this.errors.add(`Type "${t.type}" is not compatible with type "${r.type}".`),!1}areAliasTypesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.aliasOf,to:r.aliasOf})}areEnumTypesCompatible({from:t,to:r}){let i=Object.fromEntries(t.values.map(a=>[a.name.wireValue,a])),n=Object.fromEntries(r.values.map(a=>[a.name.wireValue,a]));return Object.keys(i).length!==Object.keys(n).length?!1:Object.values(i).every(a=>{let u=n[a.name.wireValue];return u?this.areNameAndWireValuesCompatible({from:a.name,to:u.name}):(this.errors.add(`Enum value "${a.name.wireValue}" was removed.`),!1)})}areObjectTypesCompatible({from:t,to:r}){let i=Object.fromEntries([...t.properties.map(a=>[a.name.wireValue,a]),...t.extendedProperties?.map(a=>[a.name.wireValue,a])??[]]),n=Object.fromEntries([...r.properties.map(a=>[a.name.wireValue,a]),...r.extendedProperties?.map(a=>[a.name.wireValue,a])??[]]);return this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(i).map(([a,u])=>[a,u.valueType])),to:Object.fromEntries(Object.entries(n).map(([a,u])=>[a,u.valueType]))}),Object.values(i).every(a=>{let u=n[a.name.wireValue];return u?this.areObjectPropertiesCompatible({from:a,to:u}):(this.errors.add(`Object property "${a.name.wireValue}" was removed.`),!1)})}areObjectPropertiesCompatible({from:t,to:r}){return this.areNameAndWireValuesCompatible({from:t.name,to:r.name})&&this.areTypeReferencesCompatible({from:t.valueType,to:r.valueType})}areUnionTypesCompatible({from:t,to:r}){if(!this.areNameAndWireValuesCompatible({from:t.discriminant,to:r.discriminant}))return this.errors.add(`Union type with discriminant value "${t.discriminant.wireValue}" changed.`),!1;let i=new Set(t.extends.map(s=>this.getKeyForDeclaration(s))),n=new Set(r.extends.map(s=>this.getKeyForDeclaration(s)));for(let s of i)if(!n.has(s))return this.errors.add(`Extended type "${s}" was removed.`),!1;let a=Object.fromEntries(t.baseProperties.map(s=>[s.name.wireValue,s])),u=Object.fromEntries(r.baseProperties.map(s=>[s.name.wireValue,s]));for(let s of Object.values(a)){let o=u[s.name.wireValue];if(!o)return this.errors.add(`Union type with discriminant value "${s.name.wireValue}" no longer has a property named "${s.name.wireValue}".`),!1;if(!this.areObjectPropertiesCompatible({from:s,to:o}))return!1}this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(a).map(([s,o])=>[s,o.valueType])),to:Object.fromEntries(Object.entries(u).map(([s,o])=>[s,o.valueType]))});let l=Object.fromEntries(t.types.map(s=>[s.discriminantValue.wireValue,s])),d=Object.fromEntries(r.types.map(s=>[s.discriminantValue.wireValue,s]));return Object.values(l).every(s=>{let o=d[s.discriminantValue.wireValue];return o?this.areSingleUnionTypesCompatible({from:s.shape,to:o.shape}):(this.errors.add(`Union type for discriminant value "${s.discriminantValue.wireValue}" was removed.`),!1)})}areSingleUnionTypesCompatible({from:t,to:r}){switch(t.propertiesType){case"samePropertiesAsObject":if(r.propertiesType==="samePropertiesAsObject")return this.areDeclaredTypeNamesCompatible({from:t,to:r});break;case"singleProperty":if(r.propertiesType==="singleProperty")return this.areNameAndWireValuesCompatible({from:t.name,to:r.name})&&this.areTypeReferencesCompatible({from:t.type,to:r.type});break;case"noProperties":if(r.propertiesType==="noProperties")return!0;break;default:mo(t)}return this.errors.add(`Single union type of style "${t.propertiesType}" is not compatible with style "${r.propertiesType}".`),!1}areUndiscriminatedUnionTypesCompatible({from:t,to:r}){return t.members.every((i,n)=>{let a=r.members[n];return a?this.areTypeReferencesCompatible({from:i.type,to:a.type}):(this.errors.add(`Undiscriminated union member at index ${n} was removed.`),!1)})}checkForNewRequiredTypeReferences({from:t,to:r}){for(let[i,n]of Object.entries(r))t[i]||(n.type!=="container"||n.container.type!=="optional")&&this.errors.add(`Required property "${i}" was added.`)}checkForNewFileUploadRequestProperties({from:t,to:r}){for(let[i,n]of Object.entries(r))t[i]||n==="file"||n==="fileArray"||(n.type!=="container"||n.container.type!=="optional")&&this.errors.add(`Required property "${i}" was added.`)}checkForNewInlinedRequestBodyProperties({from:t,to:r}){for(let[i,n]of Object.entries(r))t[i]||(n.type!=="container"||n.container.type!=="optional")&&this.errors.add(`Required property "${i}" was added.`)}areTypeReferencesCompatible({from:t,to:r}){switch(t.type){case"primitive":if(r.type==="primitive")return this.arePrimitiveTypesCompatible({from:t,to:r});break;case"container":if(r.type==="container")return this.areContainerTypesCompatible({from:t.container,to:r.container});break;case"named":if(r.type==="named")return this.areNamedTypesCompatible({from:t,to:r});break;case"unknown":if(r.type==="unknown")return!0;break;default:mo(t)}return this.errors.add(`TypeReference "${t.type}" is not compatible with type "${r.type}".`),!1}arePrimitiveTypesCompatible({from:t,to:r}){return t.primitive.v1===r.primitive.v1}areContainerTypesCompatible({from:t,to:r}){switch(t.type){case"list":if(r.type==="list")return this.areTypeReferencesCompatible({from:t.list,to:r.list});break;case"set":if(r.type==="set")return this.areTypeReferencesCompatible({from:t.set,to:r.set});break;case"map":if(r.type==="map")return this.areTypeReferencesCompatible({from:t.keyType,to:r.keyType})&&this.areTypeReferencesCompatible({from:t.valueType,to:r.valueType});break;case"optional":if(r.type==="optional")return this.areTypeReferencesCompatible({from:t.optional,to:r.optional});break;case"nullable":if(r.type==="nullable")return this.areTypeReferencesCompatible({from:t.nullable,to:r.nullable});break;case"literal":if(r.type==="literal")return this.areLiteralsCompatible({from:t.literal,to:r.literal});break;default:mo(t)}return this.errors.add(`Container type "${t.type}" is not compatible with type "${r.type}".`),!1}areNamedTypesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areDeclaredTypeNamesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areDeclaredErrorNamesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areNameAndWireValuesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&t.wireValue===r.wireValue}areLiteralsCompatible({from:t,to:r}){switch(t.type){case"boolean":if(r.type==="boolean")return t.boolean===r.boolean;break;case"string":if(r.type==="string")return t.string===r.string;break;default:mo(t)}return!1}areFernFilepathsCompatible({from:t,to:r}){return t.allParts.length!==r.allParts.length?!1:t.allParts.every((i,n)=>{let a=r.allParts[n];return a==null?!1:this.areNamesCompatible({from:i,to:a})})}areNamesCompatible({from:t,to:r}){return t.originalName===r.originalName}getInlinedRequestBody(t){let r={};for(let i of[...t.extendedProperties??[],...t.properties])r[i.name.wireValue]=i.valueType;return r}getFileUploadRequest(t){let r={};for(let i of t)switch(i.type){case"file":r[i.value.key.wireValue]="file";break;case"bodyProperty":r[i.name.wireValue]=i.valueType;break;default:mo(i)}return r}getKeyForDeclaration({name:t,fernFilepath:r}){return`${r.allParts.map(n=>n.camelCase.unsafeName).join(".")}.${t.pascalCase.unsafeName}`}};function xB_({filteredIr:e,singleUnionTypeProperties:t}){return t._visit({samePropertiesAsObject:r=>{let i=e.hasTypeId(r.typeId)?{...r,object:{properties:r.object.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:wR({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)}}:void 0;return i!==void 0?y3.samePropertiesAsObject(i):void 0},singleProperty:r=>{let i=wR({filteredIr:e,exampleTypeReference:r});return i!==void 0?y3.singleProperty(i):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function wR({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:i=>({...t,shape:Nh.container(bm.list({...i,list:i.list.map(n=>wR({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:Nh.container(bm.set({...i,set:i.set.map(n=>wR({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?wR({filteredIr:e,exampleTypeReference:i.optional}):void 0;return n!=null?{...t,shape:Nh.container(bm.optional({optional:n,valueType:i.valueType}))}:void 0},nullable:i=>{let n=i.nullable!=null?wR({filteredIr:e,exampleTypeReference:i.nullable}):void 0;return n!=null?{...t,shape:Nh.container(bm.nullable({nullable:n,valueType:i.valueType}))}:void 0},map:i=>({...t,shape:Nh.container(bm.map({...i,map:i.map.map(n=>{let a=wR({filteredIr:e,exampleTypeReference:n.key}),u=wR({filteredIr:e,exampleTypeReference:n.value});return a!==void 0&&u!==void 0?{key:a,value:u}:void 0}).filter(n=>n!==void 0)}))}),literal:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}}),named:r=>e.hasTypeId(r.typeName.typeId)?r.shape._visit({alias:i=>{let n=wR({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:Nh.named({...r,shape:Iw.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:Nh.named({...r,shape:Iw.enum(i)})}),object:i=>({...t,shape:Nh.named({...r,shape:Iw.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:wR({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=xB_({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:Nh.named({...r,shape:Iw.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=wR({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:Nh.named({...r,shape:Iw.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function kPc({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=wR({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function gJE({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=wR({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function zB_({filteredIr:e,headers:t}){return t.map(r=>{let i=wR({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function OJE({filteredIr:e,requestBody:t}){return t._visit({inlinedRequestBody:r=>({...t,properties:r.properties.filter(i=>i.originalTypeDeclaration?e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue):!0).map(i=>{let n=wR({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=wR({filteredIr:e,exampleTypeReference:r});return i!==void 0?xQ.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function mJE({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>RT.ok(kC.body(i!=null?wR({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>RT.ok(kC.stream(i.map(n=>wR({filteredIr:e,exampleTypeReference:n})).filter(V0))),sse:i=>RT.ok(kC.sse(i.map(({event:n,data:a})=>{let u=wR({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:n,data:u}:void 0}).filter(V0))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>RT.error({error:r,body:i!=null?wR({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function ejc({filteredIr:e,example:t}){return{...t,rootPathParameters:kPc({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:kPc({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:kPc({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:zB_({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:zB_({filteredIr:e,headers:t.endpointHeaders}),queryParameters:gJE({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?OJE({filteredIr:e,requestBody:t.request}):void 0,response:mJE({filteredIr:e,response:t.response})}}function RB_({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=wR({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:Iw.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:Iw.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:wR({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=xB_({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:Iw.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=wR({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:Iw.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function tjc(e,t){if(t==null)return e;let r=AVi(e.types,l=>t.hasType(l)),i=Object.fromEntries(Object.entries(r).map(([l,d])=>{let s=[];if(d.userProvidedExamples=d.userProvidedExamples.map(o=>RB_({filteredIr:t,exampleType:o})).filter(o=>o!==void 0),d.shape.type==="object"){for(let o of d.shape.properties)t.hasProperty(l,o.name.wireValue)&&s.push(o);return[l,{...d,shape:lO.object({...d.shape,properties:s})}]}return[l,d]})),n=Object.fromEntries(Object.entries(e.webhookGroups).map(([l,d])=>{let s=d.filter(o=>t.hasWebhook(o)).map(o=>{let c=o.id;return o.payload.type==="inlinedPayload"&&c!=null&&(o.payload={...o.payload,properties:o.payload.properties.filter(b=>t.hasWebhookPayloadProperty(c,b.name.wireValue))}),o});return[l,s]})),a=e.websocketChannels!=null?Object.fromEntries(Object.entries(e.websocketChannels).filter(([l])=>t.hasChannel(l)).map(([l,d])=>[l,{...d}])):{},u=e.environments;if(u){switch(u.environments.type){case"singleBaseUrl":{u.environments.environments=u.environments.environments.filter(l=>t.hasEnvironmentId(l.id));break}case"multipleBaseUrls":{u.environments.environments=u.environments.environments.filter(l=>t.hasEnvironmentId(l.id));break}}u.defaultEnvironment&&(t.hasEnvironmentId(u.defaultEnvironment)||(u.defaultEnvironment=void 0))}return{...e,environments:u,types:i,errors:AVi(e.errors,l=>t.hasError(l)),services:dd(AVi(e.services,l=>t.hasService(l)),l=>({...l,endpoints:l.endpoints.filter(d=>t.hasEndpoint(d)).map(d=>(d.autogeneratedExamples=d.autogeneratedExamples.map(s=>({...s,example:ejc({filteredIr:t,example:s.example})})),d.userSpecifiedExamples=d.userSpecifiedExamples.map(s=>({...s,example:s.example!=null?ejc({filteredIr:t,example:s.example}):void 0})),d.queryParameters.length>0&&(d.queryParameters=d.queryParameters.filter(s=>t.hasQueryParameter(d.id,s.name.wireValue))),d.requestBody?.type==="inlinedRequestBody"?{...d,requestBody:{...d.requestBody,properties:d.requestBody.properties.filter(s=>t.hasRequestProperty(d.id,s.name.wireValue))}}:d))})),websocketChannels:a,webhookGroups:n,serviceTypeReferenceInfo:PJE(e.serviceTypeReferenceInfo,t)}}function PJE(e,t){if(t==null)return e;let r={};return Object.entries(e.typesReferencedOnlyByService).forEach(([i,n])=>{t.hasServiceId(i)&&(r[i]=n.filter(a=>t.hasTypeId(a)))}),{sharedTypes:e.sharedTypes.filter(i=>t.hasTypeId(i)),typesReferencedOnlyByService:r}}var pH={};jo(pH,{AudienceExtension:()=>pko,FernAvailabilityExtension:()=>_ko,FernEnumExtension:()=>hko,FernIgnoreExtension:()=>SKi,FernOptionalExtension:()=>yko,FernTypeExtension:()=>gko,FernTypeNameExtension:()=>Oko,SdkGroupNameExtension:()=>vko,SdkMethodNameExtension:()=>bko});var pko=class extends Pm{operation;key="x-fern-audiences";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(i=>typeof i=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{audiences:r}}};var _ko=class extends Pm{node;key="x-fern-availability";constructor({breadcrumbs:t,node:r,context:i}){super({breadcrumbs:t,context:i}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t==null||typeof t!="string")return;switch(t.toUpperCase().replace(/[-_\s]/g,"_")){case"IN_DEVELOPMENT":return B9.InDevelopment;case"PRE_RELEASE":case"BETA":return B9.PreRelease;case"GENERAL_AVAILABILITY":case"GA":return B9.GeneralAvailability;case"DEPRECATED":return B9.Deprecated;default:return}}};var jJE=hu.object({snake:hu.string().optional(),camel:hu.string().optional(),screamingSnake:hu.string().optional(),pascal:hu.string().optional()}),wJE=hu.object({description:hu.string().optional(),name:hu.string().optional(),casing:jJE.optional()}),NB_=hu.record(wJE);var hko=class extends Pm{schema;key="x-fern-enum";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t==null)return;let r=NB_.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-enum extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data}};var SKi=class extends Pm{operation;key="x-fern-ignore";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-ignore",path:this.breadcrumbs});return}return t}}};var yko=class extends Pm{parameter;key="x-fern-optional";constructor({breadcrumbs:t,parameter:r,context:i}){super({breadcrumbs:t,context:i}),this.parameter=r}convert(){let t=this.getExtensionValue(this.parameter);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-optional",path:this.breadcrumbs});return}return t}}};var vko=class extends Pm{operation;key="x-fern-sdk-group-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(i=>typeof i=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{groups:r}}};var bko=class extends Pm{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null&&typeof t=="string")return{methodName:t}}};var gko=class extends Pm{schema;key="x-fern-type";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t!=null&&typeof t=="string")return t}};var Oko=class extends Pm{schema;key="x-fern-type-name";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(typeof t=="string")return t}};var qpi=class extends yb{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:i}){super({breadcrumbs:t,context:r}),this.audiences=i,this.irGraph=new wKi(i),this.ir={auth:{docs:void 0,requirement:Ws.AuthSchemesRequirement.All,schemes:[]},selfHosted:!1,types:{},services:{},errors:{},webhookGroups:{},websocketChannels:void 0,headers:[],idempotencyHeaders:[],apiVersion:void 0,apiDisplayName:void 0,apiDocs:void 0,basePath:void 0,pathParameters:[],errorDiscriminationStrategy:Ws.ErrorDiscriminationStrategy.statusCode(),variables:[],serviceTypeReferenceInfo:{sharedTypes:[],typesReferencedOnlyByService:{}},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,environments:void 0,fdrApiDefinitionId:void 0,rootPackage:this.createPackage(),subpackages:{},sdkConfig:{hasFileDownloadEndpoints:!1,hasPaginatedEndpoints:!1,hasStreamingEndpoints:!1,isAuthMandatory:!0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}}}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((i,n)=>!new SKi({breadcrumbs:[...r,String(n)],operation:i,context:this.context}).convert()).map((i,n)=>this.removeXFernIgnores({document:i,breadcrumbs:[...r,String(n)]})):t!=null&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([i,n])=>!new SKi({breadcrumbs:[...r,i],operation:n,context:this.context}).convert()).map(([i,n])=>[i,this.removeXFernIgnores({document:n,breadcrumbs:[...r,i]})])):t}finalizeIr(){let t={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}};this.irGraph.hasNoAudiences()||(t=this.filterIrForAudiences(t));let r=this.context.exampleGenerationArgs,i=JPc({ir:t,exampleGeneration:r});if(this.context.generateV1Examples){let n=CRa({ir:t,exampleGeneration:r});return{...t,...n,...i}}return{...t,...i}}filterIrForAudiences(t){let r=this.irGraph.getFilteredEndpoints(),i=this.irGraph.getFilteredChannels(),n=this.irGraph.getFilteredWebhooks();for(let a of Object.values(t.services)){let u=[];for(let l of a.endpoints)r.has(l.id)&&u.push(l);a.endpoints=u}return t.websocketChannels=Object.fromEntries(Object.entries(t.websocketChannels??{}).filter(([a])=>i.has(a))),t.webhookGroups=Object.fromEntries(Object.entries(t.webhookGroups).filter(([a])=>n.has(a))),t}async resolveAllExternalRefs({spec:t}){let r=[t];for(;r.length>0;){let i=r.shift();i!=null&&(Array.isArray(i)?await this.resolveExternalRefsInArray(i,r):typeof i=="object"&&await this.resolveExternalRefsInObject(i,r))}return t}async resolveExternalRefsInArray(t,r){for(let i=0;i<t.length;i++)t[i]=await this.resolveReferenceChain(t[i],r)}async resolveExternalRefsInObject(t,r){for(let[i,n]of Object.entries(t))t[i]=await this.resolveReferenceChain(n,r)}async resolveReferenceChain(t,r){let i=t;if(!this.context.isReferenceObject(i))return r.push(i),t;for(;this.context.isReferenceObject(i);){let n=this.context.isExternalReference(i.$ref),a=await this.context.resolveMaybeExternalReference(i);if(a.resolved){if(i=a.value,n)return i}else return t}return t}shouldAddServerToCollectedServers({server:t,currentServers:r,specType:i="openapi"}){return i==="openapi"?!r.some(n=>n.url===t.url&&"x-fern-server-name"in n&&"x-fern-server-name"in t&&n["x-fern-server-name"]===t["x-fern-server-name"]):!r.some(n=>n.url===t.url&&"name"in n&&"name"in t&&n.name===t.name)}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:i,endpointGroupDisplayName:n,serviceName:a}){let u=this.context.getGroup({groupParts:i,namespace:this.context.namespace}),l=this.getOrCreatePackage({group:i}),d=[...u].map(c=>this.context.casingsGenerator.generateName(c)),s=d[d.length-1];l.service==null&&(l.service=a??`service_${u.map(c=>T_(c)).join("/")}`),this.ir.services[l.service]==null&&(this.ir.services[l.service]=this.createNewService({allParts:d,finalpart:s,endpointGroupDisplayName:n})),this.ir.services[l.service]?.endpoints.push(t);let o=this.ir.services[l.service];o!=null&&(this.irGraph.addEndpoint(o,t),this.irGraph.markEndpointForAudience(o.name,[t],r))}addWebhookToIr({webhook:t,operationId:r,audiences:i,group:n}){let a=n?.join(".")??r,u=this.getOrCreatePackage({group:n});this.ir.webhookGroups[a]==null&&(this.ir.webhookGroups[a]=[]),this.ir.webhookGroups[a].push(t),u.webhooks=a;let l=this.context.createFernFilepath();this.irGraph.addWebhook(l,t),i!=null&&this.irGraph.markWebhookForAudiences(l,t,i)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:i,websocketGroup:n}){let a=T_(n?.join(".")),u=T_(r),l=this.context.namespace?`${T_(this.context.namespace)}/`:"",d=a?`channel_${l}${a}`:`channel_${l}${u}`,s=n?this.getOrCreatePackage({group:n}):this.getOrCreatePackage({group:[u]});this.ir.websocketChannels={...this.ir.websocketChannels,[d]:t},d!==""?s.websocket==null&&(s.websocket=d):this.ir.rootPackage.websocket="";let o=this.context.createFernFilepath();this.irGraph.addChannel(o,d,t),i!=null&&this.irGraph.markChannelForAudiences(o,d,i)}addAuthToIR(t){this.ir.auth=t}addErrorsToIr(t){this.ir.errors=t;for(let r of Object.values(t))this.irGraph.addError(r)}addGlobalHeadersToIr(t){this.ir.headers=t}addEnvironmentsToIr({environmentConfig:t,audiences:r}){if(this.ir.environments=t,r!=null)for(let[i,n]of Object.entries(t??{}))r[i]!=null&&this.irGraph.markEnvironmentForAudiences(n,r[i])}addTypeToRootPackage(t){this.ir.rootPackage.types.push(t)}addTypeToPackage(t){let r=this.context.getGroup({groupParts:[],namespace:this.context.namespace});this.getOrCreatePackage({group:r}).types.push(t)}addTypesToIr(t){Object.assign(this.ir.types,Object.fromEntries(Object.entries(t).map(([r,i])=>[r,i.typeDeclaration])));for(let r of Object.values(t))this.irGraph.addType({declaredTypeName:r.typeDeclaration.name,descendantTypeIds:r.typeDeclaration.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:r.propertiesByAudience,descendantFilepaths:new Set}),this.irGraph.markTypeForAudiences(r.typeDeclaration.name,r.audiences)}updateEndpointsWithDefaultUrl(t){if(t!=null)for(let r of Object.values(this.ir.services))for(let i of r.endpoints)i.baseUrl==null&&(i.baseUrl=t)}createNewService({allParts:t,finalpart:r,endpointGroupDisplayName:i}){return{name:{fernFilepath:{allParts:t,packagePath:t.slice(0,-1),file:r}},displayName:i,basePath:fF(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0}}createPackage(t={}){return{fernFilepath:this.context.createFernFilepath(t),service:void 0,types:[],errors:[],subpackages:[],docs:void 0,webhooks:void 0,websocket:void 0,hasEndpointsInTree:!1,navigationConfig:void 0}}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...(t??[]).map(n=>T_(n))),r.length==0)return this.ir.rootPackage;let i=this.ir.rootPackage;for(let n=0;n<r.length;n++){let a=r[n]??"",l=`subpackage_${r.slice(0,n+1).join("/")}`;this.ir.subpackages[l]==null&&(this.ir.subpackages[l]={name:this.context.casingsGenerator.generateName(a),...this.createPackage({name:a})});let d=this.ir.subpackages[l];i.subpackages.includes(l)||i.subpackages.push(l),i=d}return i}};var TM={};jo(TM,{AbstractConverters:()=>ijc,ExampleConverter:()=>VFe,SchemaConverters:()=>rjc,ServersConverter:()=>LMe});var ijc={};jo(ijc,{AbstractMediaTypeObjectConverter:()=>Pko,AbstractParameterConverter:()=>jko});var VFe=class e extends yb{MAX_DEPTH=12;EXAMPLE_STRING="foo";EXAMPLE_NUMBER=42;EXAMPLE_BOOLEAN=!0;EXAMPLE_INTEGER=42;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;constructor({breadcrumbs:t,context:r,schema:i,example:n,depth:a=0,exampleGenerationStrategy:u,generateOptionalProperties:l=!1,seenRefs:d=new Set}){super({breadcrumbs:t,context:r}),this.example=n,this.schema=i,this.depth=a,this.exampleGenerationStrategy=u,this.generateOptionalProperties=l,this.seenRefs=d}convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,validExample:typeof this.example<"u"?this.example:{},errors:[]};if(this.context.isReferenceObject(this.schema)){let r=this.schema.$ref;if(this.seenRefs.has(r))return{isValid:!0,coerced:!1,validExample:this.example,errors:[]}}let t=this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});return t==null?{isValid:!1,coerced:!1,validExample:null,errors:[{message:"Schema is not resolvable",path:this.breadcrumbs}]}:typeof t!="object"?{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Schema should be an object: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]}:"nullable"in t&&t.nullable===!0&&this.example===null?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:Array.isArray(t.type)?this.convertSchemaTypeArray({resolvedSchema:t}):t.type=="null"?this.convertNull():t.type=="boolean"?this.convertBoolean():t.enum!=null?this.convertEnum(t):t.type=="number"?this.convertNumber():t.type=="string"?this.convertString():t.type=="integer"?this.convertInteger():t.type=="array"?this.convertArray({resolvedSchema:t}):"oneOf"in t&&t.oneOf!=null?this.convertOneOf({resolvedSchema:t}):"anyOf"in t&&t.anyOf!=null?this.convertAnyOf({resolvedSchema:t}):t.type=="object"||t.properties!=null||t.allOf!=null?this.convertObject({resolvedSchema:t}):typeof t=="object"&&Object.keys(t).length===0?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Unsupported schema type: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]}}convertNull(){let t=this.example===null;return t?{isValid:t,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Example is not null: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertBoolean(){let t=typeof this.example=="boolean";if(t)return{isValid:t,coerced:!1,validExample:this.example,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.default:this.schema.default,i=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.const:this.schema.const;return typeof r=="boolean"||typeof i=="boolean"?{isValid:!0,coerced:!1,validExample:i??r,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_BOOLEAN,errors:[{message:`Example is not a boolean: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertEnum(t){let r=t.enum?.includes(this.example)??!1;if(r)return{isValid:r,coerced:!1,validExample:this.example,errors:[]};let i=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return i!==void 0&&t.enum?.includes(i)?{isValid:!0,coerced:!1,validExample:i,errors:[]}:{isValid:r,coerced:!1,validExample:t.enum?.[0],errors:[{message:`Example is not one of the allowed enum values: ${JSON.stringify(t.enum,null,2)}`,path:this.breadcrumbs}]}}convertNumber(){if(typeof this.example=="number")return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};let t=Number(this.example);if(!isNaN(t))return{isValid:!0,coerced:!0,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof r=="number"?{isValid:!0,coerced:!1,validExample:r,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertString(){if(typeof this.example=="string")return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};if(typeof this.example!="object"&&!Array.isArray(this.example)&&this.example!=null)return{isValid:!0,coerced:!0,validExample:String(this.example),errors:[]};let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof t=="string"?{isValid:!0,coerced:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_STRING,errors:[{message:`Example cannot be converted to string: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertInteger(){if(typeof this.example=="number"&&Number.isInteger(this.example))return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};if(typeof this.example=="string"){let r=Number(this.example);if(!isNaN(r)&&Number.isInteger(r))return{isValid:!0,coerced:!0,validExample:r,errors:[]}}let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof t=="number"&&Number.isInteger(t)?{isValid:!0,coerced:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_INTEGER,errors:[{message:`Example is not an integer: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertArray({resolvedSchema:t}){if(t.type!="array")return{isValid:!1,coerced:!1,validExample:null,errors:[]};t.items==null&&(t.items={type:"string"});let r=this.example==null,i=this.example??t.example,a=(Array.isArray(i)?i:[i]).map(l=>new e({breadcrumbs:[...this.breadcrumbs,"items"],context:this.context,schema:t.items,example:l,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),u=a.every(l=>l?.isValid??!1)&&!r;return{isValid:u,coerced:!1,validExample:a.map(l=>l.validExample),errors:u?[]:a.flatMap(l=>l.errors)}}convertObject({resolvedSchema:t}){if(t.type=="object"&&t.properties==null&&t.allOf==null)return{isValid:!0,coerced:!1,validExample:this.example??{},errors:[]};let r=typeof this.example!="object"||this.example==null?{}:this.example,i=Object.entries(t.properties??{}).map(([l,d])=>{if(typeof d!="object")return{key:l,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(d)&&!this.isRequiredProperty({key:l,resolvedSchema:t}))return{key:l,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("readOnly"in d&&d.readOnly===!0&&"writeOnly"in d&&d.writeOnly===!0)return{key:l,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("readOnly"in d&&d.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:l,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("writeOnly"in d&&d.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:l,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};let s=!(l in r)||!("nullable"in d)&&r[l]==null||"nullable"in d&&d.nullable===!0&&r[l]===void 0,o=!t.required?.includes(l);if(s&&o){if(this.example===void 0&&this.generateOptionalProperties){let c=new e({breadcrumbs:[...this.breadcrumbs,l],context:this.context,schema:d,example:void 0,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:l,result:c.convert()}}return{key:l,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}}}else{let b=new e({breadcrumbs:[...this.breadcrumbs,l],context:this.context,schema:d,example:r[l],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:l,result:b}}}),n=(t.allOf??[]).map((l,d)=>new e({breadcrumbs:[...this.breadcrumbs,`allOf[${d}]`],context:this.context,schema:{...t,...l,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),a=i.every(l=>l.result.isValid)&&n.every(l=>l.isValid),u=Object.fromEntries(i.map(({key:l,result:d})=>[l,d.validExample]).filter(([l,d])=>d!==void 0));for(let l of n)if(typeof l.validExample=="object"&&l.validExample!==null){let d=l.validExample;u={...u,...Object.fromEntries(Object.entries(d).filter(([s,o])=>o!==void 0))}}if(Object.keys(u).length===0){let l=n.find(d=>d.validExample!==void 0&&(typeof d.validExample!="object"||d.validExample===null));l&&(u=l.validExample)}return{isValid:a,coerced:!1,validExample:u,errors:[...i.flatMap(({result:l})=>l.errors),...n.flatMap(l=>l.errors)]}}convertSchemaTypeArray({resolvedSchema:t}){if(!Array.isArray(t.type))return{isValid:!1,coerced:!1,validExample:null,errors:[]};if(t.type.length===1)return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:{...t,type:t.type[0]},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();let r=t.type.map((u,l)=>new e({breadcrumbs:[...this.breadcrumbs,`type[${l}]`],context:this.context,schema:{...t,type:u},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.some(u=>u?.isValid??!1),a=r.find(u=>u.isValid)?.validExample??r[0]?.validExample??null;return{isValid:i,coerced:!1,validExample:a,errors:i?[]:r.flatMap(u=>u?.errors??[])}}convertOneOf({resolvedSchema:t}){if(!("oneOf"in t)||t.oneOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=t.oneOf.map((u,l)=>new e({breadcrumbs:[...this.breadcrumbs,`oneOf[${l}]`],context:this.context,schema:{...t,...u,oneOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.filter(u=>u.isValid),n=i.length>0,a;return n?a=i.find(l=>!l.coerced)?.validExample??i[0]?.validExample:a=r[0]?.validExample,{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(u=>u.errors)}}convertAnyOf({resolvedSchema:t}){if(!("anyOf"in t)||t.anyOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=t.anyOf.map((u,l)=>new e({breadcrumbs:[...this.breadcrumbs,`anyOf[${l}]`],context:this.context,schema:u,example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.filter(u=>u.isValid),n=i.length>0,a;return n?a=i.find(l=>!l.coerced)?.validExample??i[0]?.validExample:a=r[0]?.validExample,{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(u=>u.errors)}}getMaybeUpdatedSeenRefs(){let t=new Set(this.seenRefs);return this.context.isReferenceObject(this.schema)&&t.add(this.schema.$ref),t}maybeResolveSchemaExample(t){let r=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(r!=null){if("example"in r)return r.example;if("examples"in r)return Object.values(r.examples??{})[0]}}isDeprecatedProperty(t){return t!=null&&"availability"in t&&t.availability==="deprecated"}isRequiredProperty({key:t,resolvedSchema:r}){return r.required?.includes(t)??!1}};var rjc={};jo(rjc,{ArraySchemaConverter:()=>$9n,EnumSchemaConverter:()=>U9n,ObjectSchemaConverter:()=>V9n,OneOfSchemaConverter:()=>W9n,PrimitiveSchemaConverter:()=>H9n,SchemaConverter:()=>HAi,SchemaOrReferenceConverter:()=>SJ});function FB_(e){return G2({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return hf.primitive({v1:"BASE_64",v2:Dp.base64({})});case"BOOLEAN":return hf.primitive({v1:"BOOLEAN",v2:Dp.boolean({default:void 0})});case"DATE":return hf.primitive({v1:"DATE",v2:Dp.date({})});case"DATE_TIME":return hf.primitive({v1:"DATE_TIME",v2:Dp.dateTime({})});case"FLOAT":return hf.primitive({v1:"FLOAT",v2:Dp.float({})});case"DOUBLE":return hf.primitive({v1:"DOUBLE",v2:Dp.double({default:void 0,validation:void 0})});case"UINT":return hf.primitive({v1:"UINT",v2:Dp.uint({})});case"UINT_64":return hf.primitive({v1:"UINT_64",v2:Dp.uint64({})});case"INTEGER":return hf.primitive({v1:"INTEGER",v2:Dp.integer({default:void 0,validation:void 0})});case"LONG":return hf.primitive({v1:"LONG",v2:Dp.long({default:void 0})});case"STRING":return hf.primitive({v1:"STRING",v2:Dp.string({default:void 0,validation:void 0})});case"UUID":return hf.primitive({v1:"UUID",v2:Dp.uuid({})});case"BIG_INTEGER":return hf.primitive({v1:"BIG_INTEGER",v2:Dp.bigInteger({default:void 0})});default:return}},unknown:()=>hf.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return hf.container(_b.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return hf.container(_b.list(t))},optional:t=>{if(t!=null)return hf.container(_b.optional(t))},nullable:t=>{if(t!=null)return hf.container(_b.nullable(t))},set:t=>{if(t!=null)return hf.container(_b.set(t))},literal:t=>hf.container(_b.literal(t._visit({string:r=>R9.string(r),boolean:r=>R9.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var U9n=class extends yb{schema;maybeFernEnum;constructor({context:t,breadcrumbs:r,schema:i,maybeFernEnum:n}){super({context:t,breadcrumbs:r}),this.schema=i,this.maybeFernEnum=n}convert(){if(!this.schema.enum)return;let r=this.schema.enum.filter(n=>typeof n=="string"||typeof n=="number").map(n=>{let a=n.toString(),u=this.maybeFernEnum?.[a],l=u?.name??a;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:l,wireValue:a}),docs:u?.description,availability:void 0,casing:u?.casing}});if(r.length===0){this.context.errorCollector.collect({message:`Received enum schema with no valid values: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}let i=this.context.getAsString(this.schema.default);return{type:lO.enum({default:i!=null?r.find(n=>n.name.wireValue===i):void 0,values:r})}}};var mko=class extends yb{schemaOrReferenceOrBoolean;constructor({context:t,breadcrumbs:r,schemaOrReferenceOrBoolean:i}){super({context:t,breadcrumbs:r}),this.schemaOrReferenceOrBoolean=i}convert(){let t=this.tryConvertUnknownMap();if(t!=null)return t;let r=this.tryConvertTypedMap();if(r!=null)return r}tryConvertUnknownMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean"){let t=hf.container(_b.map({keyType:yb.STRING,valueType:hf.unknown()}));return{type:lO.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new SJ({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let i=hf.container(_b.map({keyType:yb.STRING,valueType:r.type})),n=new Set;for(let a of r.schema?.typeDeclaration.referencedTypes??[])n.add(a);for(let a of Object.keys(r.inlinedTypes))n.add(a);return{type:lO.alias({aliasOf:i,resolvedType:i}),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}};function zRa({properties:e,required:t,breadcrumbs:r,context:i,errorCollector:n}){let a=[],u={},l={},d=new Set;for(let[s,o]of Object.entries(e??{})){let c=[...r,"properties",s];if(typeof o!="object"){n.collect({message:`Schema property ${s} should be an object`,path:c});continue}let b=SJE(r,o,i)??i.convertBreadcrumbsToName(c),g="nullable"in o?o.nullable:!1,m=new SJ({context:i,breadcrumbs:c,schemaOrReference:o,schemaIdOverride:b,wrapAsOptional:!t.includes(s),wrapAsNullable:g}).convert();if(m!=null){a.push({name:i.casingsGenerator.generateNameAndWireValue({name:s,wireValue:s}),valueType:m.type,docs:o.description,availability:m.availability,propertyAccess:i.getPropertyAccess(o),v2Examples:m.schema?.typeDeclaration?.v2Examples??{userSpecifiedExamples:{},autogeneratedExamples:{}}}),u={...u,...m.inlinedTypes},m.schema?.typeDeclaration.referencedTypes!=null&&m.schema.typeDeclaration.referencedTypes.forEach(P=>{d.add(P)});for(let P of m.schema?.audiences??[])l[P]==null&&(l[P]=new Set),l[P].add(s)}}for(let s of Object.keys(u))d.add(s);return{convertedProperties:a,propertiesByAudience:l,inlinedTypesFromProperties:u,referencedTypes:d}}function SJE(e,t,r){return r.isReferenceObject(t)?void 0:new pH.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}var V9n=class extends yb{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:lO.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set};let{convertedProperties:r,inlinedTypesFromProperties:i,referencedTypes:n,propertiesByAudience:a}=zRa({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector}),u=[],l=n,d=this.schema.required!=null&&this.schema.required.length>0,s=i,o=a;for(let[c,b]of(this.schema.allOf??[]).entries()){let g=[...this.breadcrumbs,"allOf",c.toString()],O;if(this.context.isReferenceObject(b)){if(!d){this.addTypeReferenceToExtends({reference:b,breadcrumbs:g,extends_:u,referencedTypes:l});continue}let M=this.context.resolveMaybeReference({schemaOrReference:b,breadcrumbs:g});if(M==null)continue;if(O=M,Object.keys(O.properties??{}).every(D=>!this.schema.required?.includes(D))){this.addTypeReferenceToExtends({reference:b,breadcrumbs:g,extends_:u,referencedTypes:l});continue}}else O=b;let{convertedProperties:m,inlinedTypesFromProperties:P,referencedTypes:E,propertiesByAudience:q}=zRa({properties:O.properties??{},required:[...this.schema.required??[],...O.required??[]],breadcrumbs:g,context:this.context,errorCollector:this.context.errorCollector});r.push(...m),s={...s,...P},o={...o,...q},E.forEach(M=>{l.add(M)})}for(let c of Object.keys(s))l.add(c);return{type:lO.object({properties:r,extends:u.map(c=>this.context.typeReferenceToDeclaredTypeName(c)).filter(V0),extendedProperties:[],extraProperties:t}),propertiesByAudience:o,referencedTypes:l,inlinedTypes:s}}addTypeReferenceToExtends({reference:t,breadcrumbs:r,extends_:i,referencedTypes:n}){let a=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:r});a.ok&&i.push(a.reference);let u=this.context.getTypeIdFromSchemaReference(t);u!=null&&n.add(u)}};var W9n=class extends yb{schema;id;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlinedTypes:a}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n}convert(){return this.shouldConvertAsNullableSchemaOrReference()?this.convertAsNullableSchemaOrReference():this.schema.discriminator!=null&&!this.unionVariantsContainLiteral({discriminantProperty:this.schema.discriminator.propertyName})?this.convertAsDiscriminatedUnion():this.convertAsUndiscriminatedUnion()}unionVariantsContainLiteral({discriminantProperty:t}){for(let[r,i]of Object.entries(this.schema.discriminator?.mapping??{})){let n=this.context.resolveReference({reference:{$ref:i},breadcrumbs:this.breadcrumbs});if(n.resolved&&!Object.keys(n.value.properties??{}).includes(t))return!1}return!0}convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=[],r=new Set,i={};for(let[d,s]of Object.entries(this.schema.discriminator.mapping??{})){let o=new SJ({context:this.context,schemaOrReference:{$ref:s},breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",d]}),c=this.context.getTypeIdFromSchemaReference({$ref:s});c!=null&&r.add(c);let b=o.convert();if(b?.type!=null&&c!=null){for(let O of Object.keys(b?.inlinedTypes??{}))r.add(O);for(let O of b.schema?.typeDeclaration.referencedTypes??[])r.add(O);let g=this.context.casingsGenerator.generateNameAndWireValue({name:d,wireValue:d});t.push({docs:void 0,discriminantValue:g,availability:b.availability,displayName:d,shape:RQ.samePropertiesAsObject({typeId:c,name:this.context.casingsGenerator.generateName(c),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:d})}),i={...i,...b.inlinedTypes}}}let{convertedProperties:n,referencedTypes:a,inlinedTypesFromProperties:u}=zRa({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});r=new Set([...r,...a]);let l=[];for(let[d,s]of(this.schema.allOf??[]).entries()){let o=[...this.breadcrumbs,"allOf",d.toString()];if(this.context.isReferenceObject(s)){let c=this.context.convertReferenceToTypeReference({reference:s,breadcrumbs:o});if(c.ok){let g=this.context.typeReferenceToDeclaredTypeName(c.reference);g!=null&&l.push(g)}let b=this.context.getTypeIdFromSchemaReference(s);b!=null&&r.add(b);continue}}for(let d of Object.keys({...i,...u}))r.add(d);return{type:lO.union({baseProperties:n,discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:l,types:t}),referencedTypes:r,inlinedTypes:{...i,...u}}}convertAsUndiscriminatedUnion(){if(!this.schema.oneOf&&!this.schema.anyOf||this.schema.anyOf?.length===0&&this.schema.oneOf?.length===0)return;let t=[],r=new Set,i={};for(let[n,a]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(a)){let c;if(this.context.isReferenceObjectWithIdentifier(a))c=this.context.convertReferenceToTypeReference({reference:a,displayNameOverride:a.title??a.name??a.messageId,displayNameOverrideSource:"reference_identifier"});else if(this.getDiscriminatorKeyForRef(a)!=null){let g=this.getDiscriminatorKeyForRef(a);c=this.context.convertReferenceToTypeReference({reference:a,displayNameOverride:g,displayNameOverrideSource:"discriminator_key"})}else c=this.context.convertReferenceToTypeReference({reference:a,displayNameOverrideSource:"schema_identifier"});c.ok&&t.push({type:c.reference,docs:a.description});let b=this.context.getTypeIdFromSchemaReference(a);b!=null&&r.add(b);continue}let u=this.extendSubSchema(a),l=this.context.convertBreadcrumbsToName([`${this.id}_${n}`]),d=a.title,o=new HAi({context:this.context,id:l,nameOverride:d,breadcrumbs:[...this.breadcrumbs,`oneOf[${n}]`],schema:u??a}).convert();if(o!=null){let c=o.convertedSchema.typeDeclaration.shape;c.type==="alias"&&this.typeReferenceIsWrappedPrimitive(c.aliasOf)?t.push({type:c.aliasOf,docs:a.description}):c.type==="object"&&c.properties.length===0?t.push({type:hf.container(_b.map({keyType:yb.STRING,valueType:hf.unknown()})),docs:a.description}):(t.push({type:this.context.createNamedTypeReference(l,d),docs:a.description}),i={...i,...o.inlinedTypes,[l]:o.convertedSchema}),o.convertedSchema.typeDeclaration.referencedTypes.forEach(b=>{r.add(b)})}}return{type:lO.undiscriminatedUnion({members:t}),referencedTypes:r,inlinedTypes:i}}shouldConvertAsNullableSchemaOrReference(){return this.schema.oneOf!=null?this.schema.oneOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):this.schema.anyOf!=null?this.schema.anyOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):!1}removeNullFromOneOfOrAnyOf(){let t=this.schema.oneOf??this.schema.anyOf,r=this.schema.oneOf!=null?"oneOf":"anyOf";if(t==null)return;let i=t.filter(n=>!("type"in n&&n.type==="null"));if(i.length===0){this.context.errorCollector.collect({message:`Received ${r} schema with no valid non-null types`,path:this.breadcrumbs});return}return i.length===1?{...this.schema,[r]:void 0,...i[0]}:{...this.schema,[r]:i}}convertAsNullableSchemaOrReference(){let t=this.removeNullFromOneOfOrAnyOf();if(t==null)return;let i=new SJ({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(i==null)return;let n=this.wrapInNullable(i.type);return{type:lO.alias({aliasOf:n,resolvedType:n}),referencedTypes:i.schema?.typeDeclaration.referencedTypes??new Set,inlinedTypes:i.inlinedTypes}}typeReferenceIsWrappedPrimitive(t){switch(t.type){case"container":return this.containerTypeIsWrappedPrimitive(t.container);case"named":return!1;case"primitive":return!0;case"unknown":return!0;default:return!1}}containerTypeIsWrappedPrimitive(t){switch(t.type){case"list":return this.typeReferenceIsWrappedPrimitive(t.list);case"map":return this.typeReferenceIsWrappedPrimitive(t.keyType)&&this.typeReferenceIsWrappedPrimitive(t.valueType);case"nullable":return this.typeReferenceIsWrappedPrimitive(t.nullable);case"optional":return this.typeReferenceIsWrappedPrimitive(t.optional);case"set":return this.typeReferenceIsWrappedPrimitive(t.set);case"literal":return!0;default:return!1}}wrapInNullable(t){return hf.container(_b.nullable(t))}mergeIntoObjectSchema(t,r){return{...t,properties:{...r,...t.properties??{}}}}extendSubSchema(t){if(Object.entries(this.schema.properties??{}).length===0)return t;if(t.type==="object")return this.mergeIntoObjectSchema(t,this.schema.properties??{});this.context.isObjectSchemaType(t)||this.context.errorCollector.collect({message:"Received additional object properties for oneOf/anyOf that are not objects",path:this.breadcrumbs})}getDiscriminatorKeyForRef(t){return Object.entries(this.schema.discriminator?.mapping??{}).find(([r,i])=>i===t.$ref)?.[0]}};var H9n=class extends yb{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){switch(this.schema.type){case"string":{let t=this.context.getAsString(this.schema.const);if(t!=null)return hf.container(_b.literal(R9.string(t)));if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return hf.primitive({v1:hb.Date,v2:Dp.date({})});if(this.schema.format==="date-time")return hf.primitive({v1:hb.DateTime,v2:Dp.dateTime({})})}return hf.primitive({v1:"STRING",v2:Dp.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return hf.primitive({v1:"DOUBLE",v2:Dp.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return hf.primitive({v1:"FLOAT",v2:Dp.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return hf.primitive({v1:"INTEGER",v2:Dp.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return hf.primitive({v1:"LONG",v2:Dp.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return hf.primitive({v1:"UINT",v2:Dp.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return hf.primitive({v1:"UINT_64",v2:Dp.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return hf.primitive({v1:"DOUBLE",v2:Dp.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return hf.primitive({v1:"DOUBLE",v2:Dp.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return hf.primitive({v1:"FLOAT",v2:Dp.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return hf.primitive({v1:"INTEGER",v2:Dp.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return hf.primitive({v1:"LONG",v2:Dp.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return hf.primitive({v1:"UINT",v2:Dp.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return hf.primitive({v1:"UINT_64",v2:Dp.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return hf.primitive({v1:"INTEGER",v2:Dp.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"boolean":{let t=this.context.getAsBoolean(this.schema.const);return t!=null?hf.container(_b.literal(R9.boolean(t))):hf.primitive({v1:"BOOLEAN",v2:Dp.boolean({default:this.schema.default})})}default:return}}getNumberValidation(t){return{max:t.maximum,min:t.minimum,exclusiveMax:typeof t.exclusiveMaximum=="boolean"?t.exclusiveMaximum:void 0,exclusiveMin:typeof t.exclusiveMinimum=="boolean"?t.exclusiveMinimum:void 0,multipleOf:t.multipleOf}}getStringValidation(t){return{minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,format:t.format}}};var DJE=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],HAi=class e extends yb{schema;id;inlined;audiences;nameOverride;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlined:a=!1,nameOverride:u}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n,this.inlined=a,this.nameOverride=u,this.audiences=this.context.getAudiences({operation:this.schema,breadcrumbs:this.breadcrumbs})??[]}convert(){let t=this.tryConvertFernTypeDeclaration();if(t!=null)return t;let r=this.tryConvertEnumSchema();if(r!=null)return r;let i=this.tryConvertSingularAllOfSchema();if(i!=null)return i;let n=this.tryConvertPrimitiveSchema();if(n!=null)return n;let a=this.tryConvertArraySchema();if(a!=null)return a;let u=this.tryConvertTypeArraySchema();if(u!=null)return u;let l=this.tryConvertOneOfAnyOfSchema();if(l!=null)return l;let d=this.tryConvertMapSchema();if(d!=null)return d;let s=this.tryConvertObjectAllOfSchema();if(s!=null)return s;let o=this.tryConvertUntypedSchema();if(o!=null)return o;this.context.errorCollector.collect({message:`Failed to convert schema object: ${JSON.stringify(this.schema,null,2)}`,path:this.breadcrumbs})}tryConvertEnumSchema(){if(!this.schema.enum?.length)return;let r=new pH.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),n=new U9n({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,maybeFernEnum:r}).convert();if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:n.type,referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertSingularAllOfSchema(){if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&this.schema.allOf?.length===1&&this.schema.allOf[0]!=null){let r=this.context.resolveMaybeReference({schemaOrReference:this.schema.allOf[0],breadcrumbs:this.breadcrumbs});if(r!=null){let n=new e({context:this.context,breadcrumbs:[...this.breadcrumbs,"allOf","0"],schema:r,id:this.id,inlined:!0}).convert();if(n?.convertedSchema.typeDeclaration?.shape.type!=="object")return n}}if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&Array.isArray(this.schema.allOf)&&this.schema.allOf.length>=1){let r={};for(let n of this.schema.allOf??[]){if(this.context.isReferenceObject(n))return;r=mIn(r,n,(a,u)=>{if(u===n)return a;if(Array.isArray(a)&&Array.isArray(u))return[...a,...u]})}return new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,id:this.id,inlined:!0}).convert()}}tryConvertPrimitiveSchema(){let r=new H9n({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:lO.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new $9n({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:lO.alias({aliasOf:r.typeReference,resolvedType:r.typeReference}),referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertTypeArraySchema(){if(Array.isArray(this.schema.type)&&this.schema.type.length>0)return this.schema.type.length===1?this.schema.type=this.schema.type[0]:(this.schema.oneOf=this.schema.type.map(t=>({type:t})),this.schema.type=void 0),this.convert()}tryConvertOneOfAnyOfSchema(){if(this.schema.oneOf!=null||this.schema.anyOf!=null){let r=new W9n({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,inlinedTypes:{}}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertMapSchema(){if((typeof this.schema.additionalProperties=="object"||typeof this.schema.additionalProperties=="boolean")&&this.schema.additionalProperties!=null&&!this.schema.properties&&!this.schema.allOf){if(typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties===!1)return;let r=new mko({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReferenceOrBoolean:this.schema.additionalProperties}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertObjectAllOfSchema(){if(this.schema.type==="object"||this.schema.properties!=null||this.schema.allOf!=null){let r=new V9n({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:r.propertiesByAudience},inlinedTypes:r.inlinedTypes}}}tryConvertUntypedSchema(){if(this.isUntypedSchema())return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:lO.alias({aliasOf:hf.unknown(),resolvedType:hf.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new pH.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let i=FB_(r);if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:lO.alias({aliasOf:i,resolvedType:i}),referencedTypes:new Set,omitV2Examples:!0}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}createTypeDeclaration({shape:t,referencedTypes:r,omitV2Examples:i}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:r,source:void 0,inline:this.inlined,v2Examples:i?void 0:this.convertSchemaExamples()}}convertDeclaredTypeName(){return{typeId:this.id,fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(this.id),displayName:this.nameOverride}}schemaOnlyHasAllowedKeys(t){let r=[...DJE,...t];return Object.keys(this.schema).every(n=>r.includes(n))}isUntypedSchema(){return!!(this.schema&&typeof this.schema=="object"&&!("oneOf"in this.schema)&&!("anyOf"in this.schema)&&!("allOf"in this.schema)&&!("items"in this.schema)&&!("properties"in this.schema))}convertSchemaExamples(){let t={userSpecifiedExamples:{},autogeneratedExamples:{}},r=this.context.getExamplesFromSchema({schema:this.schema,breadcrumbs:this.breadcrumbs});if(r.length===0){let i=this.generateOrValidateExample({example:void 0,ignoreErrors:!0});return t.autogeneratedExamples={[`${this.id}_example_autogenerated`]:i},t}return t.userSpecifiedExamples=this.convertUserSpecifiedExamples(r),t}convertUserSpecifiedExamples(t){let r={};for(let[i,n]of t.entries()){let a=this.context.resolveExample(n),u=this.generateOrValidateExample({example:a});r[`${this.id}_example_${i}`]=u}return r}generateOrValidateExample({example:t,ignoreErrors:r}){let i=new VFe({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n,errors:a}=i.convert();return r||a.forEach(u=>{this.context.errorCollector.collect({message:u.message,path:u.path})}),n}};var SJ=class extends yb{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:i,schemaIdOverride:n,wrapAsOptional:a=!1,wrapAsNullable:u=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=i,this.schemaIdOverride=n,this.wrapAsOptional=a,this.wrapAsNullable=u}convert(){let t=this.maybeConvertReferenceObject({schemaOrReference:this.schemaOrReference});if(t!=null)return t;let r=this.maybeConvertSingularAllOfReferenceObject();return r??this.convertSchemaObject({schema:this.schemaOrReference})}maybeConvertReferenceObject({schemaOrReference:t}){if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:r.inlinedTypes??{}}}}maybeConvertSingularAllOfReferenceObject(){if(this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null||this.schemaOrReference.allOf.length!==1)return;let t=this.schemaOrReference.allOf[0];if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:{}}}}convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),i=new HAi({context:this.context,breadcrumbs:this.breadcrumbs,schema:t,id:r}),n=this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs}),a=i.convert();if(a!=null){let u=a.convertedSchema.typeDeclaration.shape;return u.type==="alias"?{type:this.wrapTypeReference(u.aliasOf),schema:a.convertedSchema,inlinedTypes:a.inlinedTypes,availability:n}:{type:this.wrapTypeReference(this.context.createNamedTypeReference(r)),schema:a.convertedSchema,inlinedTypes:{...a.inlinedTypes,[r]:a.convertedSchema},availability:n}}}wrapTypeReference(t){return this.wrapAsOptional&&this.wrapAsNullable?this.wrapInOptional(this.wrapInNullable(t)):this.wrapAsOptional?this.wrapInOptional(t):this.wrapAsNullable?this.wrapInNullable(t):t}wrapInOptional(t){return hf.container(_b.optional(t))}wrapInNullable(t){return hf.container(_b.nullable(t))}};var $9n=class e extends yb{static LIST_UNKNOWN=hf.container(_b.list(hf.unknown()));schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){if(this.schema.items!=null){Array.isArray(this.schema.items)&&(this.schema.items={oneOf:this.schema.items});let r=new SJ({context:this.context,breadcrumbs:[...this.breadcrumbs,"items"],schemaOrReference:this.schema.items}).convert();if(r!=null){let i=new Set;for(let n of r.schema?.typeDeclaration.referencedTypes??[])i.add(n);return r.inlinedTypes!=null&&Object.values(r.inlinedTypes).forEach(n=>{n.typeDeclaration.referencedTypes.forEach(a=>{i.add(a)})}),{typeReference:hf.container(_b.list(r.type)),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var Pko=class extends yb{group;method;constructor({context:t,breadcrumbs:r,group:i,method:n}){super({context:t,breadcrumbs:r}),this.group=i,this.method=n}parseMediaTypeObject({mediaTypeObject:t,resolveSchema:r,contentType:i,schemaId:n}){if(t.schema==null)return;if(r){let d=this.context.resolveMaybeReference({schemaOrReference:t.schema,breadcrumbs:[...this.breadcrumbs,"content",i]});if(d==null)return;t.schema=d}let u=new SJ({context:this.context,breadcrumbs:[...this.breadcrumbs,"content",i,"schema"],schemaOrReference:t.schema,schemaIdOverride:n}).convert();if(u==null)return;let l=t.examples!=null?Object.fromEntries(Object.entries(t.examples).map(([d,s])=>{if(this.context.isReferenceObject(s)){let o=this.context.resolveReference({reference:s,breadcrumbs:[...this.breadcrumbs,"content",i,"examples"],skipErrorCollector:!0});return o.resolved?[d,o.value]:null}return[d,s]}).filter(d=>d!=null)):void 0;return{...u,examples:l}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let n=new SJ({context:this.context,breadcrumbs:[...this.breadcrumbs],schemaOrReference:t,schemaIdOverride:r}).convert();if(n!=null)return{...n,examples:void 0}}convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:r,exampleGenerationStrategy:i}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},a=t?.schema,u=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`});for(let[l,d]of u){let s=this.context.resolveExampleWithValue(d),o=this.context.isExampleWithSummary(d)?d.summary:l;s!=null&&(a!=null?n.userSpecifiedExamples[o]=this.generateOrValidateExample({schema:a,example:s,exampleGenerationStrategy:i}):n.userSpecifiedExamples[o]=s)}if(Object.keys(n.userSpecifiedExamples).length===0&&a!=null){let l=T_(`${[...this.group,this.method].join("_")}_example`);n.autogeneratedExamples[l]=this.generateOrValidateExample({schema:a,example:void 0,ignoreErrors:!0,generateOptionalProperties:r,exampleGenerationStrategy:i})}return n}generateOrValidateExample({schema:t,example:r,ignoreErrors:i,generateOptionalProperties:n,exampleGenerationStrategy:a}){let u=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(u==null)return;let l=this.context.getExamplesFromSchema({schema:u,breadcrumbs:this.breadcrumbs}),d=new VFe({breadcrumbs:this.breadcrumbs,context:this.context,schema:u,example:r??l[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:a}),{validExample:s,errors:o}=d.convert();return i||o.forEach(c=>{this.context.errorCollector.collect({message:c.message,path:c.path})}),s}};var jko=class extends yb{parameter;constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r}),this.parameter=i}convertToOutput({schema:t,typeReference:r,inlinedTypes:i}){let n=this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs}),a=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs}),u=this.getParameterSchemaWithExampleOverride({schema:a});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??yb.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,v2Examples:this.convertParameterExamples({schema:u??t}),availability:n},inlinedTypes:i};case"header":return{type:"header",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??yb.OPTIONAL_STRING,env:void 0,v2Examples:this.convertParameterExamples({schema:u??t}),availability:n},inlinedTypes:i};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:this.parameter.description,valueType:r??yb.STRING,location:"ENDPOINT",variable:void 0,v2Examples:this.convertParameterExamples({schema:u??t})},inlinedTypes:i};default:return}}getParameterSchemaWithExampleOverride({schema:t}){if(t!=null)return t.type==="string"&&t.example==null?{...t,example:this.parameter.name}:t}convertParameterExamples({schema:t}){let r={userSpecifiedExamples:{},autogeneratedExamples:{}},i=this.parameter.example,n=this.parameter.examples;for(let[a,u]of Object.entries(n??{})){let l=this.context.resolveExampleWithValue(u);l!=null&&(r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:l}))}if(i!=null){let a=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(r.userSpecifiedExamples)});r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:i})}if(Object.keys(r.userSpecifiedExamples).length===0){let a=`${this.parameter.name}_example`;r.autogeneratedExamples[a]=this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0})}return r}generateOrValidateExample({schema:t,ignoreErrors:r,example:i}){let n=new VFe({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:i}),{validExample:a,errors:u}=n.convert();return r||u.forEach(l=>{this.context.errorCollector.collect({message:l.message,path:l.path})}),a}};var wko=class extends Pm{server;key="x-fern-server-name";constructor({breadcrumbs:t,server:r,context:i}){super({breadcrumbs:t,context:i}),this.server=r}convert(){let t=this.getExtensionValue(this.server,"x-name");if(!(t==null||typeof t!="string"))return t}};var LB_="Base",LMe=class e extends yb{servers;endpointLevelServers;constructor({breadcrumbs:t,context:r,servers:i,endpointLevelServers:n}){super({breadcrumbs:t,context:r}),this.servers=i,this.endpointLevelServers=n}convert(){if(this.servers==null||this.servers.length===0||this.servers[0]==null)return;if(this.endpointLevelServers!=null&&this.endpointLevelServers.length>0){let r=this.getDefaultBaseUrlName(),i={id:r,name:this.context.casingsGenerator.generateName(r)},n=this.endpointLevelServers.map(l=>{let d=e.getServerName({server:l,context:this.context});return{id:d,name:this.context.casingsGenerator.generateName(d)}}).filter((l,d,s)=>s.findIndex(o=>o.id===l.id)===d),a=[i,...n],u=this.servers.map(l=>{let d=e.getServerName({server:l,context:this.context}),s=this.endpointLevelServers?.map(o=>[e.getServerName({server:o,context:this.context}),this.getServerUrl(o)]);return{id:d,name:this.context.casingsGenerator.generateName(d),urls:{[r]:this.getServerUrl(l),...Object.fromEntries(s??[])},docs:l.description}});return{value:{defaultEnvironment:u[0]?.id,environments:cx.multipleBaseUrls({baseUrls:a,environments:u})},defaultUrl:i.id}}let t=this.withExplodedServers(this.servers).map(r=>{let i=e.getServerName({server:r,context:this.context});return{id:i,name:this.context.casingsGenerator.generateName(i),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(r)),docs:r.description}}).filter(V0);return{value:{defaultEnvironment:t[0]?.id,environments:cx.singleBaseUrl({environments:t})},defaultUrl:t[0]?.id}}static getServerExtensionName({server:t,context:r}){return new wko({breadcrumbs:[],server:t,context:r}).convert()}static getServerName({server:t,context:r}){return t.name!=null?t.name:e.getServerExtensionName({server:t,context:r})??t.description??t.url}getServerUrl(t){if(t.variables==null)return t.url;let r=t.url;for(let[i,n]of Object.entries(t.variables))n.default!=null&&(r=r.replace(`{${i}}`,encodeURIComponent(n.default)));return r}withExplodedServers(t){return t.flatMap(r=>{if(r.variables==null)return[r];let i=Object.entries(r.variables).filter(([l,d])=>d.enum!=null&&d.enum.length>0);if(i.length===0)return[r];let n=i[0];if(n==null)return[r];let[a,u]=n;return u.enum==null?[r]:u.enum.map(l=>{let d=r.url.replace(`{${a}}`,encodeURIComponent(l)),s={};for(let[c,b]of Object.entries(r.variables??{}))c!==a&&(s[c]=b);let o={...r,url:d,variables:Object.keys(s).length>0?s:void 0,"x-fern-server-name":r.description?`${r.description}_${l}`:`${l}`,description:r.description};return this.withExplodedServers([o])[0]})}).filter(V0)}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?LB_:e.getServerExtensionName({server:this.servers[0],context:this.context})??LB_}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}};var xRa={400:"BadRequestError",401:"UnauthorizedError",402:"PaymentRequiredError",403:"ForbiddenError",404:"NotFoundError",405:"MethodNotAllowedError",406:"NotAcceptableError",407:"ProxyAuthenticationRequiredError",408:"RequestTimeoutError",409:"ConflictError",410:"GoneError",411:"LengthRequiredError",412:"PreconditionFailedError",413:"ContentTooLargeError",414:"URITooLongError",415:"UnsupportedMediaTypeError",416:"RangeNotSatisfiableError",417:"ExpectationFailedError",418:"ImATeapotError",419:"AuthenticationTimeoutError",420:"MethodFailureError",421:"MisdirectedRequestError",422:"UnprocessableEntityError",423:"LockedError",424:"FailedDependencyError",425:"TooEarlyError",426:"UpgradeRequiredError",428:"PreconditionError",429:"TooManyRequestsError",430:"RequestHeaderFieldsTooLargeError",431:"RequestHeaderFieldsTooLargeError",444:"NoResponseError",449:"RetryWithError",450:"BlockedByWindowsParentalControlsError",451:"UnavailableForLegalReasonsError",498:"InvalidTokenError",499:"ClientClosedRequestError",500:"InternalServerError",501:"NotImplementedError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError",505:"HTTPVersionNotSupportedError",506:"VariantAlsoNegotiatesError",507:"InsufficientStorageError",508:"LoopDetectedError",509:"BandwidthLimitExceededError",510:"NotExtendedError",511:"NetworkAuthenticationRequiredError"},EJE=new Set(Object.values(xRa));var MJE=hu.object({type:hu.string(),channelId:hu.string().optional(),messageId:hu.string(),value:hu.any()}),AJE=hu.object({summary:hu.string().optional(),description:hu.string().optional(),"query-parameters":hu.record(hu.string()).optional(),headers:hu.record(hu.string()).optional(),messages:hu.array(MJE)}),UB_=hu.array(AJE);var Sko=class extends Pm{channel;key="x-fern-examples";constructor({breadcrumbs:t,channel:r,context:i}){super({breadcrumbs:t??[],context:i}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(t==null)return;let r=UB_.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-examples extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data.map(i=>({summary:i.summary,description:i.description,queryParameters:i["query-parameters"],headers:i.headers,messages:i.messages.map(n=>({type:n.type,channelId:n.channelId,messageId:n.messageId,value:n.value}))}))}};var G9n=class extends yb{channel;channelPath;inlinedTypes={};websocketGroup;constructor({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a}){super({context:t,breadcrumbs:r}),this.websocketGroup=i,this.channel=n,this.channelPath=a}convertExamples({fullPath:t,baseUrl:r,asyncApiVersion:i}){let a=new Sko({context:this.context,breadcrumbs:this.breadcrumbs,channel:this.channel}).convert();return a==null?{}:Object.fromEntries(a.map((u,l)=>[l.toString(),{channel:{method:"GET",path:t},baseUrl:t,environment:r,auth:void 0,pathParameters:{},queryParameters:u.queryParameters,headers:u.headers,messages:u.messages.map(d=>({type:i==="v2"?d.type:d.messageId,body:d.value}))}]))}transformToValidPath(t){return t.startsWith("/")?t:"/"+t}};var $Ai=class extends TM.AbstractConverters.AbstractParameterConverter{parameterNamePrefix;constructor({context:t,breadcrumbs:r,parameter:i,parameterNamePrefix:n}){super({context:t,breadcrumbs:r,parameter:i}),this.parameterNamePrefix=n}convert(){let t,r={},n=new pH.FernOptionalExtension({breadcrumbs:this.breadcrumbs,parameter:this.parameter,context:this.context}).convert()??this.parameter.required===!1,a=this.parameter.schema??{...this.parameter,type:"string",enum:this.parameter.enum,default:this.parameter.default,example:this.parameter.example??this.parameter.name,examples:Object.values(this.parameter.examples??{}),deprecated:this.parameter.deprecated,required:void 0},l=new TM.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaIdOverride:this.parameterNamePrefix?`${this.parameterNamePrefix}_${this.parameter.name}`:this.parameter.name,schemaOrReference:a,wrapAsOptional:n}).convert();return l!=null&&(t=l.type,r=l.inlinedTypes??{}),this.convertToOutput({schema:a,typeReference:t,inlinedTypes:r})}};var Dko=class extends Pm{channel;key="x-fern-address";constructor({breadcrumbs:t,channel:r,context:i}){super({breadcrumbs:t,context:i}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(!(t==null||typeof t!="string"))return t}};var Q9n=class extends Pm{channel;key="x-fern-display-name";constructor({breadcrumbs:t,channel:r,context:i}){super({breadcrumbs:t,context:i}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(!(t==null||typeof t!="string"))return t}};var Eko=class extends G9n{inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a}){super({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a})}convert(){let t=[],r=[],i=[],a=new Q9n({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".");this.channel.parameters&&this.convertPathParameters({context:this.context,pathParameters:t}),this.channel.bindings?.ws!=null&&(this.convertHeaders({context:this.context,headers:i}),this.convertBindingQueryParameters({context:this.context,queryParameters:r}));let u;this.channel.subscribe!=null&&(u=this.convertMessage({context:this.context,operation:this.channel.subscribe,origin:"server"}));let l;this.channel.publish!=null&&(l=this.convertMessage({context:this.context,operation:this.channel.publish,origin:"client"}));let d=[];u!=null&&d.push(u),l!=null&&d.push(l);let o=new Dko({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert(),c=this.transformToValidPath(o??this.channelPath),b=this.channel.servers?.[0]??Object.keys(this.context.spec.servers??{})[0],g=fF(c),O=T_(this.channelPath),m=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[];return{channel:{name:this.context.casingsGenerator.generateName(O),displayName:a,baseUrl:b,path:g,auth:!1,headers:i,queryParameters:r,pathParameters:t,messages:d,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:c,baseUrl:b,asyncApiVersion:"v2"})}},audiences:m,inlinedTypes:this.inlinedTypes}}convertMessage({context:t,operation:r,origin:i}){let n,a=i==="server"?"subscribe":"publish",u=[...this.breadcrumbs,a],l=t.resolveMaybeReference({schemaOrReference:r.message,breadcrumbs:u});l!=null&&(r.message=l);let d=TVi(T_(`${this.channelPath}_${a}`)).replace(/ /g,"");if("oneOf"in r.message){let o=new TM.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:u,schemaOrReference:r.message,schemaIdOverride:d}).convert();o!=null&&o.schema!=null&&(n=o.schema,this.inlinedTypes={...this.inlinedTypes,...o.inlinedTypes})}else if(t.isMessageWithPayload(r.message)){let s=t.resolveMaybeReference({schemaOrReference:r.message.payload,breadcrumbs:u});if(s!=null){let c=new TM.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:u,schemaOrReference:s,schemaIdOverride:d}).convert();c!=null&&c.schema!=null&&(n=c.schema,this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes})}}if(n!=null){let s=n,o=hf.named({fernFilepath:t.createFernFilepath(),name:s.typeDeclaration.name.name,typeId:s.typeDeclaration.name.typeId,displayName:void 0,default:void 0,inline:!1}),c=N9.reference({bodyType:o,docs:r.description}),b=i==="server"?"subscribe":"publish";return{type:b,displayName:b,origin:i,body:c,availability:t.getAvailability({node:r,breadcrumbs:this.breadcrumbs}),docs:r.description}}}convertPathParameters({context:t,pathParameters:r}){for(let[i,n]of Object.entries(this.channel.parameters??{})){let a=t.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs});if(a==null)continue;let l=new $Ai({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...a,name:i,in:"path",description:a.description,required:a.required??!0}}).convert();l!=null&&(this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes},l.type==="path"&&r.push(l.parameter))}}convertHeaders({context:t,headers:r}){if(this.channel.bindings?.ws?.headers!=null){let i=this.channel.bindings.ws.headers.required??[];for(let[n,a]of Object.entries(this.channel.bindings.ws.headers.properties??{})){let u=t.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,n]});if(u==null)continue;let d=new $Ai({context:this.context,breadcrumbs:[...this.breadcrumbs,n],parameter:{name:n,in:"header",required:i.includes(n),schema:u,description:"description"in u?u.description:void 0}}).convert();d!=null&&d.type==="header"&&(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},r.push(d.parameter))}}}convertBindingQueryParameters({context:t,queryParameters:r}){if(this.channel.bindings?.ws?.query!=null){let i=this.channel.bindings.ws.query.required??[];for(let[n,a]of Object.entries(this.channel.bindings.ws.query.properties??{})){let u=t.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,n]});if(u==null)continue;let d=new $Ai({context:this.context,breadcrumbs:[...this.breadcrumbs,n],parameter:{name:n,in:"query",required:i.includes(n),schema:u,description:"description"in u?u.description:void 0,deprecated:u.deprecated??!1}}).convert();d!=null&&d.type==="query"&&(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},r.push(d.parameter))}}}};var J9n=class extends yb{servers;constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r}),this.servers=i}convert(){if(this.servers==null||Object.keys(this.servers).length===0)return;let t=[],r;for(let[i,n]of Object.entries(this.servers)){let a=this.buildSingleBaseUrlEnvironment(this.context,i,n);t.push(a),r==null&&(r=a.id)}return{defaultEnvironment:r,environments:cx.singleBaseUrl({environments:t})}}constructServerUrl(t,r){return r.includes("://")?r:`${t}://${r}`}};var Mko=class extends J9n{constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r,servers:i})}buildSingleBaseUrlEnvironment(t,r,i){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(i.protocol,i.url),docs:void 0}}};var njc="$message.",VB_="#/channels/",WB_="#/servers/",Ako=class extends G9n{operations;inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a,operations:u}){super({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a}),this.operations=u}convert(){let t=[],r=[],i=[],a=new Q9n({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".")??this.channelPath;this.channel.parameters&&this.convertChannelParameters({pathParameters:t,queryParameters:r,headers:i,channelPath:this.channelPath});let u=Object.entries(this.operations).reduce((b,[g,O])=>{try{this.getChannelPathFromOperation(O)===this.channelPath&&(b[g]=O)}catch{}return b},{}),l=[];for(let[b,g]of Object.entries(u))for(let O of g.messages){let m=this.context.convertReferenceToTypeReference({reference:O});if(m.ok){let P=N9.reference({bodyType:m.reference,docs:g.description});l.push({type:b,displayName:b,origin:g.action==="send"?"client":"server",body:P,availability:this.context.getAvailability({node:g,breadcrumbs:this.breadcrumbs}),docs:g.description})}}let d=this.resolveChannelServersFromReference(this.channel.servers??[])??Object.keys(this.context.spec.servers??{})[0],s=this.transformToValidPath(this.channel.address??this.channelPath),o=fF(s),c=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[];return{channel:{name:this.context.casingsGenerator.generateName(a),displayName:a,baseUrl:d,path:o,auth:!1,headers:i,queryParameters:r,pathParameters:t,messages:l,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:s,baseUrl:d,asyncApiVersion:"v3"})}},audiences:c,inlinedTypes:this.inlinedTypes}}convertChannelParameters({pathParameters:t,queryParameters:r,headers:i,channelPath:n}){for(let a of Object.values(this.channel.parameters??{})){let u=this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,"parameters"]});if(u==null)continue;let l=this.convertChannelParameterLocation(u.location);if(l==null)continue;let{type:d,parameterKey:s}=l,c=new $Ai({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...u,name:s,in:d},parameterNamePrefix:this.channelPath}).convert();if(c!=null)switch(this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes},c.type){case"path":t.push(c.parameter);break;case"query":r.push(c.parameter);break;case"header":i.push(c.parameter);break}}}convertChannelParameterLocation(t){try{let[r,i]=t.split("#/");if(r==null||i==null){this.context.errorCollector.collect({message:`Invalid location format: ${t}; unable to parse message type and parameter key`,path:this.breadcrumbs});return}if(!r.startsWith(njc)){this.context.errorCollector.collect({message:`Invalid location format: ${t}; expected ${njc} prefix`,path:this.breadcrumbs});return}let n=r.substring(njc.length);if(n!=="header"&&n!=="path"&&n!=="payload"){this.context.errorCollector.collect({message:`Invalid message type: ${n}. Must be one of: header, path, payload`,path:this.breadcrumbs});return}return n==="payload"?{type:"query",parameterKey:i}:{type:n,parameterKey:i}}catch{this.context.errorCollector.collect({message:`Invalid location format: ${t}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`,path:this.breadcrumbs});return}}resolveChannelServersFromReference(t){if(t==null||t.length===0||t[0]==null)return;let r=t[0];if(!r.$ref.startsWith(WB_)){this.context.errorCollector.collect({message:`Failed to resolve server name from server ref ${r.$ref}`,path:this.breadcrumbs});return}let i=r.$ref.substring(WB_.length);if(i==null){this.context.errorCollector.collect({message:`Failed to find server with name ${i}`,path:this.breadcrumbs});return}return i}getChannelPathFromOperation(t){if(!t.channel.$ref.startsWith(VB_))throw new Error(`Failed to resolve channel path from operation ${t.channel.$ref}`);return t.channel.$ref.substring(VB_.length)}};var qko=class extends J9n{constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r,servers:i})}buildSingleBaseUrlEnvironment(t,r,i){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(i.protocol,i.host),docs:void 0}}};var RRa=class extends qpi{constructor({context:t,breadcrumbs:r,audiences:i}){super({context:t,breadcrumbs:r,audiences:i})}async convert(){return this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec}),this.isAsyncAPIV3(this.context)?this.convertChannelMessages():this.convertComponentMessages(),this.convertSchemas(),this.convertServers(),this.convertChannels(),this.finalizeIr()}isAsyncAPIV3(t){return parseFloat(t.spec.asyncapi)>=3}convertChannelMessages(){let t=this.context.spec;for(let[r,i]of Object.entries(t.channels??{}))for(let[n,a]of Object.entries(i.messages??{})){if(!this.context.isMessageWithPayload(a)&&!this.context.isReferenceObject(a))continue;let u=["channels",r,"messages",n],l=this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:u});if(!this.context.isMessageWithPayload(l))continue;let d=this.context.resolveMaybeReference({schemaOrReference:l.payload,breadcrumbs:u});if(d==null)continue;let s=`${r}_${n}`;this.convertSchema({id:s,breadcrumbs:u,schema:d})}}convertComponentMessages(){for(let[t,r]of Object.entries(this.context.spec.components?.messages??{})){if(r.payload==null)continue;let i=["components","messages",t],n=this.context.resolveMaybeReference({schemaOrReference:r.payload,breadcrumbs:i});n!=null&&this.convertSchema({id:t,breadcrumbs:i,schema:n})}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{}))this.convertSchema({id:t,breadcrumbs:["components","schemas",t],schema:r})}convertSchema({id:t,breadcrumbs:r,schema:i}){let a=new TM.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:r,schema:i}).convert();a!=null&&(this.addTypeToRootPackage(t),this.addTypesToIr({...a.inlinedTypes,[t]:a.convertedSchema}))}convertServers(){let t;if(this.isAsyncAPIV3(this.context)){let r=this.context.spec.servers;t=new qko({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}else{let r=this.context.spec.servers;t=new Mko({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}this.addEnvironmentsToIr({environmentConfig:t})}convertChannels(){for(let[t,r]of Object.entries(this.context.spec.channels??{})){let n=new pH.SdkGroupNameExtension({breadcrumbs:["channels",t],operation:r,context:this.context}).convert()?.groups,a;if(this.isAsyncAPIV3(this.context)){let l=this.context.spec.operations??{};a=new Ako({context:this.context,breadcrumbs:["channels",t],websocketGroup:n,channel:r,channelPath:t,operations:l}).convert()}else a=new Eko({context:this.context,breadcrumbs:["channels",t],websocketGroup:n,channel:r,channelPath:t}).convert();a!=null&&(this.addWebsocketChannelToIr({websocketChannel:a.channel,channelPath:t,audiences:a.audiences,websocketGroup:n}),this.addTypesToIr(a.inlinedTypes))}}};var NRa=class extends f8{isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}getTypeIdFromMessageReference(t){let r=t.$ref.match(/\/messages\/(.+)$/);if(!(!r||!r[1]))return r[1]}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n}){let a,u=t.$ref.match(/^.*\/schemas\/(.+)$/),l=t.$ref.match(/^.*\/channels\/([^/]+)\/messages\/(.+)$/),d=t.$ref.match(/^.*\/messages\/(.+)$/);if(u&&u[1])return a=u[1],this.convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a});if(l&&l[2]){let s=l[1],o=l[2];return a=`${s}_${o}`,this.convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a})}else return d&&d[1]?(a=d[1],this.convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a})):{ok:!1}}convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a}){let u=this.resolveReference({reference:t,breadcrumbs:r});if(!u.resolved)return{ok:!1};let l;return n==="reference_identifier"?l=i??u.value.title:(n==="discriminator_key"||n==="schema_identifier")&&(l=u.value.title??i),{ok:!0,reference:hf.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(a),typeId:a,displayName:l,default:void 0,inline:!1})}}convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a}){let u=this.resolveReference({reference:t,breadcrumbs:r});if(!u.resolved)return{ok:!1};let l;return n==="reference_identifier"?l=i??u.value.name:(n==="discriminator_key"||n==="schema_identifier")&&(l=u.value.name??i),{ok:!0,reference:hf.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(a),typeId:a,displayName:l,default:void 0,inline:!1})}}convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a}){let u=this.resolveReference({reference:t,breadcrumbs:r});if(!u.resolved)return{ok:!1};let l;return n==="reference_identifier"?l=i??u.value.messageId??u.value.name:(n==="discriminator_key"||n==="schema_identifier")&&(l=u.value.messageId??u.value.name??i),{ok:!0,reference:hf.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(a),typeId:a,displayName:l,default:void 0,inline:!1})}}};var JB_=ci(ajc(),1);var Tko=class extends Pm{document;key="x-fern-global-headers";constructor({breadcrumbs:t,document:r,context:i}){super({breadcrumbs:t,context:i}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected non-array value for x-fern-global-headers",path:this.breadcrumbs});return}return t}}};function HB_({globalHeaders:e,context:t}){return e.map(r=>({name:t.casingsGenerator.generateNameAndWireValue({name:r.name??"",wireValue:r.header}),valueType:r.optional?yb.OPTIONAL_STRING:yb.STRING,env:r.env,v2Examples:r.optional?void 0:CJE({header:r,context:t}),availability:void 0,docs:void 0}))}function CJE({header:e,context:t}){let r=new VFe({breadcrumbs:[],context:t,schema:{type:"string"},example:e.header}),{validExample:i}=r.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{globalHeaderExample:i}}}var sjc=ci(ajc(),1);var $B_=["get","post","put","delete","patch","head"];var Cko=class extends Pm{operation;key="x-fern-idempotent";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-idempotent",path:this.breadcrumbs});return}return t}}};var BJE=hu.object({cursor:hu.string(),next_cursor:hu.string(),results:hu.string()}),IJE=hu.object({offset:hu.string(),results:hu.string(),step:hu.string().optional(),"has-next-page":hu.string().optional()}),ojc=hu.union([hu.boolean(),BJE,IJE]);var ujc="$request.",Bko="$response.",Iko=class extends Pm{operation;document;key="x-fern-pagination";constructor({breadcrumbs:t,operation:r,document:i,context:n}){super({breadcrumbs:t,context:n}),this.operation=r,this.document=i}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=ojc.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean"){let i=this.getExtensionValue(this.document);if(i==null)return;if(typeof i=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.",path:this.breadcrumbs});return}let n=ojc.safeParse(i);if(!n.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${n.error.message}`,path:this.breadcrumbs});return}if(typeof n.data=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:n.data})}if(typeof r.data=="boolean"){this.context.errorCollector.collect({message:"Pagination extension is a boolean with no global configuration.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:r.data})}convertPaginationConfig({config:t}){let r=t;if("cursor"in r)return{type:"cursor",cursor:f8.maybeTrimPrefix(r.cursor,ujc),nextCursor:f8.maybeTrimPrefix(r.next_cursor,Bko),results:f8.maybeTrimPrefix(r.results,Bko)};let i=t;return{type:"offset",offset:f8.maybeTrimPrefix(i.offset,ujc),results:f8.maybeTrimPrefix(i.results,Bko),step:i.step!=null?f8.maybeTrimPrefix(i.step,ujc):void 0,hasNextPage:i["has-next-page"]!=null?f8.maybeTrimPrefix(i["has-next-page"],Bko):void 0}}};var zJE="$request.",xJE=hu.object({"stream-condition":hu.string().optional(),format:hu.enum(["sse","json"]).optional(),"stream-description":hu.string().optional(),"response-stream":hu.any(),response:hu.any()}),RJE=hu.union([hu.boolean(),xJE]),zko=class extends Pm{operation;key="x-fern-streaming";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=RJE.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-streaming extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean")return r.data?{type:"stream",format:"json"}:void 0;if(r.data["stream-condition"]==null&&r.data.format!=null)return{type:"stream",format:r.data.format};if(r.data["stream-condition"]==null){this.context.errorCollector.collect({message:"Missing stream-condition property without specified format.",path:this.breadcrumbs});return}return{type:"streamCondition",format:r.data.format??"json",streamDescription:r.data["stream-description"],streamConditionProperty:f8.maybeTrimPrefix(r.data["stream-condition"],zJE),responseStream:r.data["response-stream"],response:r.data.response}}};var xko=class extends Pm{operation;key="x-fern-webhook";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-webhook",path:this.breadcrumbs});return}return t}}};var Rko=class extends Pm{operation;key="x-fern-examples";constructor({context:t,breadcrumbs:r,operation:i}){super({breadcrumbs:r,context:t}),this.operation=i}convert(){let t=this.getExtensionValue(this.operation);return t==null?void 0:(Array.isArray(t)?t:[]).filter(n=>{let a=JN.serialization.ExampleEndpointCallSchema.parse(n);return a.ok||this.context.errorCollector.collect({message:`Failed to parse x-fern-example in ${this.breadcrumbs.join(".")}`,path:this.breadcrumbs}),a.ok})}};var Nko=class extends TM.AbstractConverters.AbstractMediaTypeObjectConverter{responseBody;statusCode;streamingExtension;constructor({context:t,breadcrumbs:r,responseBody:i,group:n,method:a,statusCode:u,streamingExtension:l}){super({context:t,breadcrumbs:r,group:n,method:a}),this.responseBody=i,this.statusCode=u,this.streamingExtension=l}convert(){return this.shouldConvertAsStreaming()?this.convertStreamingResponseBody():this.convertNonStreamingResponseBody()}convertStreamingResponseBody(){if(this.streamingExtension!=null){if(this.streamingExtension.type=="streamCondition"){let t=this.streamingExtension.responseStream,r=this.streamingExtension.response,i=[...this.group,this.method,"Response",this.statusCode].join("_"),n=`${i}_streaming`,a=this.parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:n}),u=this.parseMediaTypeSchemaOrReference({schemaOrReference:r,schemaId:i});return this.convertStreamConditionResponse({convertedStreamingSchema:a,convertedNonStreamingSchema:u})}if(this.streamingExtension.type==="stream"){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{});for(let i of r){let n=this.responseBody.content?.[i];if(n==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:n,schemaId:t,contentType:this.streamingExtension.format});if(a!=null)return this.convertStreamingResponse({mediaTypeObject:n,convertedSchema:a})}}}}convertNonStreamingResponseBody(){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{}).filter(n=>n.includes("json"));for(let n of r){let a=this.responseBody.content?.[n];if(a==null)continue;let u=this.parseMediaTypeObject({mediaTypeObject:a,schemaId:t,contentType:n});if(u!=null&&this.shouldReturnJsonResponse(n))return this.returnJsonResponse({mediaTypeObject:a,convertedSchema:u})}let i=Object.keys(this.responseBody.content??{}).filter(n=>!n.includes("json"));for(let n of i){let a=this.responseBody.content?.[n];if(a==null)continue;let u=this.parseMediaTypeObject({mediaTypeObject:a,schemaId:t,contentType:n});if(u!=null){if(this.isBinarySchema(u))return this.shouldReturnBytesResponse()?this.returnBytesResponse({mediaTypeObject:a}):this.returnFileDownloadResponse({mediaTypeObject:a});if(this.shouldReturnTextResponse(n))return this.returnTextResponse({mediaTypeObject:a})}}}convertStreamConditionResponse({convertedStreamingSchema:t,convertedNonStreamingSchema:r}){if(!(t==null||r==null))return{responseBody:NS.json(IQ.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:r.schema?.typeDeclaration.v2Examples})),streamResponseBody:NS.streaming(x9.json({docs:this.responseBody.description,payload:t.type,terminator:void 0,v2Examples:t.schema?.typeDeclaration.v2Examples})),inlinedTypes:{...t.inlinedTypes,...r.inlinedTypes}}}convertStreamingResponse({mediaTypeObject:t,convertedSchema:r}){if(this.streamingExtension==null)return;switch(this.streamingExtension.format){case"json":return{responseBody:NS.streaming(x9.json({docs:this.responseBody.description,payload:r.type,terminator:void 0,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples};case"sse":return{responseBody:NS.streaming(x9.sse({docs:this.responseBody.description,payload:r.type,terminator:void 0,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples};default:return}}returnJsonResponse({mediaTypeObject:t,convertedSchema:r}){return{responseBody:NS.json(IQ.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples}}returnBytesResponse({mediaTypeObject:t}){return{responseBody:NS.bytes({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{}}}returnFileDownloadResponse({mediaTypeObject:t}){return{responseBody:NS.fileDownload({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{}}}returnTextResponse({mediaTypeObject:t}){return{responseBody:NS.text({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{}}}isBinarySchema(t){let r=t.type;switch(r.type){case"container":case"named":case"unknown":return!1;case"primitive":return r.primitive.v2==null?!1:r.primitive.v2.type==="string"&&r.primitive.v2.validation?.format==="binary";default:return!1}}shouldConvertAsStreaming(){return this.streamingExtension!=null}shouldReturnJsonResponse(t){return t.includes("json")}shouldReturnBytesResponse(){return this.context.settings.useBytesForBinaryResponse&&this.streamingExtension==null}shouldReturnTextResponse(t){return mM.parse(t)?.isText()??!1}};var Fko=class extends TM.AbstractConverters.AbstractMediaTypeObjectConverter{responseError;statusCode;methodName;constructor({context:t,breadcrumbs:r,responseError:i,group:n,method:a,methodName:u,statusCode:l}){super({context:t,breadcrumbs:r,group:n,method:a}),this.responseError=i,this.statusCode=l,this.methodName=u}convert(){if(!this.responseError.content){let i=xRa[this.statusCode];if(i==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}let n=this.getErrorIdFromErrorName(i);return{error:{error:{name:this.context.casingsGenerator.generateName(n),fernFilepath:{allParts:[],packagePath:[],file:void 0},errorId:n},docs:this.responseError.description},errorType:hf.unknown(),displayName:i,statusCode:this.statusCode,inlinedTypes:{},examples:{}}}let t=Object.keys(this.responseError.content).filter(i=>i.includes("json")),r=xRa[this.statusCode];if(r==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}for(let i of[...t]){let n=this.responseError.content?.[i];if(n==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:n,schemaId:GB_(`${this.methodName}Request${r}`),contentType:i});if(a==null)continue;let u=this.getErrorIdFromErrorName(r);if(a.schema!=null)return this.constructErrorConverterOutput({errorName:r,errorId:u,fernFilepath:a.schema.typeDeclaration.name.fernFilepath,convertedSchema:a});if(a.type.type==="named")return this.constructErrorConverterOutput({errorName:r,errorId:u,fernFilepath:a.type.fernFilepath,convertedSchema:a})}}constructErrorConverterOutput({errorName:t,errorId:r,fernFilepath:i,convertedSchema:n}){return{error:{error:{name:this.context.casingsGenerator.generateName(r),fernFilepath:i,errorId:r},docs:this.responseError.description},errorType:n.type,displayName:t,statusCode:this.statusCode,inlinedTypes:n.inlinedTypes,examples:n.examples}}getErrorIdFromErrorName(t){return this.context.enableUniqueErrorsPerEndpoint?GB_(`${this.methodName}Request${t}`):t}};function GB_(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}var Lko=class extends TM.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r,parameter:i})}convert(){let t,r={};if(this.parameter.schema!=null){let i=this.context.convertBreadcrumbsToName([...this.breadcrumbs,this.parameter.name]),a=new TM.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,this.parameter.name,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required,schemaIdOverride:i}).convert();a!=null&&(t=a.type,r=a.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}};var Uko=class extends TM.AbstractConverters.AbstractMediaTypeObjectConverter{requestBody;schemaId;streamingExtension;constructor({context:t,breadcrumbs:r,requestBody:i,group:n,method:a,streamingExtension:u}){super({context:t,breadcrumbs:r,group:n,method:a}),this.requestBody=i,this.schemaId=[...this.group,this.method,"Request"].join("_"),this.streamingExtension=u}convert(){if(this.requestBody.content)return this.streamingExtension?.type=="streamCondition"?this.convertStreamConditionRequestBody():this.convertNonStreamConditionRequestBody()}convertStreamConditionRequestBody(){let t=this.getOrderedJsonOrFormContentTypes();for(let r of t){let i=this.handleStreamConditionJsonOrFormContent({contentType:r});if(i!=null)return i}}convertNonStreamConditionRequestBody(){let t=this.getOrderedJsonOrFormContentTypes();for(let n of t){let a=this.handleJsonOrFormContent({contentType:n});if(a!=null)return a}let r=Object.keys(this.requestBody.content).filter(n=>mM.parse(n)?.isMultipart());for(let n of r){let a=this.handleMultipartContent({contentType:n});if(a!=null)return a}let i=Object.keys(this.requestBody.content).filter(n=>mM.parse(n)?.isOctetStream());for(let n of i){let a=this.handleOctetStreamContent({contentType:n});if(a!=null)return a}}getOrderedJsonOrFormContentTypes(){let t=Object.keys(this.requestBody.content).filter(n=>mM.parse(n)?.isJSON()),r=Object.keys(this.requestBody.content).filter(n=>mM.parse(n)?.isURLEncoded()),i=Object.keys(this.requestBody.content).filter(n=>mM.parse(n)?.isPlainText());return[...t,...r,...i]}handleJsonOrFormContent({contentType:t}){let r=this.requestBody.content[t];if(r==null)return;let i=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});if(i==null)return;let n=i.schema?.typeDeclaration.shape;return n?.type==="object"?{requestBody:pC.inlinedRequestBody({contentType:t,docs:this.requestBody.description,name:this.context.casingsGenerator.generateName(this.schemaId),extendedProperties:n.extendedProperties,extends:n.extends,properties:n.properties,extraProperties:n.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:i.inlinedTypes})}:{requestBody:pC.reference({contentType:t,docs:this.requestBody.description,requestBodyType:i.type,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:i.inlinedTypes??{}}}handleMultipartContent({contentType:t}){let r=this.requestBody.content[t];if(r==null||r.schema==null)return;let i=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,resolveSchema:!0,contentType:t});if(i==null)return;let n=i.schema?.typeDeclaration.shape;if(n?.type==="object")return{requestBody:pC.fileUpload({contentType:t,docs:this.requestBody.description,name:this.context.casingsGenerator.generateName(this.schemaId),properties:n.properties.map(a=>this.convertRequestBodyProperty({property:a,contentType:t})),v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:i.inlinedTypes}),examples:i.examples}}handleOctetStreamContent({contentType:t}){let r=this.requestBody.content[t];if(r==null)return;let i=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});return{requestBody:pC.bytes({contentType:t,isOptional:this.requestBody.required===!1,docs:this.requestBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:i?.inlinedTypes??{}}}convertRequestBodyProperty({property:t,contentType:r}){let{isFile:i,isOptional:n,isArray:a}=this.recursivelyCheckTypeReferenceIsFile({typeReference:t.valueType});return i?a?z9.file(Jne.fileArray({key:t.name,isOptional:n,contentType:r,docs:t.docs})):z9.file(Jne.file({key:t.name,isOptional:n,contentType:r,docs:t.docs})):z9.bodyProperty({...t,contentType:r,style:void 0,name:t.name})}handleStreamConditionJsonOrFormContent({contentType:t}){if(this.streamingExtension?.type!=="streamCondition")return;let r=this.requestBody.content[t];if(r==null||r.schema==null)return;let i=this.context.resolveMaybeReference({schemaOrReference:r.schema,breadcrumbs:[...this.breadcrumbs,"content",t,"schema"]});if(i==null)return;let n=i.properties?.[this.streamingExtension.streamConditionProperty];if(n==null||this.context.isReferenceObject(n))return;let a=this.buildStreamConditionInlinedRequestBody({streamConditionProperty:n,resolvedMediaTypeSchema:i,isStreaming:!0,contentType:t,mediaTypeObject:r}),u=this.buildStreamConditionInlinedRequestBody({streamConditionProperty:n,resolvedMediaTypeSchema:i,isStreaming:!1,contentType:t,mediaTypeObject:r});if(!(a==null||u==null))return{requestBody:u.requestBody,streamRequestBody:a.requestBody,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:{...a.inlinedTypes,...u.inlinedTypes}})}}buildStreamConditionInlinedRequestBody({streamConditionProperty:t,resolvedMediaTypeSchema:r,isStreaming:i,contentType:n,mediaTypeObject:a}){if(this.streamingExtension==null||this.streamingExtension.type!=="streamCondition")return;let u={...r,properties:{...r.properties,[this.streamingExtension.streamConditionProperty]:{type:"boolean",const:i,...t}},required:[...r.required??[],this.streamingExtension.streamConditionProperty]},l={...a,schema:u},d=this.parseMediaTypeObject({mediaTypeObject:l,schemaId:this.schemaId,contentType:n});if(d==null)return;let s=d.schema?.typeDeclaration.shape;if(s?.type==="object")return{requestBody:pC.inlinedRequestBody({contentType:n,docs:void 0,name:this.context.casingsGenerator.generateName(i?`${this.schemaId}_streaming`:this.schemaId),extendedProperties:s.extendedProperties,extends:s.extends,properties:s.properties,extraProperties:s.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:l,exampleGenerationStrategy:"request"})}),inlinedTypes:d.inlinedTypes}}recursivelyCheckTypeReferenceIsFile({typeReference:t,isOptional:r,isArray:i}){return this.context.isList(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.list,isOptional:r,isArray:!0}):this.context.isOptional(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.optional,isOptional:!0,isArray:i}):this.context.isNullable(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.nullable,isOptional:r,isArray:i}):{isFile:this.context.isFile(t),isOptional:r??!1,isArray:i??!1}}};var NJE=/{([^}]+)}/g,FJE=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]),K9n=class extends yb{operation;method;path;inlinedTypes={};constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a}){super({context:t,breadcrumbs:r}),this.operation=i,this.method=n,this.path=a}convertHttpMethod(){switch(this.method){case"get":return fR.Get;case"post":return fR.Post;case"put":return fR.Put;case"delete":return fR.Delete;case"patch":return fR.Patch;case"head":return fR.Head;default:return}}convertParameters({breadcrumbs:t}){let r=[],i=[],n=[];if(!this.operation.parameters)return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:i,headers:n};for(let a of this.operation.parameters){let u=this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:t});if(u==null)continue;let d=new Lko({context:this.context,breadcrumbs:t,parameter:u}).convert();if(d!=null)switch(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},d.type){case"path":r.push(d.parameter);break;case"query":i.push(d.parameter);break;case"header":{let s=d.parameter.name.name.originalName,o=d.parameter.name.wireValue,c=!1,b=this.context.authOverrides?.["auth-schemes"];if(b!=null){for(let g of Object.values(b))if(WJE(g)&&g.header.toLowerCase()===o.toLowerCase()){c=!0;break}}!FJE.has(s.toLowerCase())&&!c&&!this.context.globalHeaderNames?.includes(o)&&n.push(d.parameter);break}}}return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:i,headers:n}}checkMissingPathParameters(t){let i=[...this.path.matchAll(NJE)].map(n=>n[1]).filter(n=>!t.some(a=>a.name.originalName===n));for(let n of i){if(n==null)continue;let a=`${n}_example`;t.push({name:this.context.casingsGenerator.generateName(n),valueType:yb.STRING,docs:void 0,location:"ENDPOINT",variable:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{[a]:this.generateStringParameterExample({example:n})}}})}}convertRequestBody({breadcrumbs:t,group:r,method:i,streamingExtension:n}){if(this.operation.requestBody==null)return;let a=this.context.resolveMaybeReference({schemaOrReference:this.operation.requestBody,breadcrumbs:t});if(a==null)return null;let l=new Uko({context:this.context,breadcrumbs:t,requestBody:a,group:r??[],method:i,streamingExtension:n}).convert();if(l!=null)return this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes},{requestBody:l.requestBody,streamRequestBody:l.streamRequestBody,examples:l.examples}}computeGroupNameAndLocationFromExtensions(){let r=new pH.SdkMethodNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.methodName,n=new pH.SdkGroupNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.groups??[];if(r!=null)return{group:n,method:r}}evaluateMethodNameFromOperation(){let t=this.operation.operationId;return t??(this.operation.summary!=null?T_(this.operation.summary):T_(`${this.method}_${this.path.split("/").join("_")}`))}computeGroupNameFromTagAndOperationId(){let t=this.operation.tags?.[0],r=this.evaluateMethodNameFromOperation();if(t==null)return{method:r};let i=QB_(t),n=QB_(r);return mEe(i,n)?{method:t}:this.computeGroupAndMethodFromTokens({tag:t,tagTokens:i,methodName:r,methodNameTokens:n})}computeGroupAndMethodFromTokens({tag:t,tagTokens:r,methodName:i,methodNameTokens:n}){if(r.some((l,d)=>l!==n[d]))return{group:[t],method:i};let u=n.slice(r.length);return{group:[t],method:T_(u.join("_"))}}generateStringParameterExample({example:t}){let r=new TM.ExampleConverter({breadcrumbs:this.breadcrumbs,context:this.context,schema:{type:"string"},example:t}),{validExample:i}=r.convert();return i}};function QB_(e){let t=LJE(e)?UJE(e):VJE(e);return t=t.map(r=>r.toLowerCase()),t=Mxe(t),t}function LJE(e){return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)}function UJE(e){return e.split(/(?=[A-Z])/)}function VJE(e){return e.split(/[^a-zA-Z0-9]+/)}function WJE(e){return e?.header!=null}var Vko=class e extends K9n{idempotent;idToAuthScheme;topLevelServers;streamingExtension;static AUTHORIZATION_HEADER="Authorization";constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a,idempotent:u,idToAuthScheme:l,topLevelServers:d,streamingExtension:s}){super({context:t,breadcrumbs:r,operation:i,method:n,path:a}),this.idempotent=u,this.idToAuthScheme=l,this.topLevelServers=d,this.streamingExtension=s}convert(){let t=this.convertHttpMethod();if(t==null)return;let{group:r,method:i}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),n=this.getGroupDisplayName(r),{headers:a,pathParameters:u,queryParameters:l}=this.convertParameters({breadcrumbs:[...this.breadcrumbs,"parameters"]}),d=this.convertRequestBody({breadcrumbs:[...this.breadcrumbs,"requestBody"],group:r,method:i,streamingExtension:this.streamingExtension}),s=d?.requestBody,o=d?.streamRequestBody,c=this.convertResponseBody({breadcrumbs:[...this.breadcrumbs,"responses"],group:r,method:i,streamingExtension:this.streamingExtension}),b=c?.response,g=c?.streamResponse,O=c!=null?c.errors:[],m={},P=O.map(V=>V.error),E=fF(this.path),q=this.getEndpointBaseUrl(),M=this.getEndpointBaseUrls(),D=this.convertExamples({httpPath:E,httpMethod:t,baseUrl:q}),T=new Set(this.operation.security?.flatMap(V=>Object.keys(V))??[]),x=this.authSchemeToHeaders(Array.from(T));x.length>0&&a.push(...x);for(let V of O){let X=V.error,K=V.errorType,k=X.error.errorId;m[k]={name:X.error,displayName:V.displayName,discriminantValue:{name:X.error.name,wireValue:k},type:K,statusCode:V.statusCode,docs:X.docs,examples:[],v2Examples:void 0}}let $={displayName:this.operation.summary,method:t,baseUrl:q,v2BaseUrls:M,path:E,pathParameters:u,queryParameters:l,headers:a.filter((V,X,K)=>X===K.findIndex(k=>k.name.wireValue===V.name.wireValue)),sdkRequest:void 0,errors:P,auth:this.operation.security!=null||this.context.spec.security!=null,availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:this.idempotent??!1,basePath:void 0,fullPath:E,allPathParameters:u,pagination:void 0,transport:void 0,source:Qne.openapi()},I=this.context.namespace!=null?[this.context.namespace]:[],L=r?.map(V=>T_(V));return I.push(...L??[]),{audiences:this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],group:r,groupDisplayName:n,errors:m,endpoint:{...$,id:`endpoint_${I.join("/")}.${i}`,name:this.context.casingsGenerator.generateName(i),requestBody:s,response:b,docs:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:D.examples}},streamEndpoint:g!=null&&g.body!=null?{...$,id:`endpoint_${I.join("/")}.${i}_stream`,name:this.context.casingsGenerator.generateName(`${i}_stream`),requestBody:o,response:g,docs:this.streamingExtension?.type==="streamCondition"?this.streamingExtension.streamDescription??this.operation.description:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:D.streamExamples}}:void 0,inlinedTypes:this.inlinedTypes,servers:this.filterOutTopLevelServers(this.operation.servers??[])}}convertResponseBody({breadcrumbs:t,group:r,method:i,streamingExtension:n}){if(this.operation.responses==null)return;let a,u=!1;for(let[l,d]of Object.entries(this.operation.responses)){let s=parseInt(l);if(!(isNaN(s)||s<200||s>=300&&s<400)){if(a==null&&(a={response:void 0,streamResponse:void 0,errors:[],examples:{}}),s>=200&&s<300&&!u){let o=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:[...t,l]});if(o==null)continue;let b=new Nko({context:this.context,breadcrumbs:[...t,l],responseBody:o,group:r??[],method:i,statusCode:l,streamingExtension:n}).convert();b!=null&&(u=!0,this.inlinedTypes={...this.inlinedTypes,...b.inlinedTypes},a.response={statusCode:s,body:b.responseBody},a.streamResponse={statusCode:s,body:b.streamResponseBody})}if(s>=400&&s<600){let o=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:[...t,l]});if(o==null)continue;let b=new Fko({context:this.context,breadcrumbs:[...t,l],responseError:o,group:r??[],method:i,methodName:this.evaluateMethodNameFromOperation(),statusCode:s}).convert();b!=null&&(this.inlinedTypes={...this.inlinedTypes,...b.inlinedTypes},a.errors.push(b))}}}return a}authSchemeToHeaders(t){let r=[];for(let i of t){let n=this.idToAuthScheme?.[i];if(n==null)continue;let a={valueType:yb.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0};switch(n.type){case"bearer":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...a});break;case"basic":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...a});break;case"header":r.push({name:n.name,...a});break}}return r}convertExamples({httpPath:t,httpMethod:r,baseUrl:i}){let a=new Rko({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation}).convert();return a==null?{examples:{},streamExamples:{}}:this.streamingExtension?.type==="streamCondition"?this.convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:a}):{examples:this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:a}),streamExamples:{}}}convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:n}){let a=n.filter(s=>!(s.response!=null&&"stream"in s.response)),u=n.filter(s=>s.response!=null&&"stream"in s.response),l=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:a}),d=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:u});return{examples:l,streamExamples:d}}convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:n}){return Object.fromEntries(n.map((a,u)=>[this.getExampleName({example:a,exampleIndex:u}),{request:a.request!=null?{docs:void 0,endpoint:{method:r,path:this.buildExamplePath(t,a["path-parameters"]??{})},baseUrl:void 0,environment:i,auth:void 0,pathParameters:a["path-parameters"]??{},queryParameters:a["query-parameters"]??{},headers:a.headers??{},requestBody:a.request}:void 0,response:a.response!=null?{docs:void 0,statusCode:void 0,body:this.getExampleResponseBody({example:a})}:void 0,codeSamples:a["code-samples"]?.map(l=>{let d=("language"in l?l.language:l.sdk)??void 0;return{name:l.name,docs:void 0,language:d,code:l.code}})}]))}getExampleName({example:t,exampleIndex:r}){return t.name??t["code-samples"]?.[0]?.name??`Example_${r}`}getExampleResponseBody({example:t}){if(t.response!=null){if("stream"in t.response)return Ws.V2HttpEndpointResponseBody.stream(t.response.stream);if("body"in t.response)return Ws.V2HttpEndpointResponseBody.json(t.response.body)}}getEndpointBaseUrl(){let t=this.operation.servers?.[0];if(t==null)return;let i=this.topLevelServers?.find(n=>n.url===t.url)??t;return LMe.getServerName({server:i,context:this.context})}getEndpointBaseUrls(){let t=this.operation.servers;return t?.map(i=>{let a=this.topLevelServers?.find(u=>u.url===i.url)??i;return LMe.getServerName({server:a,context:this.context})})}buildExamplePath(t,r){return t.head+t.parts.map(i=>`${r[i.pathParameter]?.toString()??i.pathParameter}${i.tail}`).join("")}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers?.some(i=>i.url===r.url))}getGroupDisplayName(t){let r=this.operation.tags?.[0],i=t?.[t.length-1];if(i!=null&&r!=null)return r.toLowerCase().replaceAll(" ","")===i?r:void 0}};var Y9n=class extends K9n{constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a}){super({context:t,breadcrumbs:r,operation:i,method:n,path:a})}convert(){if(this.operation.requestBody==null){this.context.errorCollector.collect({message:"Skipping webhook because no request body present",path:this.breadcrumbs});return}let t=this.convertHttpMethod();if(t==null)return;if(t!=="POST"&&t!=="GET"){this.context.errorCollector.collect({message:"Skipping webhook because non-POST or GET method",path:this.breadcrumbs});return}let{group:r,method:i}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),n=[...this.breadcrumbs,"Payload"],{headers:a}=this.convertParameters({breadcrumbs:n}),u=this.convertRequestBody({breadcrumbs:n,group:r,method:i,streamingExtension:void 0});if(u==null)return;let{requestBody:l}=u,d;if(l.type==="inlinedRequestBody")d=EW.inlinedPayload({name:l.name,extends:l.extends,properties:l.properties});else if(l.type==="reference")d=EW.reference({payloadType:l.requestBodyType,docs:l.docs});else return;return{audiences:this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],group:r,webhook:{id:`${r?.join(".")??""}.${i}`,name:this.context.casingsGenerator.generateName(i),displayName:this.operation.summary,method:t,headers:a,payload:d,examples:[],availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),docs:this.operation.description,v2Examples:{autogeneratedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(l.v2Examples?.autogeneratedExamples??{}),userSpecifiedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(l.v2Examples?.userSpecifiedExamples??{})}},inlinedTypes:this.inlinedTypes}}getWebhookV2ExamplesFromRequestBodyV2Examples(t){return Object.fromEntries(Object.entries(t).map(([r,i])=>[r,{name:r,payload:i}]))}};var Wko=class extends yb{pathItem;path;idToAuthScheme;topLevelServers;constructor({context:t,breadcrumbs:r,pathItem:i,path:n,idToAuthScheme:a,topLevelServers:u}){super({context:t,breadcrumbs:r}),this.pathItem=i,this.path=n,this.idToAuthScheme=a,this.topLevelServers=u}convert(){let t=[],r=[],i={};for(let n of $B_){let a=this.pathItem[n];if(a==null)continue;let u=[...this.breadcrumbs,n],l=this.tryParseAsWebhook({operationBreadcrumbs:u,operation:a,method:n,context:this.context});if(l!=null){r.push(l),Object.assign(i,l.inlinedTypes);continue}let s=new zko({breadcrumbs:u,operation:a,context:this.context}).convert(),o=this.tryParseAsHttpEndpoint({operationBreadcrumbs:u,operation:a,method:n,streamingExtension:s});o!=null&&(t.push(o),Object.assign(i,o.inlinedTypes))}return{endpoints:t,webhooks:r,inlinedTypes:i}}tryParseAsWebhook({operation:t,method:r,operationBreadcrumbs:i,context:n}){return new xko({breadcrumbs:i,operation:t,context:n}).convert()?new Y9n({context:this.context,breadcrumbs:i,operation:t,method:sjc.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path}).convert():void 0}tryParseAsHttpEndpoint({operation:t,method:r,operationBreadcrumbs:i,streamingExtension:n}){new Iko({breadcrumbs:i,operation:t,document:this.context.spec,context:this.context}).convert()!=null;let d=new Cko({breadcrumbs:i,operation:t,context:this.context}).convert();return new Vko({context:this.context,breadcrumbs:i,operation:t,method:sjc.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,idempotent:d,idToAuthScheme:this.idToAuthScheme,topLevelServers:this.topLevelServers,streamingExtension:n}).convert()}};var Hko=class extends yb{securityScheme;constructor({context:t,breadcrumbs:r,securityScheme:i}){super({context:t,breadcrumbs:r}),this.securityScheme=i}convert(){switch(this.securityScheme.type){case"http":{if(this.securityScheme.scheme==="bearer")return CB.bearer({token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:this.securityScheme.description});if(this.securityScheme.scheme==="basic")return CB.basic({username:this.context.casingsGenerator.generateName("username"),password:this.context.casingsGenerator.generateName("password"),usernameEnvVar:void 0,passwordEnvVar:void 0,docs:this.securityScheme.description});break}case"apiKey":{if(this.securityScheme.in==="header")return CB.header({name:{name:this.context.casingsGenerator.generateName("apiKey"),wireValue:this.securityScheme.name},valueType:yb.OPTIONAL_STRING,prefix:void 0,headerEnvVar:void 0,docs:this.securityScheme.description});break}case"oauth2":return CB.bearer({token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:this.securityScheme.description})}}};var FRa=class extends qpi{constructor({breadcrumbs:t,context:r,audiences:i}){super({breadcrumbs:t,context:r,audiences:i})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec});let t=this.convertSecuritySchemes();this.convertGlobalHeaders(),this.convertSchemas(),this.convertWebhooks();let{endpointLevelServers:r,errors:i}=this.convertPaths({idToAuthScheme:t});this.addErrorsToIr(i);let{defaultUrl:n}=this.convertServers({endpointLevelServers:r});return this.updateEndpointsWithDefaultUrl(n),this.finalizeIr()}convertGlobalHeaders(){this.context.globalHeaderOverrides;let r=new Tko({breadcrumbs:["x-fern-global-headers"],document:this.context.spec,context:this.context}).convert();if(r!=null){let i=HB_({globalHeaders:r,context:this.context});this.addGlobalHeadersToIr(i),this.context.setGlobalHeaders(i)}}convertSecuritySchemes(){if(this.context.authOverrides)return this.addAuthToIR(XPc({rawApiFileSchema:this.context.authOverrides,casingsGenerator:this.context.casingsGenerator})),{};let t={},r=[];for(let[i,n]of Object.entries(this.context.spec.components?.securitySchemes??{})){let a=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:["components","securitySchemes",i]});if(a==null)continue;let l=new Hko({context:this.context,breadcrumbs:["components","securitySchemes",i],securityScheme:a}).convert();l!=null&&(this.shouldAddAuthSchemeToIr({authScheme:l,schemeId:i,currentSecuritySchemes:r})?r.push(l):t[i]=l)}return r.length>0&&this.addAuthToIR({requirement:r.length===1?"ALL":"ANY",schemes:r,docs:void 0}),t}convertServers({endpointLevelServers:t}){if(this.context.environmentOverrides){let n=BRa({rawApiFileSchema:this.context.environmentOverrides,casingsGenerator:this.context.casingsGenerator});return n!=null&&this.addEnvironmentsToIr({environmentConfig:n.environmentsConfig,audiences:n.audiences}),{defaultUrl:this.context.environmentOverrides["default-url"]}}let i=new LMe({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();return this.addEnvironmentsToIr({environmentConfig:i?.value}),{defaultUrl:i?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let n=new TM.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();n!=null&&(this.addTypeToPackage(t),this.addTypesToIr({...n.inlinedTypes,[t]:n.convertedSchema}))}}convertWebhooks(){for(let[,t]of Object.entries(this.context.spec.webhooks??{})){if(t==null){this.context.errorCollector.collect({message:"Skipping empty webhook",path:this.breadcrumbs});continue}if(!("post"in t)){this.context.errorCollector.collect({message:"Skipping webhook as it is not a POST method",path:this.breadcrumbs});continue}if(t.post?.operationId==null){this.context.errorCollector.collect({message:"Skipping webhook as no operationId is present",path:this.breadcrumbs});continue}let r=t.post.operationId,n=new Y9n({context:this.context,breadcrumbs:["webhooks",r],operation:t.post,method:JB_.OpenAPIV3.HttpMethods.POST,path:r}).convert();n!=null&&(this.addWebhookToIr({webhook:n.webhook,operationId:r,audiences:n.audiences,group:n.group}),this.addTypesToIr(n.inlinedTypes))}}convertPaths({idToAuthScheme:t}){let r=[],i={};for(let[n,a]of Object.entries(this.context.spec.paths??{})){if(a==null)continue;let l=new Wko({context:this.context,breadcrumbs:["paths",n],topLevelServers:this.context.spec.servers,pathItem:a,path:n}).convert();if(l!=null){for(let d of l.endpoints){if(d.streamEndpoint!=null&&this.addEndpointToIr({endpoint:d.streamEndpoint,audiences:d.audiences,endpointGroup:d.group,endpointGroupDisplayName:d.groupDisplayName}),this.addEndpointToIr({endpoint:d.endpoint,audiences:d.audiences,endpointGroup:d.group,endpointGroupDisplayName:d.groupDisplayName}),d.servers)for(let s of d.servers)this.shouldAddServerToCollectedServers({server:s,currentServers:r})&&r.push(s);if(d.errors)for(let[s,o]of Object.entries(d.errors))i[s]=o}for(let d of l.webhooks){let s=this.context.getGroup({groupParts:d.group,namespace:this.context.namespace});this.addWebhookToIr({webhook:d.webhook,operationId:s.join("."),group:s,audiences:d.audiences})}this.addTypesToIr(l.inlinedTypes)}}return{endpointLevelServers:r,errors:i}}shouldAddAuthSchemeToIr({authScheme:t,schemeId:r,currentSecuritySchemes:i}){let n=i.some(u=>u.type===t.type&&u.type==="bearer"&&t.type==="bearer"?u.token===t.token:!1),a=new Set(this.context.spec.security?.flatMap(u=>Object.keys(u))??[]);return(a.size===0||a.has(r))&&!n}};var LRa=class extends f8{globalHeaderNames;isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n}){let a=this.getTypeIdFromSchemaReference(t);if(a==null)return{ok:!1};let u=this.resolveReference({reference:t,breadcrumbs:r});if(!u.resolved)return{ok:!1};let l;n==="reference_identifier"?l=i??u.value.title:(n==="discriminator_key"||n==="schema_identifier")&&(l=u.value.title??i);let d;if(a.includes("/")){let o=new TM.SchemaConverters.SchemaConverter({context:this,breadcrumbs:r??[],schema:u.value,id:a}).convert();o!=null&&(d={[a]:o.convertedSchema})}return{ok:!0,reference:hf.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(a),typeId:a,default:void 0,inline:!1,displayName:l}),inlinedTypes:d}}setGlobalHeaders(t){this.globalHeaderNames=t.map(r=>r.name.wireValue)}};var $ko=class extends TM.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r,parameter:i})}convert(){let t,r={};if(this.parameter.schema!=null){let n=new TM.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required}).convert();n!=null&&(t=n.type,r=n.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}};var HJE=hu.object({description:hu.string().optional(),required:hu.boolean().optional(),deprecated:hu.boolean().optional(),allowEmptyValue:hu.boolean().optional(),style:hu.string().optional(),explode:hu.boolean().optional(),allowReserved:hu.boolean().optional(),schema:hu.any().optional(),example:hu.any().optional(),examples:hu.record(hu.string(),hu.any()).optional(),content:hu.record(hu.string(),hu.any()).optional()}),$JE=HJE.extend({name:hu.string(),in:hu.string()}),GJE=hu.array($JE),Gko=class extends Pm{operation;key="x-fern-parameters";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null)try{return GJE.parse(t)}catch(r){this.context.errorCollector.collect({message:`Failed to parse x-fern-parameters extension: ${r instanceof Error?r.message:String(r)}`,path:this.breadcrumbs});return}}};var Qko=class extends yb{method;pathParameters;queryParameters;headers;topLevelServers;constructor({context:t,breadcrumbs:r,method:i,pathParameters:n=[],queryParameters:a=[],headers:u=[],topLevelServers:l=[]}){super({context:t,breadcrumbs:r}),this.method=i,this.pathParameters=n,this.queryParameters=a,this.headers=u,this.topLevelServers=l}convert(){let t={},r="";for(let s of this.pathParameters)r+=`/{${s.name.originalName}}`;let i=fF(r),n=[];for(let[s,o]of this.method.params.entries()){let c;if(this.context.isReferenceObject(o)){let m=this.context.resolveReference({reference:o});if(m.resolved)c=m.value;else continue}else c=o;let b=[this.method.name,"Param",c.name].join("_"),O=new TM.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"Param",c.name],schemaIdOverride:b,context:this.context,schemaOrReference:c.schema,wrapAsOptional:!c.required}).convert();O!=null&&(n.push({docs:c.description,availability:this.context.getAvailability({node:o,breadcrumbs:[...this.breadcrumbs,"parameters"]}),name:this.context.casingsGenerator.generateNameAndWireValue({name:c.name,wireValue:c.name}),valueType:O.type,v2Examples:O.schema?.typeDeclaration.v2Examples}),t={...O.inlinedTypes,...t,...O.schema!=null?{[b]:O.schema}:{}})}let a;if(this.method.result!=null){let s=this.context.resolveMaybeReference({schemaOrReference:this.method.result,breadcrumbs:[...this.breadcrumbs,"result"]});if(s!=null){let o=new TM.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"result"],context:this.context,schemaOrReference:s.schema}),c=[this.method.name,"Result"].join("_"),b=o.convert();b!=null&&(a={docs:s.description,v2Examples:b.schema?.typeDeclaration.v2Examples,responseBodyType:b.type},t={...b.inlinedTypes,...t,...b.schema!=null?{[c]:b.schema}:{}})}}let u=this.getEndpointBaseUrls(),l=this.context.getAudiences({operation:this.method,breadcrumbs:this.breadcrumbs})??[];return{endpoint:{baseUrl:void 0,v2BaseUrls:u,basePath:void 0,auth:!1,method:"POST",id:this.method.name,docs:this.method.description,name:this.context.casingsGenerator.generateName(this.method.name),headers:this.headers,displayName:this.method.name,pathParameters:this.pathParameters,queryParameters:this.queryParameters,allPathParameters:this.pathParameters,path:i,fullPath:i,requestBody:n.length>0?pC.inlinedRequestBody({name:this.context.casingsGenerator.generateName([this.method.name,"Request"].join("_")),docs:void 0,properties:n,extends:[],extendedProperties:[],contentType:"application/json",extraProperties:!1,v2Examples:void 0}):void 0,sdkRequest:void 0,response:a!=null?{body:NS.json(IQ.response(a)),statusCode:void 0}:void 0,errors:[],idempotent:!1,pagination:void 0,userSpecifiedExamples:[],autogeneratedExamples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples()},transport:void 0,availability:void 0,source:Qne.openrpc()},audiences:l,inlinedTypes:t,servers:this.filterOutTopLevelServers(this.method.servers??[])}}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers.some(i=>i.url===r.url))}getEndpointBaseUrls(){let t=this.method.servers;return t?.map(i=>{if(this.topLevelServers.find(l=>l.name===i.name&&l.url!==i.url)!=null)return i.url;let u=this.topLevelServers.find(l=>l.url===i.url)??i;return LMe.getServerName({server:u,context:this.context})})}convertExamples(){let t={},r=0;if(this.method.examples&&this.method.examples.length>0){for(let i of this.method.examples??[]){let n;if(this.context.isReferenceObject(i)){let d=this.context.resolveReference({reference:i});if(d.resolved)n=d.value;else continue}else n=i;let a;if(n.result)if(this.context.isReferenceObject(n.result)){let d=this.context.resolveReference({reference:n.result});d.resolved&&(a=d.value)}else a=n.result;let u=n.name??`Example ${r+1}`,l=[];if(n.params&&Array.isArray(n.params)){l=[];for(let d of n.params)if(this.context.isReferenceObject(d)){let s=this.context.resolveReference({reference:d});if(s.resolved)l.push(s.value);else continue}else l.push(d)}t[u]={request:{docs:void 0,endpoint:{method:"POST",path:"/{apiKey}"},baseUrl:void 0,environment:void 0,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:l.map(d=>d.value)??void 0},response:{docs:void 0,statusCode:void 0,body:a?.value?Ws.V2HttpEndpointResponseBody.json({jsonrpc:"2.0",id:n.examplePairedRequest?.id||"1",result:a.value}):void 0},codeSamples:[]}}++r}return t}};var URa=class extends qpi{constructor({context:t,breadcrumbs:r,audiences:i}){super({context:t,breadcrumbs:r,audiences:i})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.convertSchemas();let{endpointLevelServers:t}=this.convertMethods(),{defaultUrl:r}=this.convertServers({endpointLevelServers:t});return this.updateEndpointsWithDefaultUrl(r),this.finalizeIr()}convertServers({endpointLevelServers:t}){let i=new LMe({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();return this.addEnvironmentsToIr({environmentConfig:i?.value}),{defaultUrl:i?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let n=new TM.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();n!=null&&(this.addTypeToPackage(t),this.addTypesToIr({...n.inlinedTypes,[t]:n.convertedSchema}))}}convertMethods(){let t=[],i=new Gko({context:this.context,breadcrumbs:["methods"],operation:this.context.spec}).convert(),n=[],a=[],u=[];if(i&&i.length>0)for(let[d,s]of i.entries()){let c=new $ko({context:this.context,breadcrumbs:[...this.breadcrumbs,`x-fern-parameters[${d}]`],parameter:s}).convert();if(c!=null)switch(c.type){case"path":{n.push(c.parameter);break}case"query":{a.push(c.parameter);break}case"header":{u.push(c.parameter);break}}}let l=this.context.getGroup({groupParts:[],namespace:this.context.namespace});for(let d of this.context.spec.methods??[]){let s=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:["methods"]});if(s==null)continue;let c=new Qko({context:this.context,breadcrumbs:["methods"],method:s,pathParameters:n,queryParameters:a,headers:u,topLevelServers:this.context.spec.servers}).convert();if(c!=null&&(this.addEndpointToIr({endpoint:c.endpoint,audiences:c.audiences,endpointGroup:l,serviceName:"service_root"}),this.addTypesToIr(c.inlinedTypes),c.servers))for(let b of c.servers)this.shouldAddServerToCollectedServers({server:b,currentServers:t,specType:"openrpc"})&&t.push(this.maybeDeduplicateServerName(b))}return{endpointLevelServers:t}}maybeDeduplicateServerName(t){return this.context.spec.servers?.find(i=>i.name===t.name&&i.url!==t.url)?{...t,name:t.url}:t}};var VRa=class extends f8{isReferenceObject(t){return t!=null&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n}){let a=this.getTypeIdFromSchemaReference(t);if(a==null)return{ok:!1};let u=this.resolveReference({reference:t,breadcrumbs:r});if(!u.resolved)return{ok:!1};let l;return n==="reference_identifier"?l=i??u.value.title:(n==="discriminator_key"||n==="schema_identifier")&&(l=u.value.title??i),{ok:!0,reference:hf.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(a),typeId:a,displayName:l,default:void 0,inline:!1})}}};var KB_={[hy.GenerationLanguage.PHP]:new Set(["abstract","and","as","break","callable","case","catch","class","clone","const","continue","declare","default","do","echo","else","elseif","enddeclare","endfor","endforeach","endif","endswitch","endwhile","extends","final","finally","fn","for","foreach","function","global","goto","list","if","implements","include","include_once","instanceof","insteadof","interface","match","namespace","new","or","parent","Parent","print","private","protected","public","readonly","require","require_once","return","static","switch","throw","trait","try","use","var","while","xor","yield"].flatMap(e=>[e,iz(e)])),[hy.GenerationLanguage.TYPESCRIPT]:new Set(["any","as","boolean","break","case","catch","class","const","constructor","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","let","module","new","null","number","of","package","private","protected","public","require","return","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","Date","Error","File","Object","Record"]),[hy.GenerationLanguage.JAVA]:new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","false","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","true","try","void","volatile","while"]),[hy.GenerationLanguage.PYTHON]:new Set(["False","None","True","and","as","assert","async","","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","float","int","complex","bool","uuid","list","set","map","long","self","all"]),[hy.GenerationLanguage.GO]:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[hy.GenerationLanguage.RUBY]:new Set(["__ENCODING__","__LINE__","__FILE__","alias","and","begin","break","case","class","def","defined","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield","Object","JSON","Date","DateTime"]),[hy.GenerationLanguage.CSHARP]:new Set(["abstract","as","base","bool","break","byte","case","catch","char","checked","class","const","continue","decimal","default","delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","goto","if","implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","operator","out","override","params","private","protected","public","readonly","ref","return","sbyte","sealed","short","sizeof","stackalloc","static","string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","ushort","using","virtual","void","volatile","while","add","and","alias","ascending","args","async","","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","managed","nameof","nint","not","notnull","nuint","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value","var","when","where","with","yield"]),[hy.GenerationLanguage.SWIFT]:new Set([])};var QJE=["go","ruby"];function cjc({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let u=c=>({unsafeName:c,safeName:JJE({name:c,keywords:KJE({generationLanguage:e,keywords:t})})}),l=T_(n),d=iz(l),s=qVi(n),o=DVi(l);return r&&(!ZJE(o)&&(e==null||QJE.includes(e))&&(l=o.map((c,b)=>{if(b>0){let g=Jko(c);if(g!=null)return g;if(Kko(c))return c.toUpperCase()}return c}).join(""),d=o.map((c,b)=>{let g=Jko(c);return g??(Kko(c)?c.toUpperCase():b===0?iz(c):c)}).join("")),s=n.split(" ").map(c=>c.split(/(\d+)/).map(qVi).join("")).join("_")),{originalName:n,camelCase:u(a?.casingOverrides?.camel??l),snakeCase:u(a?.casingOverrides?.snake??s),screamingSnakeCase:u(a?.casingOverrides?.["screaming-snake"]??s.toUpperCase()),pascalCase:u(a?.casingOverrides?.pascal??d)}},generateNameAndWireValue:({name:n,wireValue:a,opts:u})=>({name:i.generateName(n,u),wireValue:a})};return i}function JJE({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":XJE(e)?"_"+e:e}function KJE({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return KB_[e]}var YJE=/^[0-9]/;function XJE(e){return YJE.test(e)}function ZJE(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=Jko(i)!=null||Kko(i),a=Jko(t)!=null||Kko(t);return n&&a})}function Jko(e){return eKE.get(e.toUpperCase())}function Kko(e){return kJE.has(e.toUpperCase())}var kJE=new Set(["ACL","API","ASCII","CPU","CSS","DNS","EOF","GUID","HTML","HTTP","HTTPS","ID","IP","JSON","LHS","QPS","RAM","RHS","RPC","SAML","SCIM","SLA","SMTP","SQL","SSH","SSO","TCP","TLS","TTL","UDP","UI","UID","UUID","URI","URL","UTF8","VM","XML","XMPP","XSRF","XSS"]),eKE=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);var YB_=require("fs/promises");async function ljc({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let i=(await(0,YB_.readFile)(t)).toString(),n;try{n=JSON.parse(i)}catch{n=qd.load(i)}return r!=null?await n9n({absoluteFilePathToOverrides:r,context:e,data:n}):n}var SR=class extends ZIa{type="oss";allSpecs;specs;sources;loader;constructor({allSpecs:t,specs:r,...i}){super({...i,respectReadonlySchemas:r.every(n=>n.settings?.respectReadonlySchemas),respectNullableSchemas:r.every(n=>n.settings?.respectNullableSchemas),onlyIncludeReferencedSchemas:r.every(n=>n.settings?.onlyIncludeReferencedSchemas),inlinePathParameters:r.every(n=>n.settings?.inlinePathParameters),objectQueryParameters:r.every(n=>n.settings?.objectQueryParameters),useBytesForBinaryResponse:r.filter(n=>n.type==="openapi"&&n.source.type==="openapi").some(n=>n.settings?.useBytesForBinaryResponse),respectForwardCompatibleEnums:r.filter(n=>n.type==="openapi"&&n.source.type==="openapi").some(n=>n.settings?.respectForwardCompatibleEnums),exampleGeneration:r[0]?.settings?.exampleGeneration}),this.specs=r,this.allSpecs=t,this.sources=this.convertSpecsToIdentifiableSources(r),this.loader=new MHt(this.absoluteFilePath)}async getOpenAPIIr({context:t,relativePathToDependency:r},i){let n=await zFe({context:t,specs:this.specs,relativePathToDependency:r});return PJi({context:t,documents:await this.loader.loadDocuments({context:t,specs:n}),options:{...i,respectReadonlySchemas:i?.respectReadonlySchemas??this.respectReadonlySchemas,respectNullableSchemas:i?.respectNullableSchemas??this.respectNullableSchemas,onlyIncludeReferencedSchemas:i?.onlyIncludeReferencedSchemas??this.onlyIncludeReferencedSchemas,inlinePathParameters:i?.inlinePathParameters??this.inlinePathParameters,objectQueryParameters:i?.objectQueryParameters??this.objectQueryParameters,exampleGeneration:i?.exampleGeneration??this.exampleGeneration,useBytesForBinaryResponse:i?.useBytesForBinaryResponse??this.useBytesForBinaryResponse}})}async getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:i,generateV1Examples:n}){let a=await zFe({context:t,specs:this.specs}),u=await this.loader.loadDocuments({context:t,specs:a}),l=this.generatorsConfiguration?.api?.auth!=null?{...this.generatorsConfiguration?.api}:void 0;l&&t.logger.trace("Using auth overrides from generators configuration");let d=this.generatorsConfiguration?.api?.environments!=null?{...this.generatorsConfiguration?.api}:void 0;d&&t.logger.trace("Using environment overrides from generators configuration");let s=this.generatorsConfiguration?.api?.headers!=null?{...this.generatorsConfiguration?.api}:void 0;s&&t.logger.trace("Using global header overrides from generators configuration");let o,c=[];for(let b of u){let g=Vu(this.absoluteFilePath,Qa.of(b.source?.file??"")),O=lne(oR(),g),m=new x9n({logger:t.logger,relativeFilepathToSpec:O});c.push(m);let P;switch(b.type){case"openapi":{let q=new LRa({namespace:b.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:b.value,exampleGenerationArgs:{disabled:!1},errorCollector:m,authOverrides:l,environmentOverrides:d,globalHeaderOverrides:s,enableUniqueErrorsPerEndpoint:i,generateV1Examples:n,settings:aza({options:b.settings})});P=await new FRa({context:q,audiences:r}).convert();break}case"asyncapi":{let q=new NRa({namespace:b.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:b.value,exampleGenerationArgs:{disabled:!1},errorCollector:m,enableUniqueErrorsPerEndpoint:i,settings:aza({options:b.settings}),generateV1Examples:n});P=await new RRa({context:q,audiences:r}).convert();break}default:m.collect({message:`Unsupported document type: ${b}`,path:[]});break}let E=cjc({generationLanguage:"typescript",keywords:void 0,smartCasing:!1});P!=null&&(o=o===void 0?P:lko(o,P,E))}for(let b of this.allSpecs)if(b.type==="openrpc"){let g=b.absoluteFilepath,O=lne(oR(),g),m=new x9n({logger:t.logger,relativeFilepathToSpec:O});c.push(m);let P=new VRa({namespace:b.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:await ljc({context:t,absoluteFilePath:b.absoluteFilepath,absoluteFilePathToOverrides:b.absoluteFilepathToOverrides}),exampleGenerationArgs:{disabled:!1},errorCollector:m,enableUniqueErrorsPerEndpoint:i,generateV1Examples:n,settings:aza()}),q=await new URa({context:P,audiences:r}).convert(),M=cjc({generationLanguage:"typescript",keywords:void 0,smartCasing:!1});q!=null&&(o=o===void 0?q:lko(o,q,M))}for(let b of c)if(b.hasErrors()){let g=b.getErrorStats(),O=b.relativeFilepathToSpec?` for ${b.relativeFilepathToSpec}`:"";g.numErrors>0?t.logger.log("error",`API validation${O} completed with ${g.numErrors} errors and ${g.numWarnings} warnings.`):g.numWarnings>0?t.logger.log("warn",`API validation${O} completed with ${g.numWarnings} warnings.`):t.logger.log("info",`All checks passed when parsing OpenAPI${O}.`),t.logger.log("info",""),await b.logErrors({logWarnings:!1})}if(o===void 0)throw new Error("Failed to generate intermediate representation");return o}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new EMe({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:i,cliVersion:this.cliVersion,sources:this.sources})}getAbsoluteFilePaths(){return[this.absoluteFilePath,...this.allSpecs.flatMap(t=>[t.type==="protobuf"?t.absoluteFilepathToProtobufTarget:t.absoluteFilepath,t.absoluteFilepathToOverrides]).filter(V0)]}getSources(){return this.sources}convertSpecsToIdentifiableSources(t){let r=new Set,i=[];return t.reduce((n,a)=>{let u=a.type==="protobuf"?a.absoluteFilepathToProtobufRoot:a.absoluteFilepath;return r.has(u)||(r.add(u),n.push({type:a.type,id:zae(),absoluteFilePath:u})),n},i)}};var XB_={None:"none",Header:"header"};var beu={};jo(beu,{ConjureAliasDeclaration:()=>reu,ConjureArgument:()=>heu,ConjureArgumentWithParamType:()=>_eu,ConjureAuthDefinition:()=>eLn,ConjureAuthDefinitionType:()=>deu,ConjureDefinitions:()=>leu,ConjureEndpointDefinition:()=>yeu,ConjureEnumDeclaration:()=>seu,ConjureEnumVariant:()=>ueu,ConjureEnumWithDocs:()=>oeu,ConjureObjectDeclaration:()=>aeu,ConjureParamType:()=>peu,ConjurePrimitive:()=>teu,ConjureService:()=>veu,ConjureServiceName:()=>eeu,ConjureType:()=>KAi,ConjureTypeDeclaration:()=>ceu,ConjureTypeReference:()=>YAi,ConjureTypeWithDocs:()=>ieu,ConjureTypes:()=>feu,ConjureUnionDeclaration:()=>neu,DefinitionFile:()=>SI_,WithDocs:()=>$ir,commons:()=>hjc,conjure:()=>yjc,services:()=>vjc,types:()=>bjc});var hjc={};jo(hjc,{WithDocs:()=>$ir});var ip={};jo(ip,{JsonError:()=>X9n,ParseError:()=>Z9n,any:()=>dI_,bigint:()=>kB_,boolean:()=>pI_,booleanLiteral:()=>fI_,date:()=>eI_,discriminant:()=>PI_,enum_:()=>Xko,getObjectLikeUtils:()=>THt,getObjectUtils:()=>DKi,getSchemaUtils:()=>Qq,isProperty:()=>JAi,lazy:()=>tI_,lazyObject:()=>sI_,list:()=>kko,number:()=>_I_,object:()=>Zko,objectWithoutOptionalProperties:()=>uI_,optional:()=>fjc,property:()=>iI_,record:()=>bI_,set:()=>gI_,string:()=>hI_,stringLiteral:()=>lI_,transform:()=>djc,undiscriminatedUnion:()=>mI_,union:()=>wI_,unknown:()=>yI_,withParsedProperties:()=>_jc});var qj={BIGINT:"bigint",DATE:"date",ENUM:"enum",LIST:"list",STRING_LITERAL:"stringLiteral",BOOLEAN_LITERAL:"booleanLiteral",OBJECT:"object",ANY:"any",BOOLEAN:"boolean",NUMBER:"number",STRING:"string",UNKNOWN:"unknown",RECORD:"record",SET:"set",UNION:"union",UNDISCRIMINATED_UNION:"undiscriminatedUnion",OPTIONAL:"optional"};function vA(e,t){return`Expected ${t}. Received ${tKE(e)}.`}function tKE(e){if(Array.isArray(e))return"list";if(e===null)return"null";if(e instanceof BigInt)return"BigInt";switch(typeof e){case"string":return`"${e}"`;case"bigint":case"number":case"boolean":case"undefined":return`${e}`}return typeof e}function _L(e){return{...e,json:ZB_(e.json),parse:ZB_(e.parse)}}function ZB_(e){return(t,r)=>{let i=e(t,r),{skipValidation:n=!1}=r??{};return!i.ok&&n?(console.warn(["Failed to validate.",...i.errors.map(a=>" - "+(a.path.length>0?`${a.path.join(".")}: ${a.message}`:a.message))].join(`
1961
1961
  `)),{ok:!0,value:t}):i}}function Yko(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var X9n=class e extends Error{errors;constructor(t){super(t.map(Yko).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var Z9n=class e extends Error{errors;constructor(t){super(t.map(Yko).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function Qq(e){return{optional:()=>fjc(e),transform:t=>djc(e,t),parseOrThrow:(t,r)=>{let i=e.parse(t,r);if(i.ok)return i.value;throw new Z9n(i.errors)},jsonOrThrow:(t,r)=>{let i=e.json(t,r);if(i.ok)return i.value;throw new X9n(i.errors)}}}function fjc(e){let t={parse:(r,i)=>r==null?{ok:!0,value:void 0}:e.parse(r,i),json:(r,i)=>i?.omitUndefined&&r===void 0?{ok:!0,value:void 0}:r==null?{ok:!0,value:null}:e.json(r,i),getType:()=>qj.OPTIONAL};return{...t,...Qq(t)}}function djc(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);return a.ok?{ok:!0,value:t.transform(a.value)}:a},json:(i,n)=>{let a=t.untransform(i);return e.json(a,n)},getType:()=>e.getType()};return{...r,...Qq(r)}}function kB_(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:vA(t,"string")}]}:{ok:!0,value:BigInt(t)},json:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t=="bigint"?{ok:!0,value:t.toString()}:{ok:!1,errors:[{path:r,message:vA(t,"bigint")}]},getType:()=>qj.BIGINT};return{..._L(e),...Qq(e)}}var rKE=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function eI_(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:vA(t,"string")}]}:rKE.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:vA(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:vA(t,"Date object")}]},getType:()=>qj.DATE};return{..._L(e),...Qq(e)}}function DJ(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{..._L(r),...Qq(r)}}}function Xko(e){let t=new Set(e);return DJ(qj.ENUM,(i,{allowUnrecognizedEnumValues:n,breadcrumbsPrefix:a=[]}={})=>typeof i!="string"?{ok:!1,errors:[{path:a,message:vA(i,"string")}]}:!t.has(i)&&!n?{ok:!1,errors:[{path:a,message:vA(i,"enum")}]}:{ok:!0,value:i})()}function tI_(e){let t=pjc(e);return{...t,...Qq(t)}}function pjc(e){return{parse:(t,r)=>k9n(e).parse(t,r),json:(t,r)=>k9n(e).json(t,r),getType:()=>k9n(e).getType()}}function k9n(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function WRa(e){return Object.entries(e)}function HRa(e,t){let r=new Set(t);return Object.entries(e).reduce((i,[n,a])=>(r.has(n)&&(i[n]=a),i),{})}function QAi(e){if(typeof e!="object"||e===null)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function $Ra(e){return Object.keys(e)}function rI_(e,t){let r=[],i=[];for(let n of e)t(n)?r.push(n):i.push(n);return[r,i]}function THt(e){return{withParsedProperties:t=>_jc(e,t)}}function _jc(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);if(!a.ok)return a;let u=Object.entries(t).reduce((l,[d,s])=>({...l,[d]:typeof s=="function"?s(a.value):s}),{});return{ok:!0,value:{...a.value,...u}}},json:(i,n)=>{if(!QAi(i))return{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:vA(i,"object")}]};let a=new Set(Object.keys(t)),u=HRa(i,Object.keys(i).filter(l=>!a.has(l)));return e.json(u,n)},getType:()=>e.getType()};return{...r,...Qq(r),...THt(r)}}function iI_(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function JAi(e){return e.isProperty}function Zko(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,i])=>JAi(i)?i.rawKey:r),_getParsedProperties:()=>$Ra(e),parse:(r,i)=>{let n={},a=[];for(let[u,l]of WRa(e)){let d=JAi(l)?l.rawKey:u,s=JAi(l)?l.valueSchema:l,o={rawKey:d,parsedKey:u,valueSchema:s};n[d]=o,oI_(s)&&a.push(d)}return nI_({value:r,requiredKeys:a,getProperty:u=>{let l=n[u];if(l!=null)return{transformedKey:l.parsedKey,transform:d=>l.valueSchema.parse(d,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],u]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},json:(r,i)=>{let n=[];for(let[a,u]of WRa(e)){let l=JAi(u)?u.valueSchema:u;oI_(l)&&n.push(a)}return nI_({value:r,requiredKeys:n,getProperty:a=>{let u=e[a];if(u!=null)return JAi(u)?{transformedKey:u.rawKey,transform:l=>u.valueSchema.json(l,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}:{transformedKey:a,transform:l=>u.json(l,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},getType:()=>qj.OBJECT};return{..._L(t),...Qq(t),...THt(t),...DKi(t)}}function nI_({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:i="fail",skipValidation:n=!1,breadcrumbsPrefix:a=[]}){if(!QAi(e))return{ok:!1,errors:[{path:a,message:vA(e,"object")}]};let u=new Set(t),l=[],d={};for(let[s,o]of Object.entries(e)){let c=r(s);if(c!=null){u.delete(s);let b=c.transform(o);b.ok?d[c.transformedKey]=b.value:(d[s]=o,l.push(...b.errors))}else switch(i){case"fail":l.push({path:[...a,s],message:`Unexpected key "${s}"`});break;case"strip":break;case"passthrough":d[s]=o;break}}return l.push(...t.filter(s=>u.has(s)).map(s=>({path:a,message:`Missing required key "${s}"`}))),l.length===0||n?{ok:!0,value:d}:{ok:!1,errors:l}}function DKi(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(i,n)=>aI_({extensionKeys:t._getRawProperties(),value:i,transformBase:a=>e.parse(a,n),transformExtension:a=>t.parse(a,n)}),json:(i,n)=>aI_({extensionKeys:t._getParsedProperties(),value:i,transformBase:a=>e.json(a,n),transformExtension:a=>t.json(a,n)}),getType:()=>qj.OBJECT};return{...r,...Qq(r),...THt(r),...DKi(r)}},passthrough:()=>{let t={_getParsedProperties:()=>e._getParsedProperties(),_getRawProperties:()=>e._getRawProperties(),parse:(r,i)=>{let n=e.parse(r,{...i,unrecognizedObjectKeys:"passthrough"});return n.ok?{ok:!0,value:{...r,...n.value}}:n},json:(r,i)=>{let n=e.json(r,{...i,unrecognizedObjectKeys:"passthrough"});return n.ok?{ok:!0,value:{...r,...n.value}}:n},getType:()=>qj.OBJECT};return{...t,...Qq(t),...THt(t),...DKi(t)}}}}function aI_({extensionKeys:e,value:t,transformBase:r,transformExtension:i}){let n=new Set(e),[a,u]=rI_($Ra(t),s=>n.has(s)),l=r(HRa(t,u)),d=i(HRa(t,a));return l.ok&&d.ok?{ok:!0,value:{...l.value,...d.value}}:{ok:!1,errors:[...l.ok?[]:l.errors,...d.ok?[]:d.errors]}}function oI_(e){return!iKE(e)}function iKE(e){switch(e.getType()){case qj.ANY:case qj.UNKNOWN:case qj.OPTIONAL:return!0;default:return!1}}function uI_(e){return Zko(e)}function sI_(e){let t={...pjc(e),_getRawProperties:()=>k9n(e)._getRawProperties(),_getParsedProperties:()=>k9n(e)._getParsedProperties()};return{...t,...Qq(t),...THt(t),...DKi(t)}}function kko(e){let t={parse:(r,i)=>cI_(r,(n,a)=>e.parse(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,i)=>cI_(r,(n,a)=>e.json(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>qj.LIST};return{..._L(t),...Qq(t)}}function cI_(e,t){return Array.isArray(e)?e.map((i,n)=>t(i,n)).reduce((i,n)=>{if(i.ok&&n.ok)return{ok:!0,value:[...i.value,n.value]};let a=[];return i.ok||a.push(...i.errors),n.ok||a.push(...n.errors),{ok:!1,errors:a}},{ok:!0,value:[]}):{ok:!1,errors:[{message:vA(e,"list"),path:[]}]}}function lI_(e){return DJ(qj.STRING_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:vA(r,`"${e}"`)}]})()}function fI_(e){return DJ(qj.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:vA(r,`${e.toString()}`)}]})()}var dI_=DJ(qj.ANY,e=>({ok:!0,value:e}));var pI_=DJ(qj.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:vA(e,"boolean")}]});var _I_=DJ(qj.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:vA(e,"number")}]});var hI_=DJ(qj.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:vA(e,"string")}]});var yI_=DJ(qj.UNKNOWN,e=>({ok:!0,value:e}));function bI_(e,t){let r={parse:(i,n)=>vI_({value:i,isKeyNumeric:e.getType()===qj.NUMBER,transformKey:a=>e.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),json:(i,n)=>vI_({value:i,isKeyNumeric:e.getType()===qj.NUMBER,transformKey:a=>e.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),getType:()=>qj.RECORD};return{..._L(r),...Qq(r)}}function vI_({value:e,isKeyNumeric:t,transformKey:r,transformValue:i,breadcrumbsPrefix:n=[]}){return QAi(e)?WRa(e).reduce((a,[u,l])=>{if(l==null)return a;let d=a,s=u;if(t){let g=u.length>0?Number(u):NaN;isNaN(g)||(s=g)}let o=r(s),c=i(l,s);if(d.ok&&o.ok&&c.ok)return{ok:!0,value:{...d.value,[o.value]:c.value}};let b=[];return d.ok||b.push(...d.errors),o.ok||b.push(...o.errors),c.ok||b.push(...c.errors),{ok:!1,errors:b}},{ok:!0,value:{}}):{ok:!1,errors:[{path:n,message:vA(e,"object")}]}}function gI_(e){let t=kko(e),r={parse:(i,n)=>{let a=t.parse(i,n);return a.ok?{ok:!0,value:new Set(a.value)}:a},json:(i,n)=>i instanceof Set?t.json([...i],n):{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:vA(i,"Set")}]},getType:()=>qj.SET};return{..._L(r),...Qq(r)}}function mI_(e){let t={parse:(r,i)=>OI_((n,a)=>n.parse(r,a),e,i),json:(r,i)=>OI_((n,a)=>n.json(r,a),e,i),getType:()=>qj.UNDISCRIMINATED_UNION};return{..._L(t),...Qq(t)}}function OI_(e,t,r){let i=[];for(let[n,a]of t.entries()){let u=e(a,{...r,skipValidation:!1});if(u.ok)return u;for(let l of u.errors)i.push({path:l.path,message:`[Variant ${n}] ${l.message}`})}return{ok:!1,errors:i}}function PI_(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function wI_(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,i=typeof e=="string"?e:e.parsedDiscriminant,n=Xko($Ra(t)),a={parse:(u,l)=>jI_({value:u,discriminant:r,transformedDiscriminant:i,transformDiscriminantValue:d=>n.parse(d,{allowUnrecognizedEnumValues:l?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...l?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:l?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.parse(d,l),breadcrumbsPrefix:l?.breadcrumbsPrefix}),json:(u,l)=>jI_({value:u,discriminant:i,transformedDiscriminant:r,transformDiscriminantValue:d=>n.json(d,{allowUnrecognizedEnumValues:l?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...l?.breadcrumbsPrefix??[],i]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:l?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.json(d,l),breadcrumbsPrefix:l?.breadcrumbsPrefix}),getType:()=>qj.UNION};return{..._L(a),...Qq(a),...THt(a)}}function jI_({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:i,getAdditionalPropertiesSchema:n,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:u,breadcrumbsPrefix:l=[]}){if(!QAi(e))return{ok:!1,errors:[{path:l,message:vA(e,"object")}]};let{[t]:d,...s}=e;if(d==null)return{ok:!1,errors:[{path:l,message:`Missing discriminant ("${t}")`}]};let o=i(d);if(!o.ok)return{ok:!1,errors:o.errors};let c=n(o.value);if(c==null)return a?{ok:!0,value:{[r]:o.value,...s}}:{ok:!1,errors:[{path:[...l,t],message:"Unexpected discriminant value"}]};let b=u(s,c);return b.ok?{ok:!0,value:{[r]:d,...b.value}}:b}var $ir=ip.objectWithoutOptionalProperties({docs:ip.string().optional()});var yjc={};jo(yjc,{ConjureServiceName:()=>eeu,DefinitionFile:()=>SI_});var eeu=ip.string();var teu=ip.enum_(["rid","string","safelong","integer","double","boolean"]);var KAi=ip.undiscriminatedUnion([teu,ip.string()]);var reu=ip.objectWithoutOptionalProperties({alias:KAi,docs:ip.string().optional()});var ieu=ip.objectWithoutOptionalProperties({type:KAi,docs:ip.string().optional()});var YAi=ip.undiscriminatedUnion([KAi,ieu]);var neu=ip.objectWithoutOptionalProperties({union:ip.record(ip.string(),YAi)});var aeu=ip.objectWithoutOptionalProperties({fields:ip.record(ip.string(),YAi)});var oeu=ip.objectWithoutOptionalProperties({value:ip.string()}).extend($ir);var ueu=ip.undiscriminatedUnion([ip.string(),oeu]);var seu=ip.objectWithoutOptionalProperties({values:ip.list(ueu)});var ceu=ip.undiscriminatedUnion([reu,neu,aeu,seu]);var leu=ip.objectWithoutOptionalProperties({objects:ip.record(ip.string(),ceu).optional()});var feu=ip.objectWithoutOptionalProperties({conjureImports:ip.property("conjure-imports",ip.record(ip.string(),ip.string()).optional()),definitions:leu.optional()});var deu=ip.enum_(["none","header"]);var eLn=ip.undiscriminatedUnion([deu,ip.string()]);var peu=ip.enum_(["path","query","body"]);var _eu=ip.objectWithoutOptionalProperties({paramType:ip.property("param-type",peu),type:ip.string()}).extend($ir);var heu=ip.undiscriminatedUnion([ip.string(),_eu]);var yeu=ip.objectWithoutOptionalProperties({http:ip.string(),auth:eLn.optional(),args:ip.record(ip.string(),heu).optional(),returns:YAi.optional()}).extend($ir);var veu=ip.objectWithoutOptionalProperties({name:ip.string().optional(),package:ip.string().optional(),basePath:ip.property("base-path",ip.string().optional()),defaultAuth:ip.property("default-auth",eLn.optional()),endpoints:ip.record(ip.string(),yeu).optional()}).extend($ir);var SI_=ip.objectWithoutOptionalProperties({types:feu.optional(),services:ip.record(eeu,veu).optional()});var vjc={};jo(vjc,{ConjureArgument:()=>heu,ConjureArgumentWithParamType:()=>_eu,ConjureAuthDefinition:()=>eLn,ConjureAuthDefinitionType:()=>deu,ConjureEndpointDefinition:()=>yeu,ConjureParamType:()=>peu,ConjureService:()=>veu});var bjc={};jo(bjc,{ConjureAliasDeclaration:()=>reu,ConjureDefinitions:()=>leu,ConjureEnumDeclaration:()=>seu,ConjureEnumVariant:()=>ueu,ConjureEnumWithDocs:()=>oeu,ConjureObjectDeclaration:()=>aeu,ConjurePrimitive:()=>teu,ConjureType:()=>KAi,ConjureTypeDeclaration:()=>ceu,ConjureTypeReference:()=>YAi,ConjureTypeWithDocs:()=>ieu,ConjureTypes:()=>feu,ConjureUnionDeclaration:()=>neu});var DI_=require("fs/promises");async function EI_(e,t){let r=[];for(let i of await Vxe(e,t))r.push(await nKE({relativeFilepath:xq(e,i),absoluteFilepath:i}));return r}async function nKE({relativeFilepath:e,absoluteFilepath:t}){let r=(await(0,DI_.readFile)(t)).toString().replaceAll(/: rid(?:$|\s)/g,`: string
1962
1962
  `).replaceAll("<rid>","<string>").replaceAll("rid>","string>").replaceAll(": safelong",": long").replaceAll("<safelong>","<long>").replaceAll("safelong>","long>").replaceAll(": any",": unknown").replaceAll("<any>","<unknown>").replaceAll("any>","unknown>");return{relativeFilepath:e,absoluteFilepath:t,fileContents:beu.DefinitionFile.parseOrThrow(qd.load(r),{unrecognizedObjectKeys:"passthrough",allowUnrecognizedEnumValues:!0,allowUnrecognizedUnionMembers:!0})}}function MI_(e,t){if(aKE(e))return t.alias(e);if(oKE(e))return t.enum(e);if(uKE(e))return t.object(e);if(sKE(e))return t.union(e);mo(e)}function aKE(e){return e?.alias!=null}function oKE(e){return e?.values!=null}function uKE(e){return e?.fields!=null}function sKE(e){return e?.union!=null}var GRa=class extends UIa{fernDefinitionBuilder=new vJi(!1);conjureFilepathToFernFilepath={};async import({absolutePathToConjureFolder:t,authOverrides:r,environmentOverrides:i,globalHeaderOverrides:n}){if(r!=null){for(let[a,u]of Object.entries(r["auth-schemes"]??{}))this.fernDefinitionBuilder.addAuthScheme({name:a,schema:u});r.auth!=null&&this.fernDefinitionBuilder.setAuth(r.auth)}if(i!=null){for(let[a,u]of Object.entries(i.environments??{}))this.fernDefinitionBuilder.addEnvironment({name:a,schema:u});i["default-environment"]!=null&&this.fernDefinitionBuilder.setDefaultEnvironment(i["default-environment"]),i["default-url"]!=null&&this.fernDefinitionBuilder.setDefaultUrl(i["default-url"])}return await AI_(t,(a,u,l)=>{for(let[o,c]of Object.entries(l.services??{})){let b=oOo({value:o,suffix:"Service"});this.conjureFilepathToFernFilepath[u]=Qa.of(`${b}/__package__.yml`);return}let s=P2s(u)?.split(".")[0];s!=null&&(this.conjureFilepathToFernFilepath[u]=Qa.of(`${s}/__package__.yml`))}),await AI_(t,(a,u,l)=>{if(l.services==null||Object.keys(l.services??{}).length===0){let d=this.conjureFilepathToFernFilepath[u];if(d==null)throw new Error(`Failed to find corresponding fern filepath for conjure file ${u}`);for(let[s,o]of Object.entries(l.types?.conjureImports??{})){let c=this.getFernFileToImport({absoluteFilePathToConjureFile:a,absoluteFilePathToConjureFolder:t,importFilePath:Qa.of(o)});this.fernDefinitionBuilder.addImport({file:d,fileToImport:Qa.of(c),alias:s})}this.importAllTypes({conjureFile:l,fernFilePath:d});return}for(let[d,s]of Object.entries(l.services)){let o=oOo({value:d,suffix:"Service"}),c=Qa.of(`${o}/__package__.yml`),b={};s.basePath!=null&&(b["base-path"]=s.basePath),s.docs!=null&&(b.docs=s.docs),this.fernDefinitionBuilder.setServiceInfo(c,b),this.importAllTypes({conjureFile:l,fernFilePath:c});for(let[g,O]of Object.entries(l.types?.conjureImports??{})){let m=this.getFernFileToImport({absoluteFilePathToConjureFile:a,absoluteFilePathToConjureFolder:t,importFilePath:Qa.of(O)});this.fernDefinitionBuilder.addImport({file:c,fileToImport:Qa.of(m),alias:g})}for(let[g,O]of Object.entries(s.endpoints??{})){let m=q3s(O.http);if(m.type==="failure"){this.context?.logger.error(`Failed to parse ${O.http}. Skipping.`);continue}let E={auth:(O.auth??s.defaultAuth)!==XB_.None,path:m.path,method:m.method,response:O.returns==="binary"?"file":O.returns};O.docs!=null&&(E.docs=O.docs);let q={};if(O.args!=null)for(let M of m.pathParameters){let D=O.args[M];if(D==null)throw new Error(`Failed to find path parameter ${M} in ${O.http}`);q[M]=typeof D=="string"?D:{type:D.type}}Object.entries(q).length>0&&(E["path-parameters"]=q);for(let[M,D]of Object.entries(O.args??{}))if(q[M]==null)if(typeof D=="string")E.request?typeof E.request=="string"&&(E.request={body:E.request}):E.request={},E.request.body=D==="binary"?"bytes":D;else switch(D.paramType){case"body":E.request={body:D.type==="binary"?"bytes":D.type};break;case"query":E.request==null?E.request={"query-parameters":{[M]:D.type}}:typeof E.request!="string"&&E.request?.["query-parameters"]==null?E.request["query-parameters"]={[M]:D.type}:typeof E.request!="string"&&E.request?.["query-parameters"]!=null&&(E.request["query-parameters"][M]=D.type)}E.request!=null&&typeof E.request!="string"&&E.request?.["query-parameters"]!=null&&(E.request.name=`${g}Request`),this.fernDefinitionBuilder.addEndpoint(c,{name:g,schema:E,source:void 0})}}}),this.fernDefinitionBuilder.build()}importAllTypes({conjureFile:t,fernFilePath:r}){for(let[i,n]of Object.entries(t.types?.definitions?.objects??{}))MI_(n,{alias:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{type:a.alias,docs:a.docs}})},object:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{properties:a.fields}})},enum:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{enum:a.values}})},union:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{union:Object.fromEntries(Object.entries(a.union).map(([u,l])=>[u,{type:typeof l=="string"?l:l.type,docs:typeof l=="string"?void 0:l.docs,key:u}]))}})}})}getFernFileToImport({absoluteFilePathToConjureFile:t,importFilePath:r,absoluteFilePathToConjureFolder:i}){let n=Vu(Ud(t),Qa.of(r)),a=lne(i,n),u=this.conjureFilepathToFernFilepath[a];if(u==null)throw new Error(`Failed to find corresponding fern filepath for conjure file ${a}`);return u}};async function AI_(e,t){for(let r of await EI_(e,"{yml,yaml}"))await t(r.absoluteFilepath,r.relativeFilepath,r.fileContents)}function qI_(e,t){return dd(e,t)}var geu=class extends fHt{type="conjure";absolutePathToConjureFolder;constructor({relativePathToConjureDirectory:t,...r}){super(r),this.absolutePathToConjureFolder=Vu(r.absoluteFilePath,t)}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new EMe({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:i,cliVersion:this.cliVersion,sources:void 0})}async getDefinition({context:t},r){let n=await new GRa(t).import({absolutePathToConjureFolder:this.absolutePathToConjureFolder,authOverrides:this.generatorsConfiguration?.api?.auth!=null?{...this.generatorsConfiguration?.api}:void 0,environmentOverrides:this.generatorsConfiguration?.api?.environments!=null?{...this.generatorsConfiguration?.api}:void 0,globalHeaderOverrides:this.generatorsConfiguration?.api?.headers!=null?{...this.generatorsConfiguration?.api}:void 0});return{absoluteFilePath:hl.of("/DUMMY_PATH"),rootApiFile:{defaultUrl:n.rootApiFile["default-url"],contents:n.rootApiFile,rawContents:qd.dump(n.rootApiFile)},namedDefinitionFiles:{...qI_(n.definitionFiles,a=>({absoluteFilepath:hl.of("/DUMMY_PATH"),rawContents:qd.dump(a),contents:a})),[Qa.of(zS)]:{absoluteFilepath:hl.of("/DUMMY_PATH"),rawContents:qd.dump(n.packageMarkerFile),contents:n.packageMarkerFile}},packageMarkers:{},importedDefinitions:{}}}getAbsoluteFilePaths(){return[this.absolutePathToConjureFolder]}};function gjc(e,t){for(let[r,i]of r3(e.failures))cKE({relativeFilepath:r,failure:i,logger:t})}function cKE({relativeFilepath:e,failure:t,logger:r}){switch(t.type){case xP.MISCONFIGURED_DIRECTORY:r.error("Misconfigured fern directory: please see the docs at https://buildwithfern.com/learn/api-definition/introduction/what-is-the-fern-folder");break;case xP.FILE_READ:r.error("Failed to open file: "+e);break;case xP.FILE_MISSING:r.error("Missing file: "+e);break;case xP.FILE_PARSE:t.error instanceof bSa?r.error(OFe({title:`Failed to parse ${e}: ${t.error.reason}`,subtitle:t.error.mark.snippet})):r.error("Failed to parse file: "+e);break;case xP.STRUCTURE_VALIDATION:for(let i of t.error.issues)for(let{title:n,subtitle:a}of lKE(i))r.error(OFe({title:n,subtitle:a,breadcrumbs:[e,...i.path]}));break;case xP.FAILED_TO_LOAD_DEPENDENCY:r.error("Failed to load dependency: "+t.dependencyName);break;case xP.DEPENDENCY_NOT_LISTED:r.error(`Dependency is not listed in ${GOo}: `+t.dependencyName);break;case xP.EXPORT_PACKAGE_HAS_DEFINITIONS:r.error("Exported package contains API definitions: "+t.pathToPackage);break;case xP.EXPORTING_PACKAGE_MARKER_OTHER_KEYS:r.error(`${t.pathOfPackageMarker} has an export so it cannot define other keys.`);break;case xP.JSONSCHEMA_VALIDATION:t.error.error!=null&&r.error(OFe({title:t.error.error.message??"Unknown error",breadcrumbs:[e,...t.error.error.instancePath.split("/").filter(i=>i!=="")]}));break;default:mo(t)}}function lKE(e){switch(e.code){case Jl.invalid_type:return[{title:"Incorrect type",subtitle:`Expected ${Gs.underline(e.expected)} but received ${Gs.underline(e.received)}`}];case Jl.unrecognized_keys:return e.keys.map(t=>({title:"Unexpected key",subtitle:`Encountered unexpected key ${Gs.underline(t)}`}));case Jl.invalid_enum_value:return[{title:"Unrecognized value",subtitle:`Allowed values: ${e.options.map(t=>Gs.underline(t)).join(", ")}`}];case Jl.invalid_union:case Jl.invalid_arguments:case Jl.invalid_return_type:case Jl.invalid_date:case Jl.invalid_string:case Jl.too_small:case Jl.too_big:case Jl.invalid_intersection_types:case Jl.not_multiple_of:case Jl.custom:default:return[{title:e.message}]}}var TI_=require("fs/promises");async function CI_(e,t){let r=[];for(let i of await Vxe(e,t))r.push(await fKE({relativeFilepath:xq(e,i),absoluteFilepath:i}));return r}async function fKE({relativeFilepath:e,absoluteFilepath:t}){return{relativeFilepath:e,absoluteFilepath:t,fileContents:(await(0,TI_.readFile)(t)).toString()}}async function BI_({absolutePathToWorkspace:e}){let t=Vu(e,Qa.of(Lqd));if(!await Sf(t))return;let i=await CI_(t,"{md,mdx}");return{files:await Promise.all(i.map(n=>({absoluteFilepath:n.absoluteFilepath,contents:n.fileContents})))}}async function Ojc({absolutePathToWorkspace:e,namespace:t,definitions:r}){let i=[];for(let n of r){let a=n.overrides!=null?Vu(e,Qa.of(n.overrides)):void 0;if(n.schema.type==="protobuf"){let l=Qa.of(n.schema.root),d=Vu(e,l);if(!await Sf(d))return{didSucceed:!1,failures:{[Qa.of(n.schema.root)]:{type:xP.FILE_MISSING}}};let s=Vu(e,Qa.of(n.schema.target));if(!await Sf(s))return{didSucceed:!1,failures:{[Qa.of(n.schema.target)]:{type:xP.FILE_MISSING}}};i.push({type:"protobuf",absoluteFilepathToProtobufRoot:d,absoluteFilepathToProtobufTarget:s,absoluteFilepathToOverrides:a,relativeFilepathToProtobufRoot:l,generateLocally:n.schema.localGeneration,settings:{audiences:n.audiences??[],useTitlesAsName:n.settings?.shouldUseTitleAsName??!0,shouldUseUndiscriminatedUnionsWithLiterals:n.settings?.shouldUseUndiscriminatedUnionsWithLiterals??!1,shouldUseIdiomaticRequestNames:n.settings?.shouldUseIdiomaticRequestNames??!1,optionalAdditionalProperties:n.settings?.shouldUseOptionalAdditionalProperties??!0,coerceEnumsToLiterals:n.settings?.coerceEnumsToLiterals??!0,objectQueryParameters:n.settings?.objectQueryParameters??!1,respectReadonlySchemas:n.settings?.respectReadonlySchemas??!1,respectNullableSchemas:n.settings?.respectNullableSchemas??!1,onlyIncludeReferencedSchemas:n.settings?.onlyIncludeReferencedSchemas??!1,inlinePathParameters:n.settings?.inlinePathParameters??!1,disableExamples:!1,discriminatedUnionV2:n.settings?.shouldUseUndiscriminatedUnionsWithLiterals??!1,preserveSchemaIds:!1,asyncApiNaming:n.settings?.asyncApiMessageNaming??"v1",filter:n.settings?.filter,exampleGeneration:void 0,defaultFormParameterEncoding:n.settings?.defaultFormParameterEncoding,useBytesForBinaryResponse:n.settings?.useBytesForBinaryResponse??!1,respectForwardCompatibleEnums:n.settings?.respectForwardCompatibleEnums??!1,additionalPropertiesDefaultsTo:n.settings?.additionalPropertiesDefaultsTo??!1,typeDatesAsStrings:n.settings?.typeDatesAsStrings??!0}});continue}if(n.schema.type==="openrpc"){let l=Qa.of(n.schema.path),d=Vu(e,l);i.push({type:"openrpc",absoluteFilepath:d,absoluteFilepathToOverrides:a,namespace:t});continue}let u=Vu(e,Qa.of(n.schema.path));if(!await Sf(u))return{didSucceed:!1,failures:{[Qa.of(n.schema.path)]:{type:xP.FILE_MISSING}}};if(n.overrides!=null&&a!=null&&!await Sf(a))return{didSucceed:!1,failures:{[Qa.of(n.overrides)]:{type:xP.FILE_MISSING}}};i.push({type:"openapi",absoluteFilepath:u,absoluteFilepathToOverrides:a,settings:{audiences:n.audiences??[],useTitlesAsName:n.settings?.shouldUseTitleAsName??!0,shouldUseUndiscriminatedUnionsWithLiterals:n.settings?.shouldUseUndiscriminatedUnionsWithLiterals??!1,shouldUseIdiomaticRequestNames:n.settings?.shouldUseIdiomaticRequestNames??!1,optionalAdditionalProperties:n.settings?.shouldUseOptionalAdditionalProperties??!0,coerceEnumsToLiterals:n.settings?.coerceEnumsToLiterals??!0,objectQueryParameters:n.settings?.objectQueryParameters??!1,respectReadonlySchemas:n.settings?.respectReadonlySchemas??!1,respectNullableSchemas:n.settings?.respectNullableSchemas??!1,onlyIncludeReferencedSchemas:n.settings?.onlyIncludeReferencedSchemas??!1,inlinePathParameters:n.settings?.inlinePathParameters??!1,disableExamples:!1,discriminatedUnionV2:n.settings?.shouldUseUndiscriminatedUnionsWithLiterals??!1,preserveSchemaIds:!1,asyncApiNaming:n.settings?.asyncApiMessageNaming??"v1",filter:n.settings?.filter,exampleGeneration:n.settings?.exampleGeneration,defaultFormParameterEncoding:n.settings?.defaultFormParameterEncoding,useBytesForBinaryResponse:n.settings?.useBytesForBinaryResponse??!1,respectForwardCompatibleEnums:n.settings?.respectForwardCompatibleEnums??!1,additionalPropertiesDefaultsTo:n.settings?.additionalPropertiesDefaultsTo??!1,typeDatesAsStrings:n.settings?.typeDatesAsStrings??!0},source:{type:"openapi",file:u},namespace:t})}return i}async function QRa({absolutePathToWorkspace:e,context:t,cliVersion:r,workspaceName:i}){let n=await rWt({absolutePathToWorkspace:e,context:t}),a;try{a=await BI_({absolutePathToWorkspace:e})}catch{}if(n?.api!=null&&n?.api.type==="conjure")return{didSucceed:!0,workspace:new geu({workspaceName:i,absoluteFilePath:e,generatorsConfiguration:n,changelog:a,cliVersion:r,context:t,relativePathToConjureDirectory:Qa.of(n.api.pathToConjureDefinition)})};if(n?.api!=null&&(n.api.type==="singleNamespace"&&n.api.definitions.length>0||n.api.type==="multiNamespace")){let u=[];if(n.api.type==="singleNamespace"){let l=await Ojc({absolutePathToWorkspace:e,namespace:void 0,definitions:n.api.definitions});if(!Array.isArray(l))return l;u.push(...l)}else{for(let[l,d]of Object.entries(n.api.definitions)){let s=await Ojc({absolutePathToWorkspace:e,namespace:l,definitions:d});if(!Array.isArray(s))return s;u.push(...s)}if(n.api.rootDefinitions!=null){let l=await Ojc({absolutePathToWorkspace:e,namespace:void 0,definitions:n.api.rootDefinitions});if(!Array.isArray(l))return l;u.push(...l)}}return{didSucceed:!0,workspace:new SR({specs:u.filter(l=>l.type!=="openrpc"),allSpecs:u,workspaceName:i,absoluteFilePath:e,generatorsConfiguration:n,changelog:a,cliVersion:r})}}return await Sf(Vu(e,Qa.of(v9)))?{didSucceed:!0,workspace:new Vir({absoluteFilePath:e,generatorsConfiguration:n,workspaceName:i,changelog:a,context:t,cliVersion:r,loadAPIWorkspace:QRa})}:{didSucceed:!1,failures:{[Qa.of($Oo)]:{type:xP.MISCONFIGURED_DIRECTORY}}}}var II_=require("fs/promises");var mjc={};jo(mjc,{additionalProperties:()=>hKE,default:()=>vKE,definitions:()=>yKE,properties:()=>pKE,required:()=>_KE,type:()=>dKE});var dKE="object",pKE={instances:{type:"array",items:{$ref:"#/definitions/docs.DocsInstance"}},title:{oneOf:[{type:"string"},{type:"null"}]},analytics:{oneOf:[{$ref:"#/definitions/docs.AnalyticsConfig"},{type:"null"}]},announcement:{oneOf:[{$ref:"#/definitions/docs.AnnouncementConfig"},{type:"null"}]},roles:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.RoleId"}},{type:"null"}]},tabs:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/docs.TabConfig"}},{type:"null"}]},versions:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.VersionConfig"}},{type:"null"}]},products:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ProductConfig"}},{type:"null"}]},"landing-page":{oneOf:[{$ref:"#/definitions/docs.PageConfiguration"},{type:"null"}]},navigation:{oneOf:[{$ref:"#/definitions/docs.NavigationConfig"},{type:"null"}]},"navbar-links":{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.NavbarLink"}},{type:"null"}]},"footer-links":{oneOf:[{$ref:"#/definitions/docs.FooterLinksConfig"},{type:"null"}]},experimental:{oneOf:[{$ref:"#/definitions/docs.ExperimentalConfig"},{type:"null"}]},"default-language":{oneOf:[{$ref:"#/definitions/docs.ProgrammingLanguage"},{type:"null"}]},"ai-chat":{oneOf:[{$ref:"#/definitions/docs.AIChatConfig"},{type:"null"}]},"ai-search":{oneOf:[{$ref:"#/definitions/docs.AIChatConfig"},{type:"null"}]},metadata:{oneOf:[{$ref:"#/definitions/docs.MetadataConfig"},{type:"null"}]},redirects:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.RedirectConfig"}},{type:"null"}]},logo:{oneOf:[{$ref:"#/definitions/docs.LogoConfiguration"},{type:"null"}]},favicon:{oneOf:[{type:"string"},{type:"null"}]},"background-image":{oneOf:[{$ref:"#/definitions/docs.BackgroundImageConfiguration"},{type:"null"}]},colors:{oneOf:[{$ref:"#/definitions/docs.ColorsConfiguration"},{type:"null"}]},typography:{oneOf:[{$ref:"#/definitions/docs.DocsTypographyConfig"},{type:"null"}]},layout:{oneOf:[{$ref:"#/definitions/docs.LayoutConfig"},{type:"null"}]},integrations:{oneOf:[{$ref:"#/definitions/docs.IntegrationsConfig"},{type:"null"}]},css:{oneOf:[{$ref:"#/definitions/docs.CssConfig"},{type:"null"}]},js:{oneOf:[{$ref:"#/definitions/docs.JsConfig"},{type:"null"}]}},_KE=["instances"],hKE=!1,yKE={"docs.CustomDomain":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"docs.GithubEditThisPageConfig":{type:"object",properties:{host:{oneOf:[{type:"string"},{type:"null"}]},owner:{type:"string"},repo:{type:"string"},branch:{oneOf:[{type:"string"},{type:"null"}]}},required:["owner","repo"],additionalProperties:!1},"docs.EditThisPageConfig":{type:"object",properties:{github:{oneOf:[{$ref:"#/definitions/docs.GithubEditThisPageConfig"},{type:"null"}]}},additionalProperties:!1},"docs.DocsInstance":{type:"object",properties:{url:{type:"string"},"custom-domain":{oneOf:[{$ref:"#/definitions/docs.CustomDomain"},{type:"null"}]},private:{oneOf:[{type:"boolean"},{type:"null"}]},"edit-this-page":{oneOf:[{$ref:"#/definitions/docs.EditThisPageConfig"},{type:"null"}]}},required:["url"],additionalProperties:!1},"docs.SegmentConfig":{type:"object",properties:{"write-key":{type:"string"}},required:["write-key"],additionalProperties:!1},"docs.FullStoryAnalyticsConfig":{type:"object",properties:{"org-id":{type:"string"}},required:["org-id"],additionalProperties:!1},"docs.IntercomConfig":{type:"object",properties:{"app-id":{type:"string"},"api-base":{oneOf:[{type:"string"},{type:"null"}]}},required:["app-id"],additionalProperties:!1},"docs.PostHogConfig":{type:"object",properties:{"api-key":{type:"string"},endpoint:{oneOf:[{type:"string"},{type:"null"}]}},required:["api-key"],additionalProperties:!1},"docs.GTMConfig":{type:"object",properties:{"container-id":{type:"string"}},required:["container-id"],additionalProperties:!1},"docs.GoogleAnalytics4Config":{type:"object",properties:{"measurement-id":{type:"string"}},required:["measurement-id"],additionalProperties:!1},"docs.AnalyticsConfig":{type:"object",properties:{segment:{oneOf:[{$ref:"#/definitions/docs.SegmentConfig"},{type:"null"}]},fullstory:{oneOf:[{$ref:"#/definitions/docs.FullStoryAnalyticsConfig"},{type:"null"}]},intercom:{oneOf:[{$ref:"#/definitions/docs.IntercomConfig"},{type:"null"}]},posthog:{oneOf:[{$ref:"#/definitions/docs.PostHogConfig"},{type:"null"}]},gtm:{oneOf:[{$ref:"#/definitions/docs.GTMConfig"},{type:"null"}]},ga4:{oneOf:[{$ref:"#/definitions/docs.GoogleAnalytics4Config"},{type:"null"}]}},additionalProperties:!1},"docs.AnnouncementConfig":{type:"object",properties:{message:{type:"string"}},required:["message"],additionalProperties:!1},"docs.RoleId":{type:"string"},"docs.Role":{anyOf:[{$ref:"#/definitions/docs.RoleId"},{type:"array",items:{$ref:"#/definitions/docs.RoleId"}}]},"docs.FeatureFlag":{type:"object",properties:{flag:{type:"string"},"fallback-value":{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},match:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]}},required:["flag"],additionalProperties:!1},"docs.FeatureFlagConfiguration":{anyOf:[{type:"string",description:"The name of the feature flag, We assume that it is a boolean feature flag that needs to be evaluated to true."},{$ref:"#/definitions/docs.FeatureFlag",description:"A single feature flag with a configurable name, fallback value, and match value. Especially useful for non boolean feature flags."},{type:"array",items:{$ref:"#/definitions/docs.FeatureFlag"},description:"A list of feature flags. If any of the feature flags are satisfied, we will show all content."}]},"docs.ChangelogFolderRelativePath":{type:"string"},"docs.TabConfig":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},"display-name":{type:"string"},icon:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},href:{oneOf:[{type:"string"},{type:"null"}]},changelog:{oneOf:[{$ref:"#/definitions/docs.ChangelogFolderRelativePath"},{type:"null"}]}},required:["display-name"],additionalProperties:!1},"docs.VersionAvailability":{type:"string",enum:["deprecated","ga","stable","beta"]},"docs.VersionConfig":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},"display-name":{type:"string"},path:{type:"string"},slug:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/docs.VersionAvailability"},{type:"null"}]}},required:["display-name","path"],additionalProperties:!1},"docs.ProductConfig":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},"display-name":{type:"string"},path:{type:"string"},subtitle:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},image:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},versions:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.VersionConfig"}},{type:"null"}]}},required:["display-name","path"],additionalProperties:!1},"docs.PageConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},page:{type:"string"},path:{type:"string"},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},noindex:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["page","path"],additionalProperties:!1},"docs.SectionConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},section:{type:"string"},path:{oneOf:[{type:"string"},{type:"null"}]},contents:{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},collapsed:{oneOf:[{type:"boolean"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["section","contents"],additionalProperties:!1},"docs.AudienceId":{type:"string"},"docs.VersionedSnippetLanguageConfiguration":{type:"object",properties:{version:{type:"string"},package:{type:"string"}},required:["version","package"],additionalProperties:!1},"docs.SnippetLanguageConfiguration":{anyOf:[{type:"string"},{$ref:"#/definitions/docs.VersionedSnippetLanguageConfiguration"}]},"docs.SnippetsConfiguration":{type:"object",properties:{python:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},typescript:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},go:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},java:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},ruby:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},csharp:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]}},additionalProperties:!1},"docs.PlaygroundButtonSettings":{type:"object",properties:{href:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.PlaygroundSettings":{type:"object",properties:{environments:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},button:{oneOf:[{$ref:"#/definitions/docs.PlaygroundButtonSettings"},{type:"null"}]},oauth:{oneOf:[{type:"boolean"},{type:"null"}]},"limit-websocket-messages-per-connection":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"docs.ApiReferencePackageConfigurationWithOptions":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},title:{oneOf:[{type:"string"},{type:"null"}]},summary:{oneOf:[{type:"string"},{type:"null"}]},contents:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},additionalProperties:!1},"docs.ApiReferencePackageConfiguration":{anyOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{$ref:"#/definitions/docs.ApiReferencePackageConfigurationWithOptions"}]},"docs.ApiReferenceSectionConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},section:{type:"string"},"referenced-packages":{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},summary:{oneOf:[{type:"string"},{type:"null"}]},contents:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},required:["section"],additionalProperties:!1},"docs.ApiReferenceEndpointConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},endpoint:{type:"string"},title:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"docs.LinkConfiguration":{type:"object",properties:{link:{type:"string"},href:{type:"string"},icon:{oneOf:[{type:"string"},{type:"null"}]}},required:["link","href"],additionalProperties:!1},"docs.ApiReferenceLayoutItem":{anyOf:[{type:"string",description:"This should be either an endpoint, websocket, webhook, or subpackage ID"},{type:"object",additionalProperties:{$ref:"#/definitions/docs.ApiReferencePackageConfiguration"},description:"Keyed by subpackage name, this object allows you to group endpoints and pages together."},{$ref:"#/definitions/docs.ApiReferenceSectionConfiguration"},{$ref:"#/definitions/docs.ApiReferenceEndpointConfiguration"},{$ref:"#/definitions/docs.PageConfiguration"},{$ref:"#/definitions/docs.LinkConfiguration"}]},"docs.ApiReferenceConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},api:{type:"string"},"api-name":{oneOf:[{type:"string"},{type:"null"}]},openrpc:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.AudienceId"}},{type:"null"}]},"display-errors":{oneOf:[{type:"boolean"},{type:"null"}]},snippets:{oneOf:[{$ref:"#/definitions/docs.SnippetsConfiguration"},{type:"null"}]},summary:{oneOf:[{type:"string"},{type:"null"}]},layout:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},alphabetized:{oneOf:[{type:"boolean"},{type:"null"}]},flattened:{oneOf:[{type:"boolean"},{type:"null"}]},paginated:{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},required:["api"],additionalProperties:!1},"docs.ChangelogConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},changelog:{$ref:"#/definitions/docs.ChangelogFolderRelativePath"},title:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["changelog"],additionalProperties:!1},"docs.NavigationItem":{anyOf:[{$ref:"#/definitions/docs.PageConfiguration"},{$ref:"#/definitions/docs.SectionConfiguration"},{$ref:"#/definitions/docs.ApiReferenceConfiguration"},{$ref:"#/definitions/docs.LinkConfiguration"},{$ref:"#/definitions/docs.ChangelogConfiguration"}]},"docs.UntabbedNavigationConfig":{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},"docs.TabId":{type:"string"},"docs.TabbedNavigationItem":{type:"object",properties:{tab:{$ref:"#/definitions/docs.TabId"},layout:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},{type:"null"}]}},required:["tab"],additionalProperties:!1},"docs.TabbedNavigationConfig":{type:"array",items:{$ref:"#/definitions/docs.TabbedNavigationItem"}},"docs.NavigationConfig":{anyOf:[{$ref:"#/definitions/docs.UntabbedNavigationConfig"},{$ref:"#/definitions/docs.TabbedNavigationConfig"}]},"docs.NavbarGithubConfig":{type:"string"},"docs.NavbarLink":{type:"object",properties:{type:{type:"string",enum:["filled","outlined","minimal","github","primary","secondary"]}},oneOf:[{properties:{type:{const:"filled"},href:{oneOf:[{type:"string"},{type:"null"}]},url:{oneOf:[{type:"string"},{type:"null"}]},text:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},rightIcon:{oneOf:[{type:"string"},{type:"null"}]},rounded:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"]},{properties:{type:{const:"outlined"},href:{oneOf:[{type:"string"},{type:"null"}]},url:{oneOf:[{type:"string"},{type:"null"}]},text:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},rightIcon:{oneOf:[{type:"string"},{type:"null"}]},rounded:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"]},{properties:{type:{const:"minimal"},href:{oneOf:[{type:"string"},{type:"null"}]},url:{oneOf:[{type:"string"},{type:"null"}]},text:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},rightIcon:{oneOf:[{type:"string"},{type:"null"}]},rounded:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"]},{properties:{type:{const:"github"},value:{$ref:"#/definitions/docs.NavbarGithubConfig"}},required:["type"]},{properties:{type:{const:"primary"},href:{oneOf:[{type:"string"},{type:"null"}]},url:{oneOf:[{type:"string"},{type:"null"}]},text:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},rightIcon:{oneOf:[{type:"string"},{type:"null"}]},rounded:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"]},{properties:{type:{const:"secondary"},href:{oneOf:[{type:"string"},{type:"null"}]},url:{oneOf:[{type:"string"},{type:"null"}]},text:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},rightIcon:{oneOf:[{type:"string"},{type:"null"}]},rounded:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"]}]},"docs.FooterLinksConfig":{type:"object",properties:{github:{oneOf:[{type:"string"},{type:"null"}]},twitter:{oneOf:[{type:"string"},{type:"null"}]},x:{oneOf:[{type:"string"},{type:"null"}]},linkedin:{oneOf:[{type:"string"},{type:"null"}]},youtube:{oneOf:[{type:"string"},{type:"null"}]},instagram:{oneOf:[{type:"string"},{type:"null"}]},facebook:{oneOf:[{type:"string"},{type:"null"}]},discord:{oneOf:[{type:"string"},{type:"null"}]},slack:{oneOf:[{type:"string"},{type:"null"}]},hackernews:{oneOf:[{type:"string"},{type:"null"}]},medium:{oneOf:[{type:"string"},{type:"null"}]},website:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.ExperimentalConfig":{type:"object",properties:{"mdx-components":{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"disable-stream-toggle":{oneOf:[{type:"boolean"},{type:"null"}]},"openapi-parser-v2":{oneOf:[{type:"boolean"},{type:"null"}]},"openapi-parser-v3":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"docs.ProgrammingLanguage":{type:"string",enum:["typescript","javascript","python","java","go","ruby","csharp","nodets","nodejs","dotnet","curl","jvm","ts","js"]},"docs.AIChatModel":{type:"string",enum:["claude-3.5","claude-3.7","claude-4","command-a"]},"docs.AIChatConfig":{type:"object",properties:{model:{oneOf:[{$ref:"#/definitions/docs.AIChatModel"},{type:"null"}]},"system-prompt":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.TwitterCardSetting":{type:"string",enum:["summary","summary_large_image","app","player"]},"docs.MetadataConfig":{type:"object",properties:{"og:site_name":{oneOf:[{type:"string"},{type:"null"}]},"og:title":{oneOf:[{type:"string"},{type:"null"}]},"og:description":{oneOf:[{type:"string"},{type:"null"}]},"og:url":{oneOf:[{type:"string"},{type:"null"}]},"og:image":{oneOf:[{type:"string"},{type:"null"}]},"og:image:width":{oneOf:[{type:"number"},{type:"null"}]},"og:image:height":{oneOf:[{type:"number"},{type:"null"}]},"og:locale":{oneOf:[{type:"string"},{type:"null"}]},"og:logo":{oneOf:[{type:"string"},{type:"null"}]},"twitter:title":{oneOf:[{type:"string"},{type:"null"}]},"twitter:description":{oneOf:[{type:"string"},{type:"null"}]},"twitter:handle":{oneOf:[{type:"string"},{type:"null"}]},"twitter:image":{oneOf:[{type:"string"},{type:"null"}]},"twitter:site":{oneOf:[{type:"string"},{type:"null"}]},"twitter:url":{oneOf:[{type:"string"},{type:"null"}]},"twitter:card":{oneOf:[{$ref:"#/definitions/docs.TwitterCardSetting"},{type:"null"}]}},additionalProperties:!1},"docs.RedirectConfig":{type:"object",properties:{source:{type:"string"},destination:{type:"string"},permanent:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["source","destination"],additionalProperties:!1},"docs.LogoConfiguration":{type:"object",properties:{dark:{oneOf:[{type:"string"},{type:"null"}]},light:{oneOf:[{type:"string"},{type:"null"}]},height:{oneOf:[{type:"number"},{type:"null"}]},href:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.BackgroundImageThemedConfig":{type:"object",properties:{dark:{oneOf:[{type:"string"},{type:"null"}]},light:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.BackgroundImageConfiguration":{anyOf:[{type:"string"},{$ref:"#/definitions/docs.BackgroundImageThemedConfig"}]},"docs.ColorThemedConfig":{type:"object",properties:{dark:{oneOf:[{type:"string"},{type:"null"}]},light:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.ColorConfig":{anyOf:[{type:"string"},{$ref:"#/definitions/docs.ColorThemedConfig"}]},"docs.ColorsConfiguration":{type:"object",properties:{"accent-primary":{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]},accentPrimary:{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]},background:{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]},border:{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]},"sidebar-background":{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]},"header-background":{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]},"card-background":{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]}},additionalProperties:!1},"docs.FontWeight":{anyOf:[{type:"string"},{type:"integer"}]},"docs.FontStyle":{type:"string",enum:["normal","italic"]},"docs.FontConfigVariant":{type:"object",properties:{path:{type:"string"},weight:{oneOf:[{$ref:"#/definitions/docs.FontWeight"},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/docs.FontStyle"},{type:"null"}]}},required:["path"],additionalProperties:!1},"docs.FontConfigPath":{anyOf:[{type:"string"},{$ref:"#/definitions/docs.FontConfigVariant"}]},"docs.FontDisplay":{type:"string",enum:["auto","block","swap","fallback","optional"]},"docs.FontConfig":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},path:{oneOf:[{type:"string"},{type:"null"}]},weight:{oneOf:[{$ref:"#/definitions/docs.FontWeight"},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/docs.FontStyle"},{type:"null"}]},paths:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.FontConfigPath"}},{type:"null"}]},display:{oneOf:[{$ref:"#/definitions/docs.FontDisplay"},{type:"null"}]},fallback:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"font-variation-settings":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.DocsTypographyConfig":{type:"object",properties:{headingsFont:{oneOf:[{$ref:"#/definitions/docs.FontConfig"},{type:"null"}]},bodyFont:{oneOf:[{$ref:"#/definitions/docs.FontConfig"},{type:"null"}]},codeFont:{oneOf:[{$ref:"#/definitions/docs.FontConfig"},{type:"null"}]}},additionalProperties:!1},"docs.SearchbarPlacement":{type:"string",enum:["header","header-tabs","sidebar"]},"docs.TabsPlacement":{type:"string",enum:["header","sidebar"]},"docs.ContentAlignment":{type:"string",enum:["center","left"]},"docs.HeaderPosition":{type:"string",enum:["fixed","static"]},"docs.LayoutConfig":{type:"object",properties:{"page-width":{oneOf:[{type:"string"},{type:"null"}]},"content-width":{oneOf:[{type:"string"},{type:"null"}]},"sidebar-width":{oneOf:[{type:"string"},{type:"null"}]},"header-height":{oneOf:[{type:"string"},{type:"null"}]},"searchbar-placement":{oneOf:[{$ref:"#/definitions/docs.SearchbarPlacement"},{type:"null"}]},"tabs-placement":{oneOf:[{$ref:"#/definitions/docs.TabsPlacement"},{type:"null"}]},"content-alignment":{oneOf:[{$ref:"#/definitions/docs.ContentAlignment"},{type:"null"}]},"header-position":{oneOf:[{$ref:"#/definitions/docs.HeaderPosition"},{type:"null"}]},"disable-header":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"docs.IntegrationsConfig":{type:"object",properties:{intercom:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.CssConfig":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"docs.JsScriptStrategy":{type:"string",enum:["beforeInteractive","afterInteractive","lazyOnload"]},"docs.JsRemoteConfig":{type:"object",properties:{url:{type:"string"},strategy:{oneOf:[{$ref:"#/definitions/docs.JsScriptStrategy"},{type:"null"}]}},required:["url"],additionalProperties:!1},"docs.JsFileConfigSettings":{type:"object",properties:{path:{type:"string"},strategy:{oneOf:[{$ref:"#/definitions/docs.JsScriptStrategy"},{type:"null"}]}},required:["path"],additionalProperties:!1},"docs.JsFileConfig":{anyOf:[{type:"string"},{$ref:"#/definitions/docs.JsFileConfigSettings"}]},"docs.JsConfigOptions":{anyOf:[{$ref:"#/definitions/docs.JsRemoteConfig"},{$ref:"#/definitions/docs.JsFileConfig"}]},"docs.JsConfig":{anyOf:[{$ref:"#/definitions/docs.JsConfigOptions"},{type:"array",items:{$ref:"#/definitions/docs.JsConfigOptions"}}]}},vKE={type:dKE,properties:pKE,required:_KE,additionalProperties:hKE,definitions:yKE};async function Pjc({fernDirectory:e,context:t}){let r=Vu(e,Qa.of(bVt));if(!await Sf(r))return;let i=await bKE({absolutePathToDocsDefinition:e,context:t});if(i!=null)return{type:"docs",absoluteFilePath:e,config:i,workspaceName:void 0,absoluteFilepathToDocsConfig:Vu(e,Qa.of(bVt))}}async function bKE({absolutePathToDocsDefinition:e,context:t}){if(!await Sf(e))return;let r=Vu(e,Qa.of(bVt));return await gKE({absolutePathOfConfiguration:r,context:t})}async function gKE({absolutePathOfConfiguration:e,context:t}){let r=await(0,II_.readFile)(e),i=qd.load(r.toString()),n=vVt(i,mjc);if(n.success)return cne.RawSchemas.Serializer.DocsConfiguration.parseOrThrow(i);throw new Error(`Failed to parse docs.yml because of ${n.error?.message??"Unknown error"}`)}async function jjc({context:e,nameOverride:t,...r}){let i=await MVt(t);return i==null?e.failAndThrow(`Directory "${t??cW}" not found.`):await xI_({absolutePathToFernDirectory:i,context:e,nameOverride:t,...r})}async function xI_({absolutePathToFernDirectory:e,cliName:t,cliVersion:r,commandLineApiWorkspace:i,defaultToAllApiWorkspaces:n,context:a}){let u=[];return(await Sf(Vu(e,Qa.of(Owi)))||await Sf(Vu(e,Qa.of(v9)))||await Sf(Vu(e,Qa.of(a3)))||await Sf(Vu(e,Qa.of($Oo)))||await Sf(Vu(e,Qa.of(Uqd))))&&(u=await RI_({cliName:t,fernDirectory:e,cliVersion:r,context:a,commandLineApiWorkspace:i,defaultToAllApiWorkspaces:n})),{config:await kli({directory:e,context:a}),apiWorkspaces:u,docsWorkspaces:await Pjc({fernDirectory:e,context:a}),loadAPIWorkspace:l=>l==null?u[0]:u.find(d=>d.workspaceName===l)}}async function RI_({cliName:e,fernDirectory:t,context:r,cliVersion:i,commandLineApiWorkspace:n,defaultToAllApiWorkspaces:a}){let u=Vu(t,Qa.of(Owi));if(await Sf(u)){let o=(await(0,zI_.readdir)(u,{withFileTypes:!0})).reduce((g,O)=>(O.isDirectory()&&g.push(O.name),g),[]);if(n!=null){if(!o.includes(n))return r.failAndThrow("API does not exist: "+n)}else{if(o.length===0)return r.failAndThrow("No APIs found.");if(o.length>1&&!a){let g=`There are multiple workspaces. You must specify one with --api:
1963
1963
  `,O=Math.max(...o.map(m=>m.length));return g+=o.map(m=>{let P=`${e} ${process.argv.slice(2).join(" ")} --api ${m}`;return` \u203A ${Gs.bold(m.padEnd(O))} ${Gs.dim(P)}`}).join(`
@@ -1971,8 +1971,7 @@ ${b}
1971
1971
  \`\`\``,b=b.split(`
1972
1972
  `).map(q=>s+q).join(`
1973
1973
  `),b=b+`
1974
- `,u=u.replace(d,b),i.logger.error(`Generated markdown:
1975
- ${u}`)}catch{i.logger.warn(`Failed to read markdown file "${o}" referenced in ${r}`);break}}return u}var a3_=require("fs/promises"),o3_=ci(Trr(),1);async function IiM(e){let{content:t}=(0,o3_.default)(await(0,a3_.readFile)(e));return t}async function Jwc({markdown:e,absolutePathToFernFolder:t,absolutePathToMarkdownFile:r,context:i,markdownLoader:n=IiM}){if(!e.includes("<Markdown"))return e;let a=/([ \t]*)<Markdown\s+src={?['"]([^'"]+.mdx?)['"](?! \+)}?\s*\/>/g,u=e,l;for(;(l=a.exec(e))!=null;){let d=l[0],s=l[1],o=l[2];if(d==null||o==null)throw new Error(`Failed to parse regex "${l}" in ${r}`);let c=pb(o.startsWith("/")?t:Ud(r),Qa.of(o.replace(/^\//,"")));try{let b=await n(c);b=b.split(`
1974
+ `,u=u.replace(d,b)}catch{i.logger.warn(`Failed to read markdown file "${o}" referenced in ${r}`);break}}return u}var a3_=require("fs/promises"),o3_=ci(Trr(),1);async function IiM(e){let{content:t}=(0,o3_.default)(await(0,a3_.readFile)(e));return t}async function Jwc({markdown:e,absolutePathToFernFolder:t,absolutePathToMarkdownFile:r,context:i,markdownLoader:n=IiM}){if(!e.includes("<Markdown"))return e;let a=/([ \t]*)<Markdown\s+src={?['"]([^'"]+.mdx?)['"](?! \+)}?\s*\/>/g,u=e,l;for(;(l=a.exec(e))!=null;){let d=l[0],s=l[1],o=l[2];if(d==null||o==null)throw new Error(`Failed to parse regex "${l}" in ${r}`);let c=pb(o.startsWith("/")?t:Ud(r),Qa.of(o.replace(/^\//,"")));try{let b=await n(c);b=b.split(`
1976
1975
  `).map(g=>s+g).join(`
1977
1976
  `),u=u.replace(d,b)}catch{i.logger.warn(`Failed to read markdown file "${o}" referenced in ${r}`);break}}return u}var pqi={};jo(pqi,{ApiDefinitionId:()=>xKi,ApiDefinitionV1ToLatest:()=>E1c,ApiId:()=>LKi,AuthSchemeId:()=>Kwc,Availability:()=>hH,DocsConfigId:()=>UKi,EndpointId:()=>WKi,EndpointPathLiteral:()=>kKi,EnvironmentId:()=>VKi,FileId:()=>JKi,HttpMethod:()=>eYi,JqString:()=>YKi,ObjectPropertyAccess:()=>Zwc,OrgId:()=>NKi,PageId:()=>QKi,PropertyKey:()=>XKi,RoleId:()=>ZKi,STATUS_CODE_MESSAGES:()=>Q6_,STATUS_CODE_MESSAGES_METHOD_OVERRIDES:()=>J6_,SubpackageId:()=>ANa,TokenId:()=>FKi,Transformer:()=>M1c,TypeId:()=>GKi,Url:()=>KKi,VersionId:()=>RKi,WebSocketId:()=>HKi,WebhookHttpMethod:()=>kwc,WebhookId:()=>$Ki,auth:()=>ftu,backfillSnippets:()=>iaM,buildEndpointUrl:()=>A1c,buildRequestUrl:()=>K6_,cleanLanguage:()=>g1c,collectTypeDefinitionTree:()=>p3_,collectTypeDefinitionTreeForObjectProperty:()=>HiM,commons:()=>Ywc,convertToCurl:()=>CNa,createEndpointContext:()=>YiM,createWebSocketContext:()=>XiM,createWebhookContext:()=>ZiM,endpoint:()=>Xwc,getApiLatest:()=>_tu,getMessageForStatus:()=>S1c,getUrlQueriesGetString:()=>$6_,joiner:()=>rnM,prune:()=>qNa,toColonEndpointPathLiteral:()=>enM,toCurlyBraceEndpointPathLiteral:()=>tnM,toSnippetHttpRequest:()=>TNa,type_:()=>dtu,unwrapDiscriminatedUnionVariant:()=>d1c,unwrapObjectType:()=>nYi,unwrapReference:()=>kir,webhook:()=>ptu,websocket:()=>e1c,wrapOpenRPCRequest:()=>m1c});var t1c={};jo(t1c,{AuthSchemeId:()=>Kwc,ObjectPropertyAccess:()=>Zwc,WebhookHttpMethod:()=>kwc,auth:()=>ftu,commons:()=>Ywc,endpoint:()=>Xwc,getApiLatest:()=>_tu,type_:()=>dtu,webhook:()=>ptu,websocket:()=>e1c});var ftu={};jo(ftu,{AuthSchemeId:()=>Kwc});function Kwc(e){return e}var Ywc={};var Xwc={};var dtu={};jo(dtu,{ObjectPropertyAccess:()=>Zwc});var Zwc={ReadOnly:"READ_ONLY",WriteOnly:"WRITE_ONLY"};var ptu={};jo(ptu,{WebhookHttpMethod:()=>kwc});var kwc={Get:"GET",Post:"POST"};var e1c={};var _tu={};jo(_tu,{Error:()=>ziM});var ziM={apiDoesNotExistError:()=>({error:"ApiDoesNotExistError"}),_unknown:e=>({error:void 0,content:e}),_visit:(e,t)=>{switch(e.error){case"ApiDoesNotExistError":return t.apiDoesNotExistError();default:return t._other(e)}}};var a1c={};jo(a1c,{SubpackageId:()=>ANa,WebSocketMessageId:()=>r1c,WebSocketMessageOrigin:()=>i1c,WebhookHttpMethod:()=>n1c});function ANa(e){return e}function r1c(e){return e}var i1c={Client:"client",Server:"server"};var n1c={Get:"GET",Post:"POST"};var o1c={};jo(o1c,{ApiDefinitionId:()=>xKi,ApiId:()=>LKi,Availability:()=>hH,DocsConfigId:()=>UKi,EndpointId:()=>WKi,EndpointPathLiteral:()=>kKi,EnvironmentId:()=>VKi,FileId:()=>JKi,HttpMethod:()=>eYi,JqString:()=>YKi,OrgId:()=>NKi,PageId:()=>QKi,PropertyKey:()=>XKi,RoleId:()=>ZKi,TokenId:()=>FKi,TypeId:()=>GKi,Url:()=>KKi,VersionId:()=>RKi,WebSocketId:()=>HKi,WebhookId:()=>$Ki});function xKi(e){return e}function RKi(e){return e}function NKi(e){return e}function FKi(e){return e}function LKi(e){return e}function UKi(e){return e}function VKi(e){return e}function WKi(e){return e}function HKi(e){return e}function $Ki(e){return e}function GKi(e){return e}function QKi(e){return e}function JKi(e){return e}function KKi(e){return e}function YKi(e){return e}function XKi(e){return e}function ZKi(e){return e}function kKi(e){return e}var eYi={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD"};var hH={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var htu=[hH.Stable,hH.GenerallyAvailable,hH.Beta,hH.PreRelease,hH.InDevelopment,hH.Deprecated];function tYi(e){for(let t of[...htu].reverse())if(e.includes(t))return t}function rYi(e){let t=[];for(let r=0;r<e.length;r++){let i=e[r];i&&t.push(i)}return t}function u1c(e,t){let r=new Set(t);return e.filter(i=>!r.has(i))}function s1c(e,t){let r={};for(let i=0;i<e.length;i++){let n=e[i],a=t(n);r[a]=n}return r}function s3_(e,t,r){return e<t?r==="asc"?-1:1:e>t?r==="asc"?1:-1:0}function c3_(e,t,r){return e.slice().sort((i,n)=>{let a=r.length;for(let u=0;u<t.length;u++){let l=a>u?r[u]:r[a-1],d=t[u],s=typeof d=="function",o=s?d(i):i[d],c=s?d(n):n[d],b=s3_(o,c,l);if(b!==0)return b}return 0})}function ytu(e,t){return c3_(e,t,["asc"])}function c1c(e){throw new Error("Unexpected value: "+JSON.stringify(e))}var U3=c1c;var l1c=Object.freeze([]),xiM=Object.freeze({});function RiM(e){return e}var KA=RiM;function oqi(e){return e!=null}function mLn(e){if(!NiM(e)||String(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)==null)return!0;let t=e;for(;Object.getPrototypeOf(t)!=null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function NiM(e){return typeof e=="object"&&e!=null}var PLn=mLn;var f3_=ci(PIn(),1);var l3_=["PII","PHI","PCI","GDPR","CCPA","HIPAA","COPPA","FERPA","GLBA","SOX","FISMA","NIST","CIS","ISO","IEC","ITAR","EAR","CMMC","CUI","CDI","FTC","FCC","SEC","FINRA","XSS","CSRF","SSRF","XSRF","TLS","SSL","SSH","API","OAuth","OAuth1","OAuth1.0","OAuth2","OAuth2.0","SAML","OpenID","OpenID Connect","CAPTCHA","reCAPTCHA","2FA","MFA","OTP","TOTP","HOTP","U2F","FIDO","FIDO2","PKI","HMAC","AES","RSA","SHA","MD5","BCrypt","PBKDF2","Argon2","SCrypt","JWT","JWE","JWS","JWK","JWA","JOSE","SKU","SKUs","UPC","EAN","ISBN","ASIN","MPN","MSRP","MAP","RRP","MSRP","AM","PM","UTC","GMT","PST","PDT","EST","EDT","CST","CDT","MST","MDT","USA","UK","EU","UAE","APAC","EMEA","LATAM","ANZ","SEA","MEA","MENA","NATO","NA","SA","CA","EU","AU","NZ","JP","KR","CN","HK","TW","SG","MY","TH","ID","PH","VN","IN","PK","BD","LK","NP","MM","KH","LA","MM","BT","MV","USD","EUR","GBP","JPY","CNY","RUB","INR","AUD","CAD","CHF","SGD","MYR","THB","IDR","KRW","PHP","VND","HKD","TWD","MXN","BRL","ARS","CLP","COP","PEN","ZAR","NGN","EGP","AED","SAR","ILS","TRY","SEK","NOK","DKK","ISK","HUF","PLN","CZK","RON","BGN","API","APIs","SDK","SDKs","AI","OCR","REST","SOAP","JSON","XML","HTTP","HTTPS","URI","URL","CRUD","RESTful","KYB","KYC","AML","HTML","CSS","JS","SQL","DB","UI","UX","SaaS","PaaS","IaaS","IP","TCP","UDP","DNS","FTP","SMTP","IMAP","POP3","CSV","MVC","MVP","MVVM","DOM","SPA","SSR","CSR","DDoS","CDN","IoT","ML","DL","NLP","CLI","GUI","BI","ETL","RDBMS","NoSQL","IDE","CMS","CCPA","POSIX","ABI","API","AST","COBOL","DDL","DML","NN","CNN","RNN","LSTM","GRU","ANN","GAN","RL","DL","ML","NLP","NLG","NLU","BERT","GPT","SVM","PCA","AI","CV","TF","TTS","ASR","HMM","DNN","MLP","RBM","CRF","PDF","PDFs","RTF","TXT","XLS","XLSX","PPT","JPG","JPEG","PNG","GIF","GIFs","SVG","TIFF","BMP","ICO","PSD","WebP","AVIF","HEIF","HEIC","EPS","MP3","WAV","AIFF","FLAC","WMA","AAC","OGG","AVI","WMV","MOV","M4V","MP4","MPG","MPEG","FLV","SWF","MKV","WebM","GCP","AWS","VM","VPC","S3","EC2","DynamoDB","CosmosDB","BigQuery","CI/CD","SOC1","SOC2","SOC3","PCI DSS","WAF","IAM","SDN","MPLS","BGP","Vue.js","Node.js",".NET"];function FiM(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,f3_.default)(e,{special:l3_}).replace(/V\s(\d)/g,"V$1")}var iYi=FiM;function VMe(e,{renderNull:t=!1}={}){return e==null||typeof e=="function"?t?"null":"":typeof e=="string"?e:JSON.stringify(e)}function jLn(e,t="type"){return{_visit:r=>{let i=r[e[t]];return i!=null?i(e):(r._other==null&&c1c(e),r._other(e))}}}var Ky=jLn;var d3_=new WeakMap;function kir(e,t){if(e==null)return;let r=d3_.get(e);if(r!=null)return r;let i=!1,n=!1,a=[],u=[],l=[],d=new Set,s=e,o=0,c=!1;for(;s!=null;){if(o>100){s=void 0;break}if(s.type==="nullable")n=!0,s=s.shape;else if(s.type==="optional")i=!0,s.default!=null&&a.push({type:"unknown",value:s.default}),s=s.shape;else if(s.type==="alias")s=s.value;else if(s.type==="id"){if(d.has(s.id)){s=void 0,c=!0;break}s.default!=null&&a.push({type:"typeReferenceId",value:s.default});let g=t[s.id];d.add(s.id),s=g?.shape,g!=null&&(g.availability&&l.push(g.availability),g.description!=null&&u.push(g.description))}else break;o++}s==null&&console.error(c?`Circular reference detected. Falling back to unknown type. types=[${[...d].join(", ")}]`:`Type reference is invalid. Falling back to unknown type. types=[${[...d].join(", ")}]`);let b={shape:s??{type:"unknown",displayName:void 0},availability:tYi(l),visitedTypeIds:d,isOptional:i,isNullable:n,default:UiM(s,a),descriptions:u};return d3_.set(e,b),b}function UiM(e,t){if(e?.type==="literal")return e.value.value;let r=t.find(i=>e==null?!0:i.type==="typeReferenceId"?Ky(i.value)._visit({enum:()=>e?.type==="enum"}):!0);return r?.type==="unknown"?r.value:r?.type==="typeReferenceId"?r.value.value:e?.type==="primitive"?ViM(e.value):e?.type==="enum"?e.default:void 0}var f1c=new WeakMap;function nYi(e,t,r){let i=f1c.get(e);if(i!=null)return i;let n=e.properties,a=e.extraProperties,u=[],l=new Set,d=e.extends.flatMap(g=>{if(r?.has(g))return console.error(`Circular reference detected. Cannot extend type=${g}`),[];let O=t[g];l.add(g),O?.description&&u.push(O.description);let m=kir(O?.shape,t);if(m?.descriptions.forEach(E=>u.push(E)),m?.visitedTypeIds.forEach(E=>l.add(E)),m?.shape.type!=="object")return console.error("Object extends non-object",g),[];let P=nYi(m.shape,t,l);return P.visitedTypeIds.forEach(E=>l.add(E)),P.properties=P.properties.map(E=>({...E,availability:tYi(rYi([O?.availability,m.availability,E.availability]))})),u.push(...P.descriptions),m.isOptional?P.properties.map(E=>{let q=mLn(m.default)?m.default[E.key]:void 0,M=E.valueShape.type==="alias"&&E.valueShape.value.type==="optional"?{...E.valueShape.value,default:q??E.valueShape.value.default}:{type:"optional",shape:E.valueShape,default:q};return{...E,valueShape:{type:"alias",value:M}}}):P.properties});if(d.length===0){let O={properties:ytu([...n],[m=>kir(m.valueShape,t)?.isOptional,m=>htu.indexOf(m.availability??hH.Stable)]),descriptions:u,extraProperties:a,visitedTypeIds:l};return f1c.set(e,O),O}let s=new Set(e.properties.map(g=>g.key)),o=d.filter(g=>!s.has(g.key)),b={properties:ytu([...n,...o],[g=>kir(g.valueShape,t)?.isOptional,g=>htu.indexOf(g.availability??hH.Stable),g=>g.key]),descriptions:u,extraProperties:a,visitedTypeIds:l};return f1c.set(e,b),b}function d1c(e,t,r){let{properties:i,descriptions:n,visitedTypeIds:a}=nYi(t,r);return{properties:[{key:e.discriminant,valueShape:{type:"alias",value:{type:"literal",value:{type:"stringLiteral",value:t.discriminantValue}}},propertyAccess:void 0,description:void 0,availability:void 0},...i],extraProperties:void 0,descriptions:n,visitedTypeIds:a}}function ViM(e){return Ky(e,"type")._visit({string:t=>t.default,integer:t=>t.default,double:t=>t.default,uint:()=>{},uint64:()=>{},boolean:t=>t.default,long:t=>t.default,datetime:t=>t.default,uuid:t=>t.default,base64:t=>t.default,date:t=>t.default,bigInteger:t=>t.default})}function p3_(e,t,{availability:r,maxDepth:i=5,path:n=[]}={}){let a=[],u=[{type:e,path:n,availability:r,descriptions:[],visitedTypeIds:new Set}],l=0;for(;u.length>0;){if(l++>1e4){console.error("Infinite loop detected when traversing type definitions");break}let{type:d,path:s,descriptions:o,visitedTypeIds:c,availability:b}=u.pop();if(s.length>i)continue;let g=kir(d,t),O=tYi([b,g.availability]),m=[...o,...g.descriptions],P=!1;if(g.visitedTypeIds.forEach(q=>{c.has(q)&&(P=!0)}),P)continue;let E=new Set([...c,...g.visitedTypeIds]);if(g.shape.type==="object"){let q=nYi(g.shape,t);m.push(...q.descriptions),q.visitedTypeIds.forEach(M=>E.add(M)),q.properties.forEach(M=>{u.push({type:M.valueShape,path:[...s,{type:"objectProperty",key:M.key,optional:kir(M.valueShape,t).isOptional}],descriptions:M.description?[M.description]:[],visitedTypeIds:E,availability:O})}),q.extraProperties&&u.push({type:q.extraProperties,path:[...s,{type:"extra"}],descriptions:[],visitedTypeIds:E,availability:O})}if(a.push({path:s,descriptions:m,availability:O}),g.shape.type==="undiscriminatedUnion")g.shape.variants.forEach((q,M)=>{u.push({type:q.shape,path:[...s,{type:"undiscriminatedUnionVariant",displayName:q.displayName,idx:M}],descriptions:q.description?[q.description]:[],visitedTypeIds:E,availability:tYi([O,q.availability])})});else if(g.shape.type==="discriminatedUnion"){let q=g.shape.discriminant;g.shape.variants.forEach(M=>{let D=[...s,{type:"discriminatedUnionVariant",discriminant:q,discriminantDisplayName:M.displayName,discriminantValue:M.discriminantValue}];u.push({type:{...M,type:"object"},path:D,descriptions:M.description?[M.description]:[],visitedTypeIds:E,availability:tYi([O,M.availability])})})}else g.shape.type==="list"||g.shape.type==="set"?u.push({type:g.shape.itemShape,path:[...s,{type:g.shape.type}],descriptions:m,visitedTypeIds:E,availability:O}):g.shape.type==="map"?u.push({type:g.shape.valueShape,path:[...s,{type:"mapValue"}],descriptions:[...m,...kir(g.shape.keyShape,t).descriptions],visitedTypeIds:E,availability:O}):g.shape.type==="enum"&&g.shape.values.forEach(q=>{a.push({path:[...s,{type:"enumValue",value:q.value}],descriptions:q.description?[q.description]:[],availability:O})})}return a}function HiM(e,t,r=[],i=5){return[{path:[...r,{type:"objectProperty",key:e.key,optional:kir(e.valueShape,t).isOptional}],descriptions:e.description?[e.description]:[],availability:e.availability},...p3_(e.valueShape,t,{maxDepth:i-1,availability:e.availability,path:[...r,{type:"objectProperty",key:e.key,optional:kir(e.valueShape,t).isOptional}]})]}var xHt=ci(Oz(),1);var uqi=class e{static visitEndpointDefinition(t,r){t.pathParameters?.forEach(i=>{e.visitTypeShape(i.valueShape,r)}),t.queryParameters?.forEach(i=>{e.visitTypeShape(i.valueShape,r)}),t.requestHeaders?.forEach(i=>{e.visitTypeShape(i.valueShape,r)}),t.responseHeaders?.forEach(i=>{e.visitTypeShape(i.valueShape,r)}),t.requests?.forEach(i=>{i.body!=null&&e.visitHttpRequestBodyShape(i.body,r)}),t.responses?.forEach(i=>{i.body!=null&&e.visitHttpResponseBodyShape(i.body,r)}),t.errors?.forEach(i=>{i.shape!=null&&e.visitTypeShape(i.shape,r)})}static visitWebSocketChannel(t,r){t.requestHeaders?.forEach(i=>{e.visitTypeShape(i.valueShape,r)}),t.pathParameters?.forEach(i=>{e.visitTypeShape(i.valueShape,r)}),t.queryParameters?.forEach(i=>{e.visitTypeShape(i.valueShape,r)}),t.messages.forEach(i=>{e.visitTypeShape(i.body,r)})}static visitWebhookDefinition(t,r){t.headers?.forEach(i=>{e.visitTypeShape(i.valueShape,r)}),t.payloads?.[0]!=null&&e.visitTypeShape(t.payloads[0].shape,r)}static visitHttpRequestBodyShape(t,r){return Ky(t)._visit({object:i=>e.visitObjectType(i,r),alias:i=>e.visitTypeReference(i.value,r),bytes:xHt.noop,formData:i=>e.visitFormDataRequest(i,r)})}static visitHttpResponseBodyShape(t,r){return Ky(t)._visit({object:i=>e.visitObjectType(i,r),alias:i=>e.visitTypeReference(i.value,r),fileDownload:xHt.noop,streamingText:xHt.noop,stream:i=>e.visitTypeShape(i.shape,r),empty:xHt.noop})}static visitFormDataRequest(t,r){return t.fields.forEach(i=>Ky(i)._visit({file:xHt.noop,files:xHt.noop,property:n=>e.visitTypeShape(n.valueShape,r)}))}static visitTypeDefinition(t,r){return e.visitTypeShape(t.shape,r)}static visitTypeShape(t,r){return Ky(t)._visit({object:i=>e.visitObjectType(i,r),alias:i=>e.visitTypeReference(i.value,r),enum:xHt.noop,undiscriminatedUnion:i=>i.variants.forEach(n=>e.visitTypeShape(n.shape,r)),discriminatedUnion:i=>i.variants.forEach(n=>e.visitObjectType(n,r))})}static visitObjectType(t,r){t.extends.forEach(r),t.properties.forEach(i=>{e.visitTypeShape(i.valueShape,r)})}static visitTypeReference(t,r){return Ky(t)._visit({id:i=>r(i.id),primitive:xHt.noop,optional:i=>e.visitTypeShape(i.shape,r),nullable:i=>e.visitTypeShape(i.shape,r),list:i=>e.visitTypeShape(i.itemShape,r),set:i=>e.visitTypeShape(i.itemShape,r),map:i=>{e.visitTypeShape(i.keyShape,r),e.visitTypeShape(i.valueShape,r)},literal:xHt.noop,unknown:xHt.noop})}};var _1c=class e{api;static instances=new WeakMap;static from(t){let r=e.instances.get(t)??new e(t);return e.instances.set(t,r),r}constructor(t){this.api=t}prune(...t){let r={...this.api,endpoints:{},websockets:{},webhooks:{},types:{},subpackages:{},auths:{}},i=new Set,n=new Set;for(let a of t)if(a.type==="endpoint"){let u=this.api.endpoints[a.endpointId];u&&(r.endpoints[a.endpointId]=u,u.namespace?.forEach(l=>i.add(l)),u.auth?.forEach(l=>n.add(l)))}else if(a.type==="webSocket"){let u=this.api.websockets[a.webSocketId];u&&(r.websockets[a.webSocketId]=u,u.namespace?.forEach(l=>i.add(l)),u.auth?.forEach(l=>n.add(l)))}else if(a.type==="webhook"){let u=this.api.webhooks[a.webhookId];u&&(r.webhooks[a.webhookId]=u,u.namespace?.forEach(l=>i.add(l)))}return r.types=this.pruneTypes(r),i.forEach(a=>{let u=this.api.subpackages[a];u&&(r.subpackages[a]=u)}),n.forEach(a=>{let u=this.api.auths[a];u&&(r.auths[a]=u)}),r}pruneTypes(t){let r=new Set;t.globalHeaders?.forEach(n=>{uqi.visitTypeShape(n.valueShape,a=>r.add(a))});for(let n of Object.values(t.endpoints))uqi.visitEndpointDefinition(n,a=>r.add(a));for(let n of Object.values(t.websockets))uqi.visitWebSocketChannel(n,a=>r.add(a));for(let n of Object.values(t.webhooks))uqi.visitWebhookDefinition(n,a=>r.add(a));r=this.expandTypeIds(r);let i={};return r.forEach(n=>{let a=this.api.types[n];a!=null&&(i[n]=a)}),i}expandTypeIds(t){let r=new Set,i=Array.from(t),n=0;for(;i.length>0;){if(n>1e4+t.size)throw new Error("Infinite loop detected while expanding type references.");let a=i.pop();if(a!=null&&!r.has(a)){r.add(a);let u=this.api.types[a];u&&uqi.visitTypeDefinition(u,l=>{i.push(l)})}n++}return r}};function qNa(e,...t){return _1c.from(e).prune(...t)}function YiM(e,t){if(!e)return;let r=t!=null?qNa(t,e):void 0,i=r?.endpoints[e.endpointId];if(i)return{node:e,endpoint:i,auth:i.auth?.map(n=>r.auths[n])[0],globalHeaders:r.globalHeaders??[],types:r.types}}function XiM(e,t){if(!e)return;let r=t!=null?qNa(t,e):void 0,i=r?.websockets[e.webSocketId];if(i)return{node:e,channel:i,auth:i.auth?.map(n=>r.auths[n])[0],globalHeaders:r.globalHeaders??[],types:r.types}}function ZiM(e,t){if(!e)return;let r=t!=null?qNa(t,e):void 0,i=r?.webhooks[e.webhookId];if(i)return{node:e,webhook:i,types:r.types}}var s4={};jo(s4,{ApiDefinitionId:()=>xKi,ApiId:()=>LKi,Availability:()=>hH,DocsConfigId:()=>UKi,EndpointId:()=>WKi,EndpointPathLiteral:()=>kKi,EnvironmentId:()=>VKi,FileId:()=>JKi,HttpMethod:()=>eYi,JqString:()=>YKi,ObjectPropertyAccess:()=>h1c,OrgId:()=>NKi,PageId:()=>QKi,PropertyKey:()=>XKi,RoleId:()=>ZKi,SubpackageId:()=>ANa,SupportedLanguage:()=>YB,TokenId:()=>FKi,TypeId:()=>GKi,Url:()=>KKi,VersionId:()=>RKi,WebSocketId:()=>HKi,WebSocketMessageId:()=>r1c,WebSocketMessageOrigin:()=>i1c,WebhookHttpMethod:()=>n1c,WebhookId:()=>$Ki,endpoint:()=>Ptu,getApi:()=>wtu,type_:()=>jtu,webhook:()=>y1c,websocket:()=>v1c});var b1c={};jo(b1c,{ObjectPropertyAccess:()=>h1c,SupportedLanguage:()=>YB,endpoint:()=>Ptu,getApi:()=>wtu,type_:()=>jtu,webhook:()=>y1c,websocket:()=>v1c});var Ptu={};jo(Ptu,{SupportedLanguage:()=>YB});var YB={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var jtu={};jo(jtu,{ObjectPropertyAccess:()=>h1c});var h1c={ReadOnly:"READ_ONLY",WriteOnly:"WRITE_ONLY"};var y1c={};var v1c={};var wtu={};jo(wtu,{Error:()=>kiM});var kiM={apiDoesNotExistError:()=>({error:"ApiDoesNotExistError"}),_unknown:e=>({error:void 0,content:e}),_visit:(e,t)=>{switch(e.error){case"ApiDoesNotExistError":return t.apiDoesNotExistError();default:return t._other(e)}}};function enM(e){return e.map(t=>t.type==="literal"?t.value:`:${t.value}`).join("")}function tnM(e){return e.map(t=>t.type==="literal"?t.value:`{${t.value}}`).join("")}function rnM(e=!1){return(t,...r)=>{let i={id:t.id,endpoints:{...t.endpoints},websockets:{...t.websockets},webhooks:{...t.webhooks},types:{...t.types},subpackages:{...t.subpackages},auths:{...t.auths},globalHeaders:t.globalHeaders?[...t.globalHeaders]:void 0,snippetsConfiguration:t.snippetsConfiguration?{...t.snippetsConfiguration}:void 0},n=!1;for(let a of r){if(a.id!==i.id)throw new Error("Cannot join API definitions with different IDs");for(let[l,d]of Object.entries(a.endpoints))!n&&!t.endpoints[l]&&(n=!0),i.endpoints[l]=d;for(let[l,d]of Object.entries(a.websockets))!n&&!t.websockets[l]&&(n=!0),i.websockets[l]=d;for(let[l,d]of Object.entries(a.webhooks))!n&&!t.webhooks[l]&&(n=!0),i.webhooks[l]=d;for(let[l,d]of Object.entries(a.types))!n&&!t.types[l]&&(n=!0),i.types[l]=d;for(let[l,d]of Object.entries(a.subpackages))!n&&!t.subpackages[l]&&(n=!0),i.subpackages[l]=d;for(let[l,d]of Object.entries(a.auths))!n&&!t.auths[l]&&(n=!0),i.auths[l]=d;let u=i.globalHeaders??=[];a.globalHeaders?.forEach(l=>{u.find(d=>d.key===l.key)||(n=!0,u.push(l))})}return!n&&!e?t:i}}function g1c(e){return e=e.toLowerCase().trim(),["node","nodejs","js","javascript"].includes(e)?YB.Javascript:["py","python"].includes(e)?YB.Python:["ts","typescript","ts-node"].includes(e)?YB.Typescript:["go","golang"].includes(e)?YB.Go:e}function Dk(e,t){let r={},i=Object.keys(e);for(let n=0;n<i.length;n++){let a=i[n],u=e[a];r[a]=t(u,a,e)}return r}var HFe="__package__";var O1c=ci(Oz(),1);function inM(e){var t=[];if(e.length===0)return"";if(typeof e[0]!="string")throw new TypeError("Url must be a string. Received "+e[0]);if(e[0].match(/^[^/:]+:\/*$/)&&e.length>1){var r=e.shift();e[0]=r+e[0]}e[0].match(/^file:\/\/\//)?e[0]=e[0].replace(/^([^/:]+):\/*/,"$1:///"):e[0]=e[0].replace(/^([^/:]+):\/*/,"$1://");for(var i=0;i<e.length;i++){var n=e[i];if(typeof n!="string")throw new TypeError("Url must be a string. Received "+n);n!==""&&(i>0&&(n=n.replace(/^[\/]+/,"")),i<e.length-1?n=n.replace(/[\/]+$/,""):n=n.replace(/[\/]+$/,"/"),t.push(n))}var a=t.join("/");a=a.replace(/\/(\?|&|#[^!])/g,"$1");var u=a.split("?");return a=u.shift()+(u.length>0?"?":"")+u.join("&"),a}function Eb(){var e;return typeof arguments[0]=="object"?e=arguments[0]:e=[].slice.call(arguments),inM(e)}function TNa(e,t,r){let i=(e.environments?.find(d=>d.id===e.defaultEnvironment)??e.environments?.[0])?.baseUrl,n=Eb(rYi([i,t.path])),a={...t.headers},u;e.auth&&e.auth.length>0&&r&&Ky(r,"type")._visit({basicAuth:({usernameName:d="username",passwordName:s="password"})=>{u={username:`<${d}>`,password:`<${s}>`}},bearerAuth:({tokenName:d="token"})=>{a.Authorization=`Bearer <${d}>`},header:({headerWireValue:d,nameOverride:s=d,prefix:o})=>{a[d]=o!=null?`${o} <${s}>`:`<${s}>`},oAuth:({value:d})=>{Ky(d,"type")._visit({clientCredentials:()=>{a.Authorization="Bearer <token>"},_other:O1c.noop})},_other:O1c.noop});let l=t.requestBody;return e.requests?.[0]?.contentType!=null&&(a["Content-Type"]=e.requests?.[0]?.contentType),l!=null&&a["Content-Type"]==null&&(l.type==="json"?a["Content-Type"]="application/json":l.type==="form"&&(a["Content-Type"]="multipart/form-data")),e.protocol?.type==="openrpc"&&(a["Content-Type"]="application/json"),{method:e.method,url:n,searchParams:t.queryParameters??{},headers:JSON.parse(JSON.stringify(a)),basicAuth:u,protocol:e.protocol,body:l==null?void 0:Ky(l)._visit({json:d=>d,form:d=>{let s={};for(let[o,c]of Object.entries(d.value))s[o]=Ky(c)._visit({exploded:b=>b,json:b=>b,filename:b=>({type:"filename",filename:b.value,contentType:void 0}),filenames:b=>({type:"filenames",files:b.value.map(g=>({filename:g,contentType:void 0}))}),filenameWithData:b=>({type:"filename",filename:b.filename,contentType:void 0}),filenamesWithData:b=>({type:"filenames",files:b.value.map(({filename:g})=>({filename:g,contentType:void 0}))})});return{type:"form",value:s}},bytes:()=>({type:"bytes",filename:"<filename>"}),_other:()=>{}})}}var P1c=ci(Oz(),1);function m1c(e,t){let r=[];return e&&typeof e=="object"&&(r=Object.values(e)),{jsonrpc:"2.0",method:t,params:r,id:1}}function nnM(e){return encodeURIComponent(e)!==e}function CNa(e,t){try{return _nM(e,t)}catch(r){return console.error(r),""}}function anM(e,t,r){let i=G6_(r).map(([n,a])=>`${n}=${encodeURIComponent(VMe(a))}`).join("&");return e!=="GET"?i.length>0?`-X ${e} "${t}?${i}"`:`-X ${e} ${t}`:i.length>0?`-G ${t}`:t}function onM(e){return Object.entries(e).map(([t,r])=>`-H "${t}: ${VMe(r)}"`)}function unM(e,t){return t?[`-u "${e.username}:${j1c(e.password)}"`]:[`-u "${e.username}:${e.password}"`]}function $6_(e){return G6_(e).map(([t,r])=>`${nnM(r)?"--data-urlencode":"-d"} ${t.includes("[")?`"${t}"`:t}=${r.includes(" ")?`"${r}"`:r}`)}function W6_(e,t){if(t?.type==="openrpc"){let i=m1c(e,t.methodName);return[`-d '${JSON.stringify(i,null,2).replace(/'/g,"\\'")}'`]}return e==null?[]:typeof e=="string"?[`-d "${e.replace(/"/g,'\\"')}"`]:[`-d '${JSON.stringify(e,null,2).replace(/'/g,"\\'")}'`]}function snM(e){return[`--data-binary @${e.includes(" ")?`"${e}"`:e}`]}function H6_(e,t,r){if(e==null)return[];if(typeof e=="string")return[`-F ${t}="${e.replace(/"/g,'\\"')}"`];let i=JSON.stringify(e,null,2);return[`-F ${t}='${i.replace(/'/g,"'\\''")}${r?";type=application/json":""}'`]}function cnM({files:e},t){return e.filter(r=>r.filename!=null).map(({filename:r,contentType:i})=>`-F "${t}[]"=@${r.includes(" ")||i!=null?`"${r}${i!=null?`;type=${i}`:""}"`:r}`)}function lnM({filename:e,contentType:t},r){return e==null?[]:[`-F ${r}=@${e.includes(" ")||t!=null?`"${e}${t!=null?`;type=${t}`:""}"`:e}`]}function fnM(e,t,r){switch(e.type){case"json":return H6_(e.value,t,r);case"filename":return lnM(e,t);case"filenames":return cnM(e,t);case"exploded":return(e.value??[]).flatMap(i=>H6_(i,t,r));default:throw new P1c.UnreachableCaseError(e)}}function dnM(e,t){return Object.entries(e).flatMap(([r,i])=>fnM(i,r,t))}function pnM(e,t,r,i){if(e==="GET")return[];if(t==null)return i?.type==="openrpc"?W6_(void 0,i):[];switch(t.type){case"json":return W6_(t.value,i);case"bytes":return snM(t.filename);case"form":return dnM(t.value,r);default:throw new P1c.UnreachableCaseError(t)}}function _nM({method:e,url:t,searchParams:r,headers:i,basicAuth:n,body:a,protocol:u,redacted:l},{usesApplicationJsonInFormDataValue:d}){let s=anM(e,t,r),o=onM(n!=null?Object.fromEntries(Object.entries(i).filter(([E])=>E.toLowerCase()!=="authorization")):i),c=n!=null?unM(n,l):[],b=e!=="GET"&&VMe(i["Content-Type"]??i["content-type"]).toLowerCase().includes("form-urlencoded"),g=$6_({...e==="GET"?r:{},...b&&a?.type==="json"&&mLn(a.value)?a.value:{}}),O=b?[]:pnM(e,a,d,u),m=rYi([...o,...c,...g,...O]);function P(E){return` \\
1978
1977
  ${E}`}return`curl ${s}${m.map(P).join("")}`}function G6_(e){return Object.entries(e).flatMap(([t,r])=>Array.isArray(r)?r.filter(oqi).map(i=>[t,VMe(i)]):r==null?[]:[[t,VMe(r)]])}function w1c(e,t){return Dk(s1c([...t,...u1c(Object.keys(e),t)],r=>r),r=>e[r])}function yH(e,t,r){return!PLn(e)&&!Array.isArray(e)||t==null?e:Ky(t,"type")._visit({id:({id:i})=>yH(e,r[i]?.shape,r),primitive:()=>e,literal:()=>e,optional:({shape:i})=>yH(e,i,r),nullable:({shape:i})=>yH(e,i,r),list:({itemShape:i})=>Array.isArray(e)?e.map(n=>yH(n,i,r)):e,set:({itemShape:i})=>Array.isArray(e)?e.map(n=>yH(n,i,r)):e,map:({valueShape:i})=>PLn(e)?Dk(e,n=>yH(n,i,r)):e,unknown:()=>e,object:i=>{let n=nYi(i,r).properties;return PLn(e)?Dk(w1c(e,n.map(a=>a.key)),(a,u)=>{let l=n.find(d=>d.key===u);return l==null?a:yH(a,l?.valueShape,r)}):e},undiscriminatedUnion:()=>e,discriminatedUnion:i=>{let{discriminant:n,variants:a}=i;if(!PLn(e))return e;let u=e[n];if(u==null)return e;let l=a.find(s=>s.discriminantValue===u);if(l==null)return e;let d=d1c(i,l,r).properties;return Dk(w1c(e,[n,...d.map(s=>s.key)]),(s,o)=>{if(o===n)return s;let c=d.find(b=>b.key===o);return c==null?s:yH(s,c.valueShape,r)})},enum:()=>e,alias:({value:i})=>yH(e,i,r),formData:({fields:i})=>PLn(e)?Dk(w1c(e,i.map(n=>n.key)),(n,a)=>{let u=i.find(l=>l.key===a);if(u==null)return n;if(u.type==="property")return yH(n,u.valueShape,r)}):e,bytes:()=>e,fileDownload:()=>e,streamingText:()=>e,stream:()=>e,empty:()=>e,_other:()=>e})}var Q6_={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"},J6_={200:{GET:"Retrieved",POST:"Successful",PUT:"Updated",PATCH:"Updated",DELETE:"Deleted"}};function S1c(e,t){if(t!=null){let i=J6_[e];if(i!=null){let n=i[t];if(n!=null)return n}}let r=Q6_[e];return r??(e>=100&&e<200?"Informational":e>=200&&e<300?"Success":e>=300&&e<400?"Redirection":e>=400&&e<500?"Client Error":e>=500&&e<600?"Server Error":"Unknown Status")}function hnM(e){return typeof e.subpackageId=="string"}var D1c="default",E1c=class e{v1;flags;static from(t,r){return new e(t,r)}auth;constructor(t,r){this.v1=t,this.flags=r,this.auth=t.auth}static createEndpointId(t,r=HFe){return t.originalEndpointId??`${r}.${t.id}`}static createWebSocketId(t,r=HFe){return`${r}.${t.id}`}static createWebhookId(t,r=HFe){return`${r}.${t.id}`}endpoints={};websockets={};webhooks={};subpackages={};types={};migrate=()=>(Object.entries(this.v1.types).forEach(([t,r])=>{this.types[t]={name:r.name,description:r.description,availability:r.availability,shape:this.migrateTypeShape(r.shape),displayName:r.displayName}}),[this.v1.rootPackage,...Object.values(this.v1.subpackages)].forEach(t=>{let[r,i]=this.collectNamespace(t,this.v1.subpackages);t.endpoints.forEach(n=>{let a=e.createEndpointId(n,r);this.endpoints[a]=this.migrateEndpoint(a,n,i)}),t.websockets.forEach(n=>{let a=e.createWebSocketId(n,r);this.websockets[a]=this.migrateWebSocket(a,n,i)}),t.webhooks.forEach(n=>{let a=e.createWebhookId(n,r);this.webhooks[a]=this.migrateWebhook(a,n,i)})}),Object.values(this.v1.subpackages).forEach(t=>{this.subpackages[t.subpackageId]=this.migrateSubpackage(t)}),{id:this.v1.id,endpoints:this.endpoints,websockets:this.websockets,webhooks:this.webhooks,types:this.types,subpackages:this.subpackages,auths:this.v1.auth?{[D1c]:this.v1.auth}:{},globalHeaders:this.migrateParameters(this.v1.globalHeaders),snippetsConfiguration:void 0});collectNamespace=(t,r)=>{if(!hnM(t))return[HFe,[]];let i=[t.subpackageId],n=t,a=0;for(;n.parent!=null;){if(a>100)throw new Error("Circular subpackage reference detected");let u=r[n.parent];if(u==null)break;i.unshift(n.parent),n=u,a++}return[t.subpackageId,i]};migrateEndpoint=(t,r,i)=>{let n={id:t,namespace:i,displayName:r.name,operationId:r.urlSlug.split("/").pop(),description:r.description,availability:r.availability,method:r.method,path:r.path.parts.filter(a=>a.value!==""),auth:r.authed?[D1c]:void 0,defaultEnvironment:r.defaultEnvironment,environments:r.environments,pathParameters:this.migrateParameters(r.path.pathParameters),queryParameters:this.migrateParameters(r.queryParameters),requestHeaders:this.migrateParameters(r.headers),responseHeaders:void 0,requests:[this.migrateHttpRequest(r.request)].filter(oqi),responses:[this.migrateHttpResponse(r.response)].filter(oqi),errors:this.migrateHttpErrors(r.errorsV2),examples:void 0,snippetTemplates:r.snippetTemplates,protocol:r.protocol};return n.examples=this.migrateHttpExamples(r.examples,n),n};migrateWebSocket=(t,r,i)=>{let n=this.migrateChannelMessages(r.messages);return{id:t,namespace:i,displayName:r.name,operationId:r.urlSlug.split("/").pop(),description:r.description,availability:r.availability,path:r.path.parts.filter(a=>a.value!==""),messages:n,auth:r.auth?[D1c]:void 0,defaultEnvironment:r.defaultEnvironment,environments:r.environments,pathParameters:this.migrateParameters(r.path.pathParameters),queryParameters:this.migrateParameters(r.queryParameters),requestHeaders:this.migrateParameters(r.headers),examples:this.migrateChannelExamples(r.examples,n)}};migrateWebhook=(t,r,i)=>{let n=this.migrateWebhookPayload(r.payload);return{id:t,namespace:i,displayName:r.name,operationId:r.urlSlug.split("/").pop(),description:r.description,availability:void 0,method:r.method,path:r.path,headers:this.migrateParameters(r.headers),payloads:[n],examples:r.examples.map(a=>({...a,payload:yH(a.payload,n.shape,this.types)}))}};migrateSubpackage=t=>({id:t.subpackageId,name:t.name,displayName:t.displayName});migrateParameters=t=>{if(!(t==null||t.length===0))return t.map(r=>({key:r.key,valueShape:{type:"alias",value:this.migrateTypeReference(r.type)},propertyAccess:void 0,description:r.description,availability:r.availability}))};migrateTypeReference=t=>Ky(t)._visit({map:r=>({type:"map",keyShape:{type:"alias",value:this.migrateTypeReference(r.keyType)},valueShape:{type:"alias",value:this.migrateTypeReference(r.valueType)}}),id:r=>({type:"id",id:r.value,default:r.default}),primitive:r=>r,optional:r=>({type:"optional",shape:{type:"alias",value:this.migrateTypeReference(r.itemType)},default:r.defaultValue}),list:r=>({type:"list",itemShape:{type:"alias",value:this.migrateTypeReference(r.itemType)}}),set:r=>({type:"set",itemShape:{type:"alias",value:this.migrateTypeReference(r.itemType)}}),literal:r=>r,unknown:()=>({type:"unknown",displayName:void 0})});migrateTypeShape=t=>Ky(t)._visit({object:r=>({type:"object",extends:r.extends,properties:this.migrateObjectProperties(r.properties),extraProperties:r.extraProperties!=null?this.migrateTypeReference(r.extraProperties):void 0}),alias:r=>({type:"alias",value:this.migrateTypeReference(r.value)}),enum:r=>r,undiscriminatedUnion:r=>({type:"undiscriminatedUnion",variants:r.variants.map(i=>({displayName:i.displayName,shape:{type:"alias",value:this.migrateTypeReference(i.type)},description:i.description,availability:i.availability}))}),discriminatedUnion:r=>({type:"discriminatedUnion",discriminant:r.discriminant,variants:r.variants.map(i=>({discriminantValue:i.discriminantValue,displayName:i.displayName,description:i.description,availability:i.availability,extends:i.additionalProperties.extends,properties:this.migrateObjectProperties(i.additionalProperties.properties),extraProperties:void 0}))})});migrateObjectProperties=t=>t.map(r=>({key:r.key,valueShape:{type:"alias",value:this.migrateTypeReference(r.valueType)},propertyAccess:r.propertyAccess,description:r.description,availability:r.availability}));migrateJsonShape=t=>Ky(t)._visit({object:this.migrateTypeShape,reference:r=>({type:"alias",value:this.migrateTypeReference(r.value)})});migrateWebhookPayload=t=>({description:t.description,shape:this.migrateJsonShape(t.type)});migrateChannelExamples=(t,r)=>{if(t.length!==0)return t.map(i=>({description:i.description,path:i.path,name:i.name,pathParameters:i.pathParameters,queryParameters:i.queryParameters,requestHeaders:i.headers,messages:i.messages.map(n=>({...n,body:yH(n.body,r.find(a=>a.type===n.type)?.body,this.types)}))}))};migrateChannelMessages=t=>t.map(r=>({type:r.type,displayName:r.displayName,origin:r.origin,body:this.migrateJsonShape(r.body),description:r.description,availability:r.availability}));migrateHttpExamples=(t,r)=>{if(t.length!==0)return t.map(i=>{let n={path:i.path,responseStatusCode:i.responseStatusCode,name:i.name,description:i.description,pathParameters:i.pathParameters,queryParameters:i.queryParameters,headers:i.headers,requestBody:i.requestBodyV3,responseBody:i.responseBodyV3,snippets:void 0};return i.requestBodyV3&&(n.requestBody=Ky(i.requestBodyV3)._visit({bytes:a=>a,json:a=>({type:"json",value:yH(a.value,r.requests?.[0]?.body,this.types)}),form:a=>({type:"form",value:Dk(a.value,(u,l)=>{if(u.type==="json"){let d=r.requests?.[0]?.body.type==="formData"?r.requests?.[0]?.body.fields.find(s=>s.key===l&&s.type==="property")?.valueShape:void 0;return{type:"json",value:yH(u.value,d,this.types)}}else return u})})})),n.responseBody&&(n.responseBody.value=yH(n.responseBody.value,r.responses?.[0]?.body,this.types)),n.snippets=this.migrateEndpointSnippets(r,n,i.codeSamples,i.codeExamples,this.flags),n})};migrateHttpErrors=t=>{if(!(t==null||t.length===0))return t.map(r=>{let i=r.type!=null?this.migrateTypeShape(r.type):void 0;return{description:r.description,availability:r.availability,name:(r.name!=null?iYi(r.name):void 0)??S1c(r.statusCode),statusCode:r.statusCode,shape:i,examples:r.examples?.map(n=>({description:n.description,name:n.name,responseBody:{type:"json",value:yH(n.responseBody.value,i,this.types)}}))}})};migrateHttpResponse=t=>{if(t!=null)return{description:t.description,statusCode:t.statusCode??200,body:Ky(t.type)._visit({object:r=>({type:"object",extends:r.extends,properties:this.migrateObjectProperties(r.properties),extraProperties:void 0}),reference:r=>({type:"alias",value:this.migrateTypeReference(r.value)}),fileDownload:r=>r,streamingText:r=>r,stream:r=>({type:"stream",terminator:r.terminator,shape:this.migrateJsonShape(r.shape)}),streamCondition:r=>({type:"stream",terminator:void 0,shape:this.migrateJsonShape(r.streamResponse.shape)})})}};migrateHttpRequest=t=>{if(t!=null)return{description:t.description,contentType:t.contentType,body:Ky(t.type)._visit({object:r=>({type:"object",extends:r.extends,properties:this.migrateObjectProperties(r.properties),extraProperties:void 0}),reference:r=>({type:"alias",value:this.migrateTypeReference(r.value)}),bytes:r=>({type:"bytes",isOptional:r.isOptional,contentType:r.contentType}),formData:r=>({type:"formData",description:r.description,availability:r.availability,fields:this.migrateFormDataProperties(r.properties)}),fileUpload:r=>({type:"formData",description:r.value?.description,availability:r.value?.availability,fields:this.migrateFormDataProperties(r.value?.properties??[])})})}};migrateFormDataProperties=t=>t.map(r=>Ky(r)._visit({file:i=>Ky(i.value)._visit({file:n=>({type:"file",key:n.key,isOptional:n.isOptional,contentType:n.contentType,description:n.description,availability:n.availability}),fileArray:n=>({type:"files",key:n.key,isOptional:n.isOptional,contentType:n.contentType,description:n.description,availability:n.availability})}),bodyProperty:i=>({type:"property",key:i.key,contentType:i.contentType,description:i.description,availability:i.availability,exploded:i.exploded,valueShape:{type:"alias",value:this.migrateTypeReference(i.valueType)},propertyAccess:i.propertyAccess})}));migrateEndpointSnippets(t,r,i,n,a){let u={};function l(o,c){(u[o]??=[]).push(c)}let d=new Set;if(i.forEach(o=>{let c=g1c(o.language);d.add(c),l(c,{name:o.name,language:c,install:o.install,code:o.code,generated:!1,description:o.description})}),!d.has(YB.Curl)){let o=CNa(TNa(t,r,this.auth),a);l(YB.Curl,{language:YB.Curl,code:o,name:void 0,install:void 0,generated:!0,description:void 0})}!d.has(YB.Python)&&n.pythonSdk!=null&&l(YB.Python,{name:void 0,language:YB.Python,install:n.pythonSdk.install,code:n.pythonSdk.sync_client,generated:!0,description:void 0});let s=a.useJavaScriptAsTypeScript?YB.Javascript:YB.Typescript;return!a.alwaysEnableJavaScriptFetch&&!d.has(s)&&n.typescriptSdk!=null&&l(s,{name:void 0,language:s,install:n.typescriptSdk.install,code:n.typescriptSdk.client,generated:!0,description:void 0}),!d.has(YB.Go)&&n.goSdk!=null&&l(YB.Go,{name:void 0,language:YB.Go,install:n.goSdk.install,code:n.goSdk.client,generated:!0,description:void 0}),!d.has(YB.Ruby)&&n.rubySdk!=null&&l(YB.Ruby,{name:void 0,language:YB.Ruby,install:n.rubySdk.install,code:n.rubySdk.client,generated:!0,description:void 0}),!d.has(YB.Csharp)&&n.csharpSdk!=null&&l(YB.Csharp,{name:void 0,language:YB.Csharp,install:n.csharpSdk.install,code:n.csharpSdk.client,generated:!0,description:void 0}),u}};var M1c=class e{static with(t){return new e({EndpointDefinition:t.EndpointDefinition??KA,HttpRequest:t.HttpRequest??KA,HttpResponse:t.HttpResponse??KA,ErrorResponse:t.ErrorResponse??KA,ExampleEndpointCall:t.ExampleEndpointCall??KA,CodeSnippet:t.CodeSnippet??KA,ErrorExample:t.ErrorExample??KA,WebhookDefinition:t.WebhookDefinition??KA,WebhookPayload:t.WebhookPayload??KA,WebSocketChannel:t.WebSocketChannel??KA,WebSocketMessage:t.WebSocketMessage??KA,ExampleWebSocketSession:t.ExampleWebSocketSession??KA,TypeDefinition:t.TypeDefinition??KA,TypeShape:t.TypeShape??KA,ObjectType:t.ObjectType??KA,ObjectProperty:t.ObjectProperty??KA,EnumValue:t.EnumValue??KA,UndiscriminatedUnionVariant:t.UndiscriminatedUnionVariant??KA,DiscriminatedUnionVariant:t.DiscriminatedUnionVariant??KA,FormDataRequest:t.FormDataRequest??KA,FormDataField:t.FormDataField??KA,FormDataFile:t.FormDataFile??KA,FormDataFiles:t.FormDataFiles??KA})}static descriptions(t){function r(i,n){let a=i.description!=null?t(i.description,n):void 0;return{...i,description:a}}return e.with({EndpointDefinition:r,HttpRequest:r,HttpResponse:r,ErrorResponse:r,ExampleEndpointCall:r,CodeSnippet:r,ErrorExample:r,WebhookDefinition:r,WebhookPayload:r,WebSocketChannel:r,WebSocketMessage:r,ExampleWebSocketSession:r,TypeDefinition:r,ObjectProperty:r,EnumValue:r,UndiscriminatedUnionVariant:r,DiscriminatedUnionVariant:r,FormDataRequest:r,FormDataField:r,FormDataFile:r,FormDataFiles:r})}static keys(t){function r(i,n){return t(n),i}return e.with({EndpointDefinition:r,HttpRequest:r,HttpResponse:r,ErrorResponse:r,ExampleEndpointCall:r,CodeSnippet:r,ErrorExample:r,WebhookDefinition:r,WebhookPayload:r,WebSocketChannel:r,WebSocketMessage:r,ExampleWebSocketSession:r,TypeDefinition:r,TypeShape:r,ObjectType:r,ObjectProperty:r,EnumValue:r,UndiscriminatedUnionVariant:r,DiscriminatedUnionVariant:r,FormDataRequest:r,FormDataField:r,FormDataFile:r,FormDataFiles:r})}visitor;constructor(t){this.visitor=this.#e(t)}apiDefinition=t=>{let r=Object.entries(t.endpoints).map(([l,d])=>[l,this.visitor.EndpointDefinition(d,`${t.id}/endpoint/${l}`)]),i=Object.entries(t.websockets).map(([l,d])=>[l,this.visitor.WebSocketChannel(d,`${t.id}/websocket/${l}`)]),n=Object.entries(t.webhooks).map(([l,d])=>[l,this.visitor.WebhookDefinition(d,`${t.id}/webhoook/${l}`)]),a=Object.entries(t.types).map(([l,d])=>[l,this.visitor.TypeDefinition(d,`${t.id}/type-definition/${l}`)]),u=t.globalHeaders?.map(l=>this.visitor.ObjectProperty(l,`${t.id}/global-headers/${l.key}`))??[];return{id:t.id,endpoints:Object.fromEntries(r),websockets:Object.fromEntries(i),webhooks:Object.fromEntries(n),types:Object.fromEntries(a),globalHeaders:u,auths:t.auths,subpackages:t.subpackages,snippetsConfiguration:t.snippetsConfiguration}};#e=t=>({CodeSnippet:t.CodeSnippet,ErrorExample:t.ErrorExample,ExampleWebSocketSession:t.ExampleWebSocketSession,ObjectProperty:t.ObjectProperty,EnumValue:t.EnumValue,UndiscriminatedUnionVariant:t.UndiscriminatedUnionVariant,FormDataFile:t.FormDataFile,FormDataFiles:t.FormDataFiles,EndpointDefinition:(i,n)=>t.EndpointDefinition(this.endpoint(i,n),n),HttpRequest:(i,n)=>t.HttpRequest(this.httpRequest(i,n),n),HttpResponse:(i,n)=>t.HttpResponse(this.httpResponse(i,n),n),ErrorResponse:(i,n)=>t.ErrorResponse(this.errorResponse(i,n),n),ExampleEndpointCall:(i,n)=>t.ExampleEndpointCall(this.exampleEndpointCall(i,n),n),WebhookDefinition:(i,n)=>t.WebhookDefinition(this.webhookDefinition(i,n),n),WebhookPayload:(i,n)=>t.WebhookPayload(this.webhookPayload(i,n),n),WebSocketChannel:(i,n)=>t.WebSocketChannel(this.webSocketChannel(i,n),n),WebSocketMessage:(i,n)=>t.WebSocketMessage(this.webSocketMessage(i,n),n),TypeDefinition:(i,n)=>t.TypeDefinition(this.typeDefinition(i,n),n),TypeShape:(i,n)=>t.TypeShape(this.typeShape(i,n),n),ObjectType:(i,n)=>t.ObjectType(this.objectType(i,n),n),DiscriminatedUnionVariant:(i,n)=>t.DiscriminatedUnionVariant(this.objectType(i,n),n),FormDataRequest:(i,n)=>t.FormDataRequest(this.formDataRequest(i,n),n),FormDataField:(i,n)=>t.FormDataField(this.formDataField(i,n),n)});endpoint=(t,r)=>{let i=t.pathParameters?.map(c=>this.visitor.ObjectProperty(c,`${r}/path/${c.key}`))??[],n=t.queryParameters?.map(c=>this.visitor.ObjectProperty(c,`${r}/query/${c.key}`))??[],a=t.requestHeaders?.map(c=>this.visitor.ObjectProperty(c,`${r}/requestHeader/${c.key}`))??[],u=t.responseHeaders?.map(c=>this.visitor.ObjectProperty(c,`${r}/responseHeader/${c.key}`))??[],l=t.requests?.map((c,b)=>this.visitor.HttpRequest(c,`${r}/request/${b}`)),d=t.responses?.map((c,b)=>this.visitor.HttpResponse(c,`${r}/response/${b}/${c.statusCode}`)),s=t.errors?.map((c,b)=>this.visitor.ErrorResponse(c,`${r}/error/${b}/${c.statusCode}`))??[],o=t.examples?.map((c,b)=>this.visitor.ExampleEndpointCall(c,`${r}/example/${b}`))??[];return{...t,pathParameters:i.length>0?i:void 0,queryParameters:n.length>0?n:void 0,requestHeaders:a.length>0?a:void 0,responseHeaders:u.length>0?u:void 0,requests:l,responses:d,errors:s.length>0?s:void 0,examples:o.length>0?o:void 0}};httpRequest=(t,r)=>{let i=Ky(t.body)._visit({object:n=>({...n,...this.visitor.ObjectType(n,`${r}/object`)}),alias:KA,bytes:KA,formData:n=>({...n,...this.visitor.FormDataRequest(n,`${r}/formdata`)})});return{...t,body:i}};formDataField=(t,r)=>Ky(t)._visit({file:i=>({...i,...this.visitor.FormDataFile(i,`${r}/file/${i.key}`)}),files:i=>({...i,...this.visitor.FormDataFiles(i,`${r}/files/${i.key}`)}),property:i=>({...i,...this.visitor.ObjectProperty(i,`${r}/property/${i.key}`)})});httpResponse=(t,r)=>{let i=Ky(t.body)._visit({object:n=>({...n,...this.visitor.ObjectType(n,`${r}/object`)}),alias:KA,fileDownload:KA,streamingText:KA,stream:n=>({...n,shape:this.visitor.TypeShape(n.shape,`${r}/stream/shape`)}),empty:KA});return{...t,body:i}};objectType=(t,r)=>{let i=t.properties.map(n=>this.visitor.ObjectProperty(n,`${r}/property/${n.key}`));return{...t,properties:i}};errorResponse=(t,r)=>{let i=t.shape?this.visitor.TypeShape(t.shape,`${r}/error/shape`):void 0,n=t.examples?.map((a,u)=>this.visitor.ErrorExample(a,`${r}/example/${u}`))??[];return{...t,shape:i,examples:n.length>0?n:void 0}};exampleEndpointCall=(t,r)=>{let i=Object.entries(t.snippets??{}).map(([a,u])=>[a,u.map((l,d)=>this.visitor.CodeSnippet(l,`${r}/snippet/${a}/${d}`))]).filter(([,a])=>a.length>0),n=Object.fromEntries(i);return{...t,snippets:i.length>0?n:void 0}};webhookDefinition=(t,r)=>{let i=t.payloads?.[0]!=null?this.visitor.WebhookPayload(t.payloads[0],`${r}/payload`):void 0,n=t.headers?.map(a=>this.visitor.ObjectProperty(a,`${r}/header/${a.key}`))??[];return{...t,payloads:i!=null?[i]:void 0,headers:n.length>0?n:void 0}};webhookPayload=(t,r)=>{let i=this.visitor.TypeShape(t.shape,`${r}/shape`);return{...t,shape:i}};webSocketChannel=(t,r)=>{let i=t.pathParameters?.map(d=>this.visitor.ObjectProperty(d,`${r}/path/${d.key}`))??[],n=t.queryParameters?.map(d=>this.visitor.ObjectProperty(d,`${r}/query/${d.key}`))??[],a=t.requestHeaders?.map(d=>this.visitor.ObjectProperty(d,`${r}/requestHeader/${d.key}`))??[],u=t.messages.map(d=>this.visitor.WebSocketMessage(d,`${r}/message/${d.origin}/${d.type}`)),l=t.examples?.map((d,s)=>this.visitor.ExampleWebSocketSession(d,`${r}/example/${s}`))??[];return{...t,pathParameters:i.length>0?i:void 0,queryParameters:n.length>0?n:void 0,requestHeaders:a.length>0?a:void 0,messages:u,examples:l.length>0?l:void 0}};webSocketMessage=(t,r)=>{let i=this.visitor.TypeShape(t.body,`${r}/body`);return{...t,body:i}};typeShape=(t,r)=>Ky(t)._visit({object:i=>({...i,...this.visitor.ObjectType(i,`${r}/object`)}),alias:KA,enum:i=>({...i,values:i.values.map(n=>this.visitor.EnumValue(n,`${r}/enum/value/${n.value}`))}),undiscriminatedUnion:i=>({...i,variants:i.variants.map((n,a)=>this.visitor.UndiscriminatedUnionVariant(n,`${r}/undiscriminatedUnion/variant/${a}`))}),discriminatedUnion:i=>({...i,variants:i.variants.map(n=>this.visitor.DiscriminatedUnionVariant(n,`${r}/discriminatedUnion/variant/${n.discriminantValue}`))})});formDataRequest=(t,r)=>({...t,fields:t.fields.map(i=>this.visitor.FormDataField(i,`${r}/field/${i.key}`))});typeDefinition=(t,r)=>({...t,shape:this.visitor.TypeShape(t.shape,`${r}/shape`)})};function ynM(e){if(e==null)return"";let t=new URLSearchParams;return Object.entries(e).forEach(([r,i])=>{i!=null&&t.set(r,VMe(i))}),t.size>0?"?"+t.toString():""}function vnM(e=[],t){return e.map(r=>{if(r.type==="pathParameter"){let i=r.value,n=VMe(t?.[i]);return n.length>0?encodeURIComponent(n):":"+i}return r.value}).join("")}function K6_({baseUrl:e="",path:t,pathParameters:r,queryParameters:i}){return e+vnM(t,r)+ynM(i)}function A1c({endpoint:e,pathParameters:t,queryParameters:r,baseUrl:i}){return K6_({baseUrl:i??(e?.environments?.find(n=>n.id===e.defaultEnvironment)??e?.environments?.[0])?.baseUrl,path:e?.path,pathParameters:t,queryParameters:r})}var j2_=require("util");var SE=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol:e=>`Symbol(${e})`;function O4_(){}function MJ(e){return typeof e=="object"&&e!==null||typeof e=="function"}var m4_=O4_;function bA(e,t){try{Object.defineProperty(e,"name",{value:t,configurable:!0})}catch{}}var V1c=Promise,bnM=Promise.prototype.then,gnM=Promise.resolve.bind(V1c),OnM=Promise.reject.bind(V1c);function Ek(e){return new V1c(e)}function YA(e){return gnM(e)}function hg(e){return OnM(e)}function Vpi(e,t,r){return bnM.call(e,t,r)}function EJ(e,t,r){Vpi(Vpi(e,t,r),void 0,m4_)}function Y6_(e,t){EJ(e,t)}function X6_(e,t){EJ(e,void 0,t)}function RHt(e,t,r){return Vpi(e,t,r)}function ELn(e){Vpi(e,void 0,m4_)}var Btu=e=>{if(typeof queueMicrotask=="function")Btu=queueMicrotask;else{let t=YA(void 0);Btu=r=>Vpi(t,r)}return Btu(e)};function Qtu(e,t,r){if(typeof e!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function fYi(e,t,r){try{return YA(Qtu(e,t,r))}catch(i){return hg(i)}}var loe=class{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(t){let r=this._back,i=r;r._elements.length===16383&&(i={_elements:[],_next:void 0}),r._elements.push(t),i!==r&&(this._back=i,r._next=i),++this._size}shift(){let t=this._front,r=t,i=this._cursor,n=i+1,a=t._elements,u=a[i];return n===16384&&(r=t._next,n=0),--this._size,this._cursor=n,t!==r&&(this._front=r),a[i]=void 0,u}forEach(t){let r=this._cursor,i=this._front,n=i._elements;for(;!(r===n.length&&i._next===void 0||r===n.length&&(i=i._next,n=i._elements,r=0,n.length===0));)t(n[r]),++r}peek(){let t=this._front,r=this._cursor;return t._elements[r]}},P4_=SE("[[AbortSteps]]"),j4_=SE("[[ErrorSteps]]"),W1c=SE("[[CancelSteps]]"),H1c=SE("[[PullSteps]]"),$1c=SE("[[ReleaseSteps]]");function w4_(e,t){e._ownerReadableStream=t,t._reader=e,t._state==="readable"?z1c(e):t._state==="closed"?function(r){z1c(r),M4_(r)}(e):E4_(e,t._storedError)}function S4_(e,t){return n2_(e._ownerReadableStream,t)}function D4_(e){let t=e._ownerReadableStream;t._state==="readable"?G1c(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(r,i){E4_(r,i)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),t._readableStreamController[$1c](),t._reader=void 0,e._ownerReadableStream=void 0}function MLn(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function z1c(e){e._closedPromise=Ek((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r})}function E4_(e,t){z1c(e),G1c(e,t)}function G1c(e,t){e._closedPromise_reject!==void 0&&(ELn(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function M4_(e){e._closedPromise_resolve!==void 0&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}var Z6_=Number.isFinite||function(e){return typeof e=="number"&&isFinite(e)},mnM=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function Wpi(e,t){if(e!==void 0&&typeof(r=e)!="object"&&typeof r!="function")throw new TypeError(`${t} is not an object.`);var r}function NHt(e,t){if(typeof e!="function")throw new TypeError(`${t} is not a function.`)}function A4_(e,t){if(!function(r){return typeof r=="object"&&r!==null||typeof r=="function"}(e))throw new TypeError(`${t} is not an object.`)}function Hpi(e,t,r){if(e===void 0)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function x1c(e,t,r){if(e===void 0)throw new TypeError(`${t} is required in '${r}'.`)}function Q1c(e){return Number(e)}function k6_(e){return e===0?0:e}function q4_(e,t){let r=Number.MAX_SAFE_INTEGER,i=Number(e);if(i=k6_(i),!Z6_(i))throw new TypeError(`${t} is not a finite number`);if(i=function(n){return k6_(mnM(n))}(i),i<0||i>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return Z6_(i)&&i!==0?i:0}function zNa(e){if(!MJ(e)||typeof e.getReader!="function")return!1;try{return typeof e.locked=="boolean"}catch{return!1}}function T4_(e){if(!MJ(e)||typeof e.getWriter!="function")return!1;try{return typeof e.locked=="boolean"}catch{return!1}}function C4_(e,t){if(!cYi(e))throw new TypeError(`${t} is not a ReadableStream.`)}function B4_(e,t){e._reader._readRequests.push(t)}function J1c(e,t,r){let i=e._reader._readRequests.shift();r?i._closeSteps():i._chunkSteps(t)}function Jtu(e){return e._reader._readRequests.length}function I4_(e){let t=e._reader;return t!==void 0&&!!sYi(t)}var xpi=class{constructor(t){if(Hpi(t,1,"ReadableStreamDefaultReader"),C4_(t,"First parameter"),TLn(t))throw new TypeError("This stream has already been locked for exclusive reading by another reader");w4_(this,t),this._readRequests=new loe}get closed(){return sYi(this)?this._closedPromise:hg(Stu("closed"))}cancel(t){return sYi(this)?this._ownerReadableStream===void 0?hg(MLn("cancel")):S4_(this,t):hg(Stu("cancel"))}read(){if(!sYi(this))return hg(Stu("read"));if(this._ownerReadableStream===void 0)return hg(MLn("read from"));let t,r,i=Ek((n,a)=>{t=n,r=a});return function(n,a){let u=n._ownerReadableStream;u._disturbed=!0,u._state==="closed"?a._closeSteps():u._state==="errored"?a._errorSteps(u._storedError):u._readableStreamController[H1c](a)}(this,{_chunkSteps:n=>t({value:n,done:!1}),_closeSteps:()=>t({value:void 0,done:!0}),_errorSteps:n=>r(n)}),i}releaseLock(){if(!sYi(this))throw Stu("releaseLock");this._ownerReadableStream!==void 0&&function(t){D4_(t);let r=new TypeError("Reader was released");z4_(t,r)}(this)}};function sYi(e){return!!MJ(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof xpi}function z4_(e,t){let r=e._readRequests;e._readRequests=new loe,r.forEach(i=>{i._errorSteps(t)})}function Stu(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}Object.defineProperties(xpi.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),bA(xpi.prototype.cancel,"cancel"),bA(xpi.prototype.read,"read"),bA(xpi.prototype.releaseLock,"releaseLock"),typeof SE.toStringTag=="symbol"&&Object.defineProperty(xpi.prototype,SE.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});var Ntu=class{constructor(t,r){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=t,this._preventCancel=r}next(){let t=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?RHt(this._ongoingPromise,t,t):t(),this._ongoingPromise}return(t){let r=()=>this._returnSteps(t);return this._ongoingPromise?RHt(this._ongoingPromise,r,r):r()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let t=this._reader;return t===void 0?hg(MLn("iterate")):Vpi(t.read(),r=>{var i;return this._ongoingPromise=void 0,r.done&&(this._isFinished=!0,(i=this._reader)===null||i===void 0||i.releaseLock(),this._reader=void 0),r},r=>{var i;throw this._ongoingPromise=void 0,this._isFinished=!0,(i=this._reader)===null||i===void 0||i.releaseLock(),this._reader=void 0,r})}_returnSteps(t){if(this._isFinished)return Promise.resolve({value:t,done:!0});this._isFinished=!0;let r=this._reader;if(r===void 0)return hg(MLn("finish iterating"));if(this._reader=void 0,!this._preventCancel){let i=r.cancel(t);return r.releaseLock(),RHt(i,()=>({value:t,done:!0}))}return r.releaseLock(),YA({value:t,done:!0})}},x4_={next(){return e4_(this)?this._asyncIteratorImpl.next():hg(t4_("next"))},return(e){return e4_(this)?this._asyncIteratorImpl.return(e):hg(t4_("return"))}};function e4_(e){if(!MJ(e)||!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof Ntu}catch{return!1}}function t4_(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}typeof SE.asyncIterator=="symbol"&&Object.defineProperty(x4_,SE.asyncIterator,{value(){return this},writable:!0,configurable:!0});var R4_=Number.isNaN||function(e){return e!=e};function N4_(e,t,r,i,n){new Uint8Array(e).set(new Uint8Array(r,i,n),t)}function r4_(e){let t=function(r,i,n){if(r.slice)return r.slice(i,n);let a=n-i,u=new ArrayBuffer(a);return N4_(u,0,r,i,a),u}(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(t)}function R1c(e){let t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function K1c(e,t,r){if(typeof(i=r)!="number"||R4_(i)||i<0||r===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var i;e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function lqi(e){e._queue=new loe,e._queueTotalSize=0}var sqi=class{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!q1c(this))throw T1c("view");return this._view}respond(t){if(!q1c(this))throw T1c("respond");if(Hpi(t,1,"respond"),t=q4_(t,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,function(r,i){let n=r._pendingPullIntos.peek();if(r._controlledReadableByteStream._state==="closed"){if(i!==0)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(i===0)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(n.bytesFilled+i>n.byteLength)throw new RangeError("bytesWritten out of range")}n.buffer=n.buffer,i4_(r,i)}(this._associatedReadableByteStreamController,t)}respondWithNewView(t){if(!q1c(this))throw T1c("respondWithNewView");if(Hpi(t,1,"respondWithNewView"),!ArrayBuffer.isView(t))throw new TypeError("You can only respond with array buffer views");if(this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");t.buffer,function(r,i){let n=r._pendingPullIntos.peek();if(r._controlledReadableByteStream._state==="closed"){if(i.byteLength!==0)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(i.byteLength===0)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(n.byteOffset+n.bytesFilled!==i.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(n.bufferByteLength!==i.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(n.bytesFilled+i.byteLength>n.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let a=i.byteLength;n.buffer=i.buffer,i4_(r,a)}(this._associatedReadableByteStreamController,t)}};Object.defineProperties(sqi.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),bA(sqi.prototype.respond,"respond"),bA(sqi.prototype.respondWithNewView,"respondWithNewView"),typeof SE.toStringTag=="symbol"&&Object.defineProperty(sqi.prototype,SE.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});var Rpi=class{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!wLn(this))throw BNa("byobRequest");return function(t){if(t._byobRequest===null&&t._pendingPullIntos.length>0){let r=t._pendingPullIntos.peek(),i=new Uint8Array(r.buffer,r.byteOffset+r.bytesFilled,r.byteLength-r.bytesFilled),n=Object.create(sqi.prototype);(function(a,u,l){a._associatedReadableByteStreamController=u,a._view=l})(n,t,i),t._byobRequest=n}return t._byobRequest}(this)}get desiredSize(){if(!wLn(this))throw BNa("desiredSize");return G4_(this)}close(){if(!wLn(this))throw BNa("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let t=this._controlledReadableByteStream._state;if(t!=="readable")throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be closed`);(function(r){let i=r._controlledReadableByteStream;if(!(r._closeRequested||i._state!=="readable")){if(r._queueTotalSize>0)return void(r._closeRequested=!0);if(r._pendingPullIntos.length>0&&r._pendingPullIntos.peek().bytesFilled>0){let n=new TypeError("Insufficient bytes to fill elements in the given buffer");throw ALn(r,n),n}Ftu(r),LNa(i)}})(this)}enqueue(t){if(!wLn(this))throw BNa("enqueue");if(Hpi(t,1,"enqueue"),!ArrayBuffer.isView(t))throw new TypeError("chunk must be an array buffer view");if(t.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(t.buffer.byteLength===0)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");let r=this._controlledReadableByteStream._state;if(r!=="readable")throw new TypeError(`The stream (in ${r} state) is not in the readable state and cannot be enqueued to`);(function(i,n){let a=i._controlledReadableByteStream;if(i._closeRequested||a._state!=="readable")return;let u=n.buffer,l=n.byteOffset,d=n.byteLength,s=u;if(i._pendingPullIntos.length>0){let o=i._pendingPullIntos.peek();o.buffer,Y1c(i),o.buffer=o.buffer,o.readerType==="none"&&V4_(i,o)}I4_(a)?(function(o){let c=o._controlledReadableByteStream._reader;for(;c._readRequests.length>0;){if(o._queueTotalSize===0)return;n4_(o,c._readRequests.shift())}}(i),Jtu(a)===0?Itu(i,s,l,d):(i._pendingPullIntos.length>0&&DLn(i),J1c(a,new Uint8Array(s,l,d),!1))):X1c(a)?(Itu(i,s,l,d),F1c(i)):Itu(i,s,l,d),lYi(i)})(this,t)}error(t){if(!wLn(this))throw BNa("error");ALn(this,t)}[W1c](t){F4_(this),lqi(this);let r=this._cancelAlgorithm(t);return Ftu(this),r}[H1c](t){let r=this._controlledReadableByteStream;if(this._queueTotalSize>0)return void n4_(this,t);let i=this._autoAllocateChunkSize;if(i!==void 0){let n;try{n=new ArrayBuffer(i)}catch(u){return void t._errorSteps(u)}let a={buffer:n,bufferByteLength:i,byteOffset:0,byteLength:i,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(a)}B4_(r,t),lYi(this)}[$1c](){if(this._pendingPullIntos.length>0){let t=this._pendingPullIntos.peek();t.readerType="none",this._pendingPullIntos=new loe,this._pendingPullIntos.push(t)}}};function wLn(e){return!!MJ(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof Rpi}function q1c(e){return!!MJ(e)&&!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof sqi}function lYi(e){if(function(r){let i=r._controlledReadableByteStream;return i._state!=="readable"||r._closeRequested||!r._started?!1:!!(I4_(i)&&Jtu(i)>0||X1c(i)&&Q4_(i)>0||G4_(r)>0)}(e)){if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0,EJ(e._pullAlgorithm(),()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,lYi(e)),null),r=>(ALn(e,r),null))}}function F4_(e){Y1c(e),e._pendingPullIntos=new loe}function N1c(e,t){let r=!1;e._state==="closed"&&(r=!0);let i=L4_(t);t.readerType==="default"?J1c(e,i,r):function(n,a,u){let l=n._reader._readIntoRequests.shift();u?l._closeSteps(a):l._chunkSteps(a)}(e,i,r)}function L4_(e){let t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function Itu(e,t,r,i){e._queue.push({buffer:t,byteOffset:r,byteLength:i}),e._queueTotalSize+=i}function U4_(e,t,r,i){let n;try{n=t.slice(r,r+i)}catch(a){throw ALn(e,a),a}Itu(e,n,0,i)}function V4_(e,t){t.bytesFilled>0&&U4_(e,t.buffer,t.byteOffset,t.bytesFilled),DLn(e)}function W4_(e,t){let r=t.elementSize,i=t.bytesFilled-t.bytesFilled%r,n=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),a=t.bytesFilled+n,u=a-a%r,l=n,d=!1;u>i&&(l=u-t.bytesFilled,d=!0);let s=e._queue;for(;l>0;){let o=s.peek(),c=Math.min(l,o.byteLength),b=t.byteOffset+t.bytesFilled;N4_(t.buffer,b,o.buffer,o.byteOffset,c),o.byteLength===c?s.shift():(o.byteOffset+=c,o.byteLength-=c),e._queueTotalSize-=c,H4_(e,c,t),l-=c}return d}function H4_(e,t,r){r.bytesFilled+=t}function $4_(e){e._queueTotalSize===0&&e._closeRequested?(Ftu(e),LNa(e._controlledReadableByteStream)):lYi(e)}function Y1c(e){e._byobRequest!==null&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function F1c(e){for(;e._pendingPullIntos.length>0;){if(e._queueTotalSize===0)return;let t=e._pendingPullIntos.peek();W4_(e,t)&&(DLn(e),N1c(e._controlledReadableByteStream,t))}}function i4_(e,t){let r=e._pendingPullIntos.peek();Y1c(e),e._controlledReadableByteStream._state==="closed"?function(i,n){n.readerType==="none"&&DLn(i);let a=i._controlledReadableByteStream;if(X1c(a))for(;Q4_(a)>0;)N1c(a,DLn(i))}(e,r):function(i,n,a){if(H4_(0,n,a),a.readerType==="none")return V4_(i,a),void F1c(i);if(a.bytesFilled<a.elementSize)return;DLn(i);let u=a.bytesFilled%a.elementSize;if(u>0){let l=a.byteOffset+a.bytesFilled;U4_(i,a.buffer,l-u,u)}a.bytesFilled-=u,N1c(i._controlledReadableByteStream,a),F1c(i)}(e,t,r),lYi(e)}function DLn(e){return e._pendingPullIntos.shift()}function Ftu(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function ALn(e,t){let r=e._controlledReadableByteStream;r._state==="readable"&&(F4_(e),lqi(e),Ftu(e),a2_(r,t))}function n4_(e,t){let r=e._queue.shift();e._queueTotalSize-=r.byteLength,$4_(e);let i=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);t._chunkSteps(i)}function G4_(e){let t=e._controlledReadableByteStream._state;return t==="errored"?null:t==="closed"?0:e._strategyHWM-e._queueTotalSize}function PnM(e,t,r){let i=Object.create(Rpi.prototype),n,a,u;n=t.start!==void 0?()=>t.start(i):()=>{},a=t.pull!==void 0?()=>t.pull(i):()=>YA(void 0),u=t.cancel!==void 0?d=>t.cancel(d):()=>YA(void 0);let l=t.autoAllocateChunkSize;if(l===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");(function(d,s,o,c,b,g,O){s._controlledReadableByteStream=d,s._pullAgain=!1,s._pulling=!1,s._byobRequest=null,s._queue=s._queueTotalSize=void 0,lqi(s),s._closeRequested=!1,s._started=!1,s._strategyHWM=g,s._pullAlgorithm=c,s._cancelAlgorithm=b,s._autoAllocateChunkSize=O,s._pendingPullIntos=new loe,d._readableStreamController=s,EJ(YA(o()),()=>(s._started=!0,lYi(s),null),m=>(ALn(s,m),null))})(e,i,n,a,u,r,l)}function T1c(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function BNa(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function a4_(e,t){e._reader._readIntoRequests.push(t)}function Q4_(e){return e._reader._readIntoRequests.length}function X1c(e){let t=e._reader;return t!==void 0&&!!SLn(t)}Object.defineProperties(Rpi.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),bA(Rpi.prototype.close,"close"),bA(Rpi.prototype.enqueue,"enqueue"),bA(Rpi.prototype.error,"error"),typeof SE.toStringTag=="symbol"&&Object.defineProperty(Rpi.prototype,SE.toStringTag,{value:"ReadableByteStreamController",configurable:!0});var Npi=class{constructor(t){if(Hpi(t,1,"ReadableStreamBYOBReader"),C4_(t,"First parameter"),TLn(t))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!wLn(t._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");w4_(this,t),this._readIntoRequests=new loe}get closed(){return SLn(this)?this._closedPromise:hg(Dtu("closed"))}cancel(t){return SLn(this)?this._ownerReadableStream===void 0?hg(MLn("cancel")):S4_(this,t):hg(Dtu("cancel"))}read(t){if(!SLn(this))return hg(Dtu("read"));if(!ArrayBuffer.isView(t))return hg(new TypeError("view must be an array buffer view"));if(t.byteLength===0)return hg(new TypeError("view must have non-zero byteLength"));if(t.buffer.byteLength===0)return hg(new TypeError("view's buffer must have non-zero byteLength"));if(t.buffer,this._ownerReadableStream===void 0)return hg(MLn("read from"));let r,i,n=Ek((a,u)=>{r=a,i=u});return function(a,u,l){let d=a._ownerReadableStream;d._disturbed=!0,d._state==="errored"?l._errorSteps(d._storedError):function(s,o,c){let b=s._controlledReadableByteStream,g=1;o.constructor!==DataView&&(g=o.constructor.BYTES_PER_ELEMENT);let O=o.constructor,m=o.buffer,P={buffer:m,bufferByteLength:m.byteLength,byteOffset:o.byteOffset,byteLength:o.byteLength,bytesFilled:0,elementSize:g,viewConstructor:O,readerType:"byob"};if(s._pendingPullIntos.length>0)return s._pendingPullIntos.push(P),void a4_(b,c);if(b._state!=="closed"){if(s._queueTotalSize>0){if(W4_(s,P)){let E=L4_(P);return $4_(s),void c._chunkSteps(E)}if(s._closeRequested){let E=new TypeError("Insufficient bytes to fill elements in the given buffer");return ALn(s,E),void c._errorSteps(E)}}s._pendingPullIntos.push(P),a4_(b,c),lYi(s)}else{let E=new O(P.buffer,P.byteOffset,0);c._closeSteps(E)}}(d._readableStreamController,u,l)}(this,t,{_chunkSteps:a=>r({value:a,done:!1}),_closeSteps:a=>r({value:a,done:!0}),_errorSteps:a=>i(a)}),n}releaseLock(){if(!SLn(this))throw Dtu("releaseLock");this._ownerReadableStream!==void 0&&function(t){D4_(t);let r=new TypeError("Reader was released");J4_(t,r)}(this)}};function SLn(e){return!!MJ(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof Npi}function J4_(e,t){let r=e._readIntoRequests;e._readIntoRequests=new loe,r.forEach(i=>{i._errorSteps(t)})}function Dtu(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function FNa(e,t){let{highWaterMark:r}=e;if(r===void 0)return t;if(R4_(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function Ltu(e){let{size:t}=e;return t||(()=>1)}function Utu(e,t){Wpi(e,t);let r=e?.highWaterMark,i=e?.size;return{highWaterMark:r===void 0?void 0:Q1c(r),size:i===void 0?void 0:jnM(i,`${t} has member 'size' that`)}}function jnM(e,t){return NHt(e,t),r=>Q1c(e(r))}function wnM(e,t,r){return NHt(e,r),i=>fYi(e,t,[i])}function SnM(e,t,r){return NHt(e,r),()=>fYi(e,t,[])}function DnM(e,t,r){return NHt(e,r),i=>Qtu(e,t,[i])}function EnM(e,t,r){return NHt(e,r),(i,n)=>fYi(e,t,[i,n])}Object.defineProperties(Npi.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),bA(Npi.prototype.cancel,"cancel"),bA(Npi.prototype.read,"read"),bA(Npi.prototype.releaseLock,"releaseLock"),typeof SE.toStringTag=="symbol"&&Object.defineProperty(Npi.prototype,SE.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});var MnM=typeof AbortController=="function",Fpi=class{constructor(t={},r={}){t===void 0?t=null:A4_(t,"First parameter");let i=Utu(r,"Second parameter"),n=function(l,d){Wpi(l,d);let s=l?.abort,o=l?.close,c=l?.start,b=l?.type,g=l?.write;return{abort:s===void 0?void 0:wnM(s,l,`${d} has member 'abort' that`),close:o===void 0?void 0:SnM(o,l,`${d} has member 'close' that`),start:c===void 0?void 0:DnM(c,l,`${d} has member 'start' that`),write:g===void 0?void 0:EnM(g,l,`${d} has member 'write' that`),type:b}}(t,"First parameter");var a;if((a=this)._state="writable",a._storedError=void 0,a._writer=void 0,a._writableStreamController=void 0,a._writeRequests=new loe,a._inFlightWriteRequest=void 0,a._closeRequest=void 0,a._inFlightCloseRequest=void 0,a._pendingAbortRequest=void 0,a._backpressure=!1,n.type!==void 0)throw new RangeError("Invalid type is specified");let u=Ltu(i);(function(l,d,s,o){let c=Object.create(qLn.prototype),b,g,O,m;b=d.start!==void 0?()=>d.start(c):()=>{},g=d.write!==void 0?P=>d.write(P,c):()=>YA(void 0),O=d.close!==void 0?()=>d.close():()=>YA(void 0),m=d.abort!==void 0?P=>d.abort(P):()=>YA(void 0),function(P,E,q,M,D,T,x,$){E._controlledWritableStream=P,P._writableStreamController=E,E._queue=void 0,E._queueTotalSize=void 0,lqi(E),E._abortReason=void 0,E._abortController=function(){if(MnM)return new AbortController}(),E._started=!1,E._strategySizeAlgorithm=$,E._strategyHWM=x,E._writeAlgorithm=M,E._closeAlgorithm=D,E._abortAlgorithm=T;let I=tSc(E);eSc(P,I);let L=q();EJ(YA(L),()=>(E._started=!0,Ktu(E),null),V=>(E._started=!0,L1c(P,V),null))}(l,c,b,g,O,m,s,o)})(this,n,FNa(i,1),u)}get locked(){if(!tnr(this))throw Mtu("locked");return ztu(this)}abort(t){return tnr(this)?ztu(this)?hg(new TypeError("Cannot abort a stream that already has a writer")):K4_(this,t):hg(Mtu("abort"))}close(){return tnr(this)?ztu(this)?hg(new TypeError("Cannot close a stream that already has a writer")):cqi(this)?hg(new TypeError("Cannot close an already-closing stream")):Y4_(this):hg(Mtu("close"))}getWriter(){if(!tnr(this))throw Mtu("getWriter");return new enr(this)}};function tnr(e){return!!MJ(e)&&!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof Fpi}function ztu(e){return e._writer!==void 0}function K4_(e,t){var r;if(e._state==="closed"||e._state==="errored")return YA(void 0);e._writableStreamController._abortReason=t,(r=e._writableStreamController._abortController)===null||r===void 0||r.abort(t);let i=e._state;if(i==="closed"||i==="errored")return YA(void 0);if(e._pendingAbortRequest!==void 0)return e._pendingAbortRequest._promise;let n=!1;i==="erroring"&&(n=!0,t=void 0);let a=Ek((u,l)=>{e._pendingAbortRequest={_promise:void 0,_resolve:u,_reject:l,_reason:t,_wasAlreadyErroring:n}});return e._pendingAbortRequest._promise=a,n||Z1c(e,t),a}function Y4_(e){let t=e._state;if(t==="closed"||t==="errored")return hg(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));let r=Ek((a,u)=>{let l={_resolve:a,_reject:u};e._closeRequest=l}),i=e._writer;var n;return i!==void 0&&e._backpressure&&t==="writable"&&iSc(i),K1c(n=e._writableStreamController,Z4_,0),Ktu(n),r}function L1c(e,t){e._state!=="writable"?k1c(e):Z1c(e,t)}function Z1c(e,t){let r=e._writableStreamController;e._state="erroring",e._storedError=t;let i=e._writer;i!==void 0&&X4_(i,t),!function(n){return!(n._inFlightWriteRequest===void 0&&n._inFlightCloseRequest===void 0)}(e)&&r._started&&k1c(e)}function k1c(e){e._state="errored",e._writableStreamController[j4_]();let t=e._storedError;if(e._writeRequests.forEach(i=>{i._reject(t)}),e._writeRequests=new loe,e._pendingAbortRequest===void 0)return void Etu(e);let r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void Etu(e);EJ(e._writableStreamController[P4_](r._reason),()=>(r._resolve(),Etu(e),null),i=>(r._reject(i),Etu(e),null))}function cqi(e){return e._closeRequest!==void 0||e._inFlightCloseRequest!==void 0}function Etu(e){e._closeRequest!==void 0&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);let t=e._writer;t!==void 0&&rSc(t,e._storedError)}function eSc(e,t){let r=e._writer;r!==void 0&&t!==e._backpressure&&(t?function(i){Ytu(i)}(r):iSc(r)),e._backpressure=t}Object.defineProperties(Fpi.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),bA(Fpi.prototype.abort,"abort"),bA(Fpi.prototype.close,"close"),bA(Fpi.prototype.getWriter,"getWriter"),typeof SE.toStringTag=="symbol"&&Object.defineProperty(Fpi.prototype,SE.toStringTag,{value:"WritableStream",configurable:!0});var enr=class{constructor(t){if(Hpi(t,1,"WritableStreamDefaultWriter"),function(n,a){if(!tnr(n))throw new TypeError(`${a} is not a WritableStream.`)}(t,"First parameter"),ztu(t))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=t,t._writer=this;let r=t._state;if(r==="writable")!cqi(t)&&t._backpressure?Ytu(this):s4_(this),xtu(this);else if(r==="erroring")U1c(this,t._storedError),xtu(this);else if(r==="closed")s4_(this),xtu(i=this),t2_(i);else{let n=t._storedError;U1c(this,n),u4_(this,n)}var i}get closed(){return aYi(this)?this._closedPromise:hg(oYi("closed"))}get desiredSize(){if(!aYi(this))throw oYi("desiredSize");if(this._ownerWritableStream===void 0)throw INa("desiredSize");return function(t){let r=t._ownerWritableStream,i=r._state;return i==="errored"||i==="erroring"?null:i==="closed"?0:k4_(r._writableStreamController)}(this)}get ready(){return aYi(this)?this._readyPromise:hg(oYi("ready"))}abort(t){return aYi(this)?this._ownerWritableStream===void 0?hg(INa("abort")):function(r,i){return K4_(r._ownerWritableStream,i)}(this,t):hg(oYi("abort"))}close(){if(!aYi(this))return hg(oYi("close"));let t=this._ownerWritableStream;return t===void 0?hg(INa("close")):cqi(t)?hg(new TypeError("Cannot close an already-closing stream")):Y4_(this._ownerWritableStream)}releaseLock(){if(!aYi(this))throw oYi("releaseLock");this._ownerWritableStream!==void 0&&function(t){let r=t._ownerWritableStream,i=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");X4_(t,i),function(n,a){n._closedPromiseState==="pending"?rSc(n,a):function(u,l){u4_(u,l)}(n,a)}(t,i),r._writer=void 0,t._ownerWritableStream=void 0}(this)}write(t){return aYi(this)?this._ownerWritableStream===void 0?hg(INa("write to")):function(r,i){let n=r._ownerWritableStream,a=n._writableStreamController,u=function(s,o){try{return s._strategySizeAlgorithm(o)}catch(c){return o4_(s,c),1}}(a,i);if(n!==r._ownerWritableStream)return hg(INa("write to"));let l=n._state;if(l==="errored")return hg(n._storedError);if(cqi(n)||l==="closed")return hg(new TypeError("The stream is closing or closed and cannot be written to"));if(l==="erroring")return hg(n._storedError);let d=function(s){return Ek((o,c)=>{let b={_resolve:o,_reject:c};s._writeRequests.push(b)})}(n);return function(s,o,c){try{K1c(s,o,c)}catch(g){return void o4_(s,g)}let b=s._controlledWritableStream;!cqi(b)&&b._state==="writable"&&eSc(b,tSc(s)),Ktu(s)}(a,i,u),d}(this,t):hg(oYi("write"))}};function aYi(e){return!!MJ(e)&&!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof enr}function X4_(e,t){e._readyPromiseState==="pending"?r2_(e,t):function(r,i){U1c(r,i)}(e,t)}Object.defineProperties(enr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),bA(enr.prototype.abort,"abort"),bA(enr.prototype.close,"close"),bA(enr.prototype.releaseLock,"releaseLock"),bA(enr.prototype.write,"write"),typeof SE.toStringTag=="symbol"&&Object.defineProperty(enr.prototype,SE.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});var Z4_={},qLn=class{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!C1c(this))throw B1c("abortReason");return this._abortReason}get signal(){if(!C1c(this))throw B1c("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(t){if(!C1c(this))throw B1c("error");this._controlledWritableStream._state==="writable"&&e2_(this,t)}[P4_](t){let r=this._abortAlgorithm(t);return Vtu(this),r}[j4_](){lqi(this)}};function C1c(e){return!!MJ(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof qLn}function Vtu(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function k4_(e){return e._strategyHWM-e._queueTotalSize}function Ktu(e){let t=e._controlledWritableStream;if(!e._started||t._inFlightWriteRequest!==void 0)return;if(t._state==="erroring")return void k1c(t);if(e._queue.length===0)return;let r=e._queue.peek().value;r===Z4_?function(i){let n=i._controlledWritableStream;(function(u){u._inFlightCloseRequest=u._closeRequest,u._closeRequest=void 0})(n),R1c(i);let a=i._closeAlgorithm();Vtu(i),EJ(a,()=>(function(u){u._inFlightCloseRequest._resolve(void 0),u._inFlightCloseRequest=void 0,u._state==="erroring"&&(u._storedError=void 0,u._pendingAbortRequest!==void 0&&(u._pendingAbortRequest._resolve(),u._pendingAbortRequest=void 0)),u._state="closed";let l=u._writer;l!==void 0&&t2_(l)}(n),null),u=>(function(l,d){l._inFlightCloseRequest._reject(d),l._inFlightCloseRequest=void 0,l._pendingAbortRequest!==void 0&&(l._pendingAbortRequest._reject(d),l._pendingAbortRequest=void 0),L1c(l,d)}(n,u),null))}(e):function(i,n){let a=i._controlledWritableStream;(function(u){u._inFlightWriteRequest=u._writeRequests.shift()})(a),EJ(i._writeAlgorithm(n),()=>{(function(l){l._inFlightWriteRequest._resolve(void 0),l._inFlightWriteRequest=void 0})(a);let u=a._state;if(R1c(i),!cqi(a)&&u==="writable"){let l=tSc(i);eSc(a,l)}return Ktu(i),null},u=>(a._state==="writable"&&Vtu(i),function(l,d){l._inFlightWriteRequest._reject(d),l._inFlightWriteRequest=void 0,L1c(l,d)}(a,u),null))}(e,r)}function o4_(e,t){e._controlledWritableStream._state==="writable"&&e2_(e,t)}function tSc(e){return k4_(e)<=0}function e2_(e,t){let r=e._controlledWritableStream;Vtu(e),Z1c(r,t)}function Mtu(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function B1c(e){return new TypeError(`WritableStreamDefaultController.prototype.${e} can only be used on a WritableStreamDefaultController`)}function oYi(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function INa(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function xtu(e){e._closedPromise=Ek((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"})}function u4_(e,t){xtu(e),rSc(e,t)}function rSc(e,t){e._closedPromise_reject!==void 0&&(ELn(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function t2_(e){e._closedPromise_resolve!==void 0&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function Ytu(e){e._readyPromise=Ek((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r}),e._readyPromiseState="pending"}function U1c(e,t){Ytu(e),r2_(e,t)}function s4_(e){Ytu(e),iSc(e)}function r2_(e,t){e._readyPromise_reject!==void 0&&(ELn(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function iSc(e){e._readyPromise_resolve!==void 0&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(qLn.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof SE.toStringTag=="symbol"&&Object.defineProperty(qLn.prototype,SE.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});var c4_=typeof DOMException<"u"?DOMException:void 0,AnM=function(e){if(typeof e!="function"&&typeof e!="object")return!1;try{return new e,!0}catch{return!1}}(c4_)?c4_:function(){let e=function(t,r){this.message=t||"",this.name=r||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function l4_(e,t,r,i,n,a){let u=e.getReader(),l=t.getWriter();cYi(e)&&(e._disturbed=!0);let d,s,o,c=!1,b=!1,g="readable",O="writable",m=!1,P=!1,E=Ek(M=>{o=M}),q=Promise.resolve(void 0);return Ek((M,D)=>{let T;function x(){if(c)return;let k=Ek((fe,be)=>{(function _e(we){we?fe():Vpi(function(){return c?YA(!0):Vpi(l.ready,()=>Vpi(u.read(),Qe=>!!Qe.done||(q=l.write(Qe.value),ELn(q),!1)))}(),_e,be)})(!1)});ELn(k)}function $(){return g="closed",r?X():V(()=>(tnr(t)&&(m=cqi(t),O=t._state),m||O==="closed"?YA(void 0):O==="erroring"||O==="errored"?hg(s):(m=!0,l.close())),!1,void 0),null}function I(k){return c||(g="errored",d=k,i?X(!0,k):V(()=>l.abort(k),!0,k)),null}function L(k){return b||(O="errored",s=k,n?X(!0,k):V(()=>u.cancel(k),!0,k)),null}if(a!==void 0&&(T=()=>{let k=a.reason!==void 0?a.reason:new AnM("Aborted","AbortError"),fe=[];i||fe.push(()=>O==="writable"?l.abort(k):YA(void 0)),n||fe.push(()=>g==="readable"?u.cancel(k):YA(void 0)),V(()=>Promise.all(fe.map(be=>be())),!0,k)},a.aborted?T():a.addEventListener("abort",T)),cYi(e)&&(g=e._state,d=e._storedError),tnr(t)&&(O=t._state,s=t._storedError,m=cqi(t)),cYi(e)&&tnr(t)&&(P=!0,o()),g==="errored")I(d);else if(O==="erroring"||O==="errored")L(s);else if(g==="closed")$();else if(m||O==="closed"){let k=new TypeError("the destination writable stream closed before all data could be piped to it");n?X(!0,k):V(()=>u.cancel(k),!0,k)}function V(k,fe,be){function _e(){return O!=="writable"||m?we():Y6_(function(){let Qe;return YA(function Dt(){if(Qe!==q)return Qe=q,RHt(q,Dt,Dt)}())}(),we),null}function we(){return k?EJ(k(),()=>K(fe,be),Qe=>K(!0,Qe)):K(fe,be),null}c||(c=!0,P?_e():Y6_(E,_e))}function X(k,fe){V(void 0,k,fe)}function K(k,fe){return b=!0,l.releaseLock(),u.releaseLock(),a!==void 0&&a.removeEventListener("abort",T),k?D(fe):M(void 0),null}c||(EJ(u.closed,$,I),EJ(l.closed,function(){return b||(O="closed"),null},L)),P?x():Btu(()=>{P=!0,o(),x()})})}function qnM(e,t){return function(r){try{return r.getReader({mode:"byob"}).releaseLock(),!0}catch{return!1}}(e)?function(r){let i,n,a,u,l,d=r.getReader(),s=!1,o=!1,c=!1,b=!1,g=!1,O=!1,m=Ek(L=>{l=L});function P(L){X6_(L.closed,V=>(L!==d||(a.error(V),u.error(V),g&&O||l(void 0)),null))}function E(){s&&(d.releaseLock(),d=r.getReader(),P(d),s=!1),EJ(d.read(),L=>{var V,X;if(c=!1,b=!1,L.done)return g||a.close(),O||u.close(),(V=a.byobRequest)===null||V===void 0||V.respond(0),(X=u.byobRequest)===null||X===void 0||X.respond(0),g&&O||l(void 0),null;let K=L.value,k=K,fe=K;if(!g&&!O)try{fe=r4_(K)}catch(be){return a.error(be),u.error(be),l(d.cancel(be)),null}return g||a.enqueue(k),O||u.enqueue(fe),o=!1,c?M():b&&D(),null},()=>(o=!1,null))}function q(L,V){s||(d.releaseLock(),d=r.getReader({mode:"byob"}),P(d),s=!0);let X=V?u:a,K=V?a:u;EJ(d.read(L),k=>{var fe;c=!1,b=!1;let be=V?O:g,_e=V?g:O;if(k.done){be||X.close(),_e||K.close();let Qe=k.value;return Qe!==void 0&&(be||X.byobRequest.respondWithNewView(Qe),_e||(fe=K.byobRequest)===null||fe===void 0||fe.respond(0)),be&&_e||l(void 0),null}let we=k.value;if(_e)be||X.byobRequest.respondWithNewView(we);else{let Qe;try{Qe=r4_(we)}catch(Dt){return X.error(Dt),K.error(Dt),l(d.cancel(Dt)),null}be||X.byobRequest.respondWithNewView(we),K.enqueue(Qe)}return o=!1,c?M():b&&D(),null},()=>(o=!1,null))}function M(){if(o)return c=!0,YA(void 0);o=!0;let L=a.byobRequest;return L===null?E():q(L.view,!1),YA(void 0)}function D(){if(o)return b=!0,YA(void 0);o=!0;let L=u.byobRequest;return L===null?E():q(L.view,!0),YA(void 0)}function T(L){if(g=!0,i=L,O){let V=[i,n],X=d.cancel(V);l(X)}return m}function x(L){if(O=!0,n=L,g){let V=[i,n],X=d.cancel(V);l(X)}return m}let $=new c4({type:"bytes",start(L){a=L},pull:M,cancel:T}),I=new c4({type:"bytes",start(L){u=L},pull:D,cancel:x});return P(d),[$,I]}(e):function(r,i){let n=r.getReader(),a,u,l,d,s,o=!1,c=!1,b=!1,g=!1,O=Ek(D=>{s=D});function m(){return o?(c=!0,YA(void 0)):(o=!0,EJ(n.read(),D=>{if(c=!1,D.done)return b||l.close(),g||d.close(),b&&g||s(void 0),null;let T=D.value,x=T,$=T;return b||l.enqueue(x),g||d.enqueue($),o=!1,c&&m(),null},()=>(o=!1,null)),YA(void 0))}function P(D){if(b=!0,a=D,g){let T=[a,u],x=n.cancel(T);s(x)}return O}function E(D){if(g=!0,u=D,b){let T=[a,u],x=n.cancel(T);s(x)}return O}let q=new c4({start(D){l=D},pull:m,cancel:P}),M=new c4({start(D){d=D},pull:m,cancel:E});return X6_(n.closed,D=>(l.error(D),d.error(D),b&&g||s(void 0),null)),[q,M]}(e)}var Lpi=class{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Atu(this))throw qtu("desiredSize");return i2_(this)}close(){if(!Atu(this))throw qtu("close");if(!xNa(this))throw new TypeError("The stream is not in a state that permits close");(function(t){if(!xNa(t))return;let r=t._controlledReadableStream;t._closeRequested=!0,t._queue.length===0&&(Rtu(t),LNa(r))})(this)}enqueue(t){if(!Atu(this))throw qtu("enqueue");if(!xNa(this))throw new TypeError("The stream is not in a state that permits enqueue");return function(r,i){if(!xNa(r))return;let n=r._controlledReadableStream;if(TLn(n)&&Jtu(n)>0)J1c(n,i,!1);else{let a;try{a=r._strategySizeAlgorithm(i)}catch(u){throw NNa(r,u),u}try{K1c(r,i,a)}catch(u){throw NNa(r,u),u}}RNa(r)}(this,t)}error(t){if(!Atu(this))throw qtu("error");NNa(this,t)}[W1c](t){lqi(this);let r=this._cancelAlgorithm(t);return Rtu(this),r}[H1c](t){let r=this._controlledReadableStream;if(this._queue.length>0){let i=R1c(this);this._closeRequested&&this._queue.length===0?(Rtu(this),LNa(r)):RNa(this),t._chunkSteps(i)}else B4_(r,t),RNa(this)}[$1c](){}};function Atu(e){return!!MJ(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof Lpi}function RNa(e){if(function(r){let i=r._controlledReadableStream;return!xNa(r)||!r._started?!1:!!(TLn(i)&&Jtu(i)>0||i2_(r)>0)}(e)){if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0,EJ(e._pullAlgorithm(),()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,RNa(e)),null),r=>(NNa(e,r),null))}}function Rtu(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function NNa(e,t){let r=e._controlledReadableStream;r._state==="readable"&&(lqi(e),Rtu(e),a2_(r,t))}function i2_(e){let t=e._controlledReadableStream._state;return t==="errored"?null:t==="closed"?0:e._strategyHWM-e._queueTotalSize}function xNa(e){return!e._closeRequested&&e._controlledReadableStream._state==="readable"}function TnM(e,t,r,i){let n=Object.create(Lpi.prototype),a,u,l;a=t.start!==void 0?()=>t.start(n):()=>{},u=t.pull!==void 0?()=>t.pull(n):()=>YA(void 0),l=t.cancel!==void 0?d=>t.cancel(d):()=>YA(void 0),function(d,s,o,c,b,g,O){s._controlledReadableStream=d,s._queue=void 0,s._queueTotalSize=void 0,lqi(s),s._started=!1,s._closeRequested=!1,s._pullAgain=!1,s._pulling=!1,s._strategySizeAlgorithm=O,s._strategyHWM=g,s._pullAlgorithm=c,s._cancelAlgorithm=b,d._readableStreamController=s,EJ(YA(o()),()=>(s._started=!0,RNa(s),null),m=>(NNa(s,m),null))}(e,n,a,u,l,r,i)}function qtu(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function CnM(e,t,r){return NHt(e,r),i=>fYi(e,t,[i])}function BnM(e,t,r){return NHt(e,r),i=>fYi(e,t,[i])}function InM(e,t,r){return NHt(e,r),i=>Qtu(e,t,[i])}function znM(e,t){if((e=`${e}`)!="bytes")throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function xnM(e,t){if((e=`${e}`)!="byob")throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function f4_(e,t){Wpi(e,t);let r=e?.preventAbort,i=e?.preventCancel,n=e?.preventClose,a=e?.signal;return a!==void 0&&function(u,l){if(!function(d){if(typeof d!="object"||d===null)return!1;try{return typeof d.aborted=="boolean"}catch{return!1}}(u))throw new TypeError(`${l} is not an AbortSignal.`)}(a,`${t} has member 'signal' that`),{preventAbort:!!r,preventCancel:!!i,preventClose:!!n,signal:a}}function RnM(e,t){Wpi(e,t);let r=e?.readable;x1c(r,"readable","ReadableWritablePair"),function(n,a){if(!zNa(n))throw new TypeError(`${a} is not a ReadableStream.`)}(r,`${t} has member 'readable' that`);let i=e?.writable;return x1c(i,"writable","ReadableWritablePair"),function(n,a){if(!T4_(n))throw new TypeError(`${a} is not a WritableStream.`)}(i,`${t} has member 'writable' that`),{readable:r,writable:i}}Object.defineProperties(Lpi.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),bA(Lpi.prototype.close,"close"),bA(Lpi.prototype.enqueue,"enqueue"),bA(Lpi.prototype.error,"error"),typeof SE.toStringTag=="symbol"&&Object.defineProperty(Lpi.prototype,SE.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});var c4=class{constructor(t={},r={}){t===void 0?t=null:A4_(t,"First parameter");let i=Utu(r,"Second parameter"),n=function(u,l){Wpi(u,l);let d=u,s=d?.autoAllocateChunkSize,o=d?.cancel,c=d?.pull,b=d?.start,g=d?.type;return{autoAllocateChunkSize:s===void 0?void 0:q4_(s,`${l} has member 'autoAllocateChunkSize' that`),cancel:o===void 0?void 0:CnM(o,d,`${l} has member 'cancel' that`),pull:c===void 0?void 0:BnM(c,d,`${l} has member 'pull' that`),start:b===void 0?void 0:InM(b,d,`${l} has member 'start' that`),type:g===void 0?void 0:znM(g,`${l} has member 'type' that`)}}(t,"First parameter");var a;if((a=this)._state="readable",a._reader=void 0,a._storedError=void 0,a._disturbed=!1,n.type==="bytes"){if(i.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");PnM(this,n,FNa(i,0))}else{let u=Ltu(i);TnM(this,n,FNa(i,1),u)}}get locked(){if(!cYi(this))throw uYi("locked");return TLn(this)}cancel(t){return cYi(this)?TLn(this)?hg(new TypeError("Cannot cancel a stream that already has a reader")):n2_(this,t):hg(uYi("cancel"))}getReader(t){if(!cYi(this))throw uYi("getReader");return function(r,i){Wpi(r,i);let n=r?.mode;return{mode:n===void 0?void 0:xnM(n,`${i} has member 'mode' that`)}}(t,"First parameter").mode===void 0?new xpi(this):function(r){return new Npi(r)}(this)}pipeThrough(t,r={}){if(!zNa(this))throw uYi("pipeThrough");Hpi(t,1,"pipeThrough");let i=RnM(t,"First parameter"),n=f4_(r,"Second parameter");if(this.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(i.writable.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return ELn(l4_(this,i.writable,n.preventClose,n.preventAbort,n.preventCancel,n.signal)),i.readable}pipeTo(t,r={}){if(!zNa(this))return hg(uYi("pipeTo"));if(t===void 0)return hg("Parameter 1 is required in 'pipeTo'.");if(!T4_(t))return hg(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let i;try{i=f4_(r,"Second parameter")}catch(n){return hg(n)}return this.locked?hg(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):t.locked?hg(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):l4_(this,t,i.preventClose,i.preventAbort,i.preventCancel,i.signal)}tee(){if(!zNa(this))throw uYi("tee");if(this.locked)throw new TypeError("Cannot tee a stream that already has a reader");return qnM(this)}values(t){if(!zNa(this))throw uYi("values");return function(r,i){let n=r.getReader(),a=new Ntu(n,i),u=Object.create(x4_);return u._asyncIteratorImpl=a,u}(this,function(r,i){return Wpi(r,i),{preventCancel:!!r?.preventCancel}}(t,"First parameter").preventCancel)}};function cYi(e){return!!MJ(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof c4}function TLn(e){return e._reader!==void 0}function n2_(e,t){if(e._disturbed=!0,e._state==="closed")return YA(void 0);if(e._state==="errored")return hg(e._storedError);LNa(e);let r=e._reader;if(r!==void 0&&SLn(r)){let i=r._readIntoRequests;r._readIntoRequests=new loe,i.forEach(n=>{n._closeSteps(void 0)})}return RHt(e._readableStreamController[W1c](t),O4_)}function LNa(e){e._state="closed";let t=e._reader;if(t!==void 0&&(M4_(t),sYi(t))){let r=t._readRequests;t._readRequests=new loe,r.forEach(i=>{i._closeSteps()})}}function a2_(e,t){e._state="errored",e._storedError=t;let r=e._reader;r!==void 0&&(G1c(r,t),sYi(r)?z4_(r,t):J4_(r,t))}function uYi(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function o2_(e,t){Wpi(e,t);let r=e?.highWaterMark;return x1c(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Q1c(r)}}Object.defineProperties(c4.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),bA(c4.prototype.cancel,"cancel"),bA(c4.prototype.getReader,"getReader"),bA(c4.prototype.pipeThrough,"pipeThrough"),bA(c4.prototype.pipeTo,"pipeTo"),bA(c4.prototype.tee,"tee"),bA(c4.prototype.values,"values"),typeof SE.toStringTag=="symbol"&&Object.defineProperty(c4.prototype,SE.toStringTag,{value:"ReadableStream",configurable:!0}),typeof SE.asyncIterator=="symbol"&&Object.defineProperty(c4.prototype,SE.asyncIterator,{value:c4.prototype.values,writable:!0,configurable:!0});var u2_=e=>e.byteLength;bA(u2_,"size");var UNa=class{constructor(t){Hpi(t,1,"ByteLengthQueuingStrategy"),t=o2_(t,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=t.highWaterMark}get highWaterMark(){if(!p4_(this))throw d4_("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!p4_(this))throw d4_("size");return u2_}};function d4_(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function p4_(e){return!!MJ(e)&&!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof UNa}Object.defineProperties(UNa.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof SE.toStringTag=="symbol"&&Object.defineProperty(UNa.prototype,SE.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});var s2_=()=>1;bA(s2_,"size");var VNa=class{constructor(t){Hpi(t,1,"CountQueuingStrategy"),t=o2_(t,"First parameter"),this._countQueuingStrategyHighWaterMark=t.highWaterMark}get highWaterMark(){if(!h4_(this))throw _4_("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!h4_(this))throw _4_("size");return s2_}};function _4_(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function h4_(e){return!!MJ(e)&&!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof VNa}function NnM(e,t,r){return NHt(e,r),i=>fYi(e,t,[i])}function FnM(e,t,r){return NHt(e,r),i=>Qtu(e,t,[i])}function LnM(e,t,r){return NHt(e,r),(i,n)=>fYi(e,t,[i,n])}Object.defineProperties(VNa.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof SE.toStringTag=="symbol"&&Object.defineProperty(VNa.prototype,SE.toStringTag,{value:"CountQueuingStrategy",configurable:!0});var WNa=class{constructor(t={},r={},i={}){t===void 0&&(t=null);let n=Utu(r,"Second parameter"),a=Utu(i,"Third parameter"),u=function(b,g){Wpi(b,g);let O=b?.flush,m=b?.readableType,P=b?.start,E=b?.transform,q=b?.writableType;return{flush:O===void 0?void 0:NnM(O,b,`${g} has member 'flush' that`),readableType:m,start:P===void 0?void 0:FnM(P,b,`${g} has member 'start' that`),transform:E===void 0?void 0:LnM(E,b,`${g} has member 'transform' that`),writableType:q}}(t,"First parameter");if(u.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(u.writableType!==void 0)throw new RangeError("Invalid writableType specified");let l=FNa(a,0),d=Ltu(a),s=FNa(n,1),o=Ltu(n),c;(function(b,g,O,m,P,E){function q(){return g}function M(I){return function(L,V){let X=L._transformStreamController;return L._backpressure?RHt(L._backpressureChangePromise,()=>{if((tnr(L._writable)?L._writable._state:L._writableState)==="erroring")throw tnr(L._writable)?L._writable._storedError:L._writableStoredError;return v4_(X,V)}):v4_(X,V)}(b,I)}function D(I){return function(L,V){return Wtu(L,V),YA(void 0)}(b,I)}function T(){return function(I){let L=I._transformStreamController,V=L._flushAlgorithm();return c2_(L),RHt(V,()=>{if(I._readableState==="errored")throw I._readableStoredError;$tu(I)&&f2_(I)},X=>{throw Wtu(I,X),I._readableStoredError})}(b)}function x(){return function(I){return Htu(I,!1),I._backpressureChangePromise}(b)}function $(I){return Xtu(b,I),YA(void 0)}b._writableState="writable",b._writableStoredError=void 0,b._writableHasInFlightOperation=!1,b._writableStarted=!1,b._writable=function(I,L,V,X,K,k,fe){return new Fpi({start(be){I._writableController=be;try{let _e=be.signal;_e!==void 0&&_e.addEventListener("abort",()=>{I._writableState==="writable"&&(I._writableState="erroring",_e.reason&&(I._writableStoredError=_e.reason))})}catch{}return RHt(L(),()=>(I._writableStarted=!0,g4_(I),null),_e=>{throw I._writableStarted=!0,I1c(I,_e),_e})},write:be=>(function(_e){_e._writableHasInFlightOperation=!0}(I),RHt(V(be),()=>(function(_e){_e._writableHasInFlightOperation=!1}(I),g4_(I),null),_e=>{throw function(we,Qe){we._writableHasInFlightOperation=!1,I1c(we,Qe)}(I,_e),_e})),close:()=>(function(be){be._writableHasInFlightOperation=!0}(I),RHt(X(),()=>(function(be){be._writableHasInFlightOperation=!1,be._writableState==="erroring"&&(be._writableStoredError=void 0),be._writableState="closed"}(I),null),be=>{throw function(_e,we){_e._writableHasInFlightOperation=!1,_e._writableState,I1c(_e,we)}(I,be),be})),abort:be=>(I._writableState="errored",I._writableStoredError=be,K(be))},{highWaterMark:k,size:fe})}(b,q,M,T,D,O,m),b._readableState="readable",b._readableStoredError=void 0,b._readableCloseRequested=!1,b._readablePulling=!1,b._readable=function(I,L,V,X,K,k){return new c4({start:fe=>(I._readableController=fe,L().catch(be=>{Gtu(I,be)})),pull:()=>(I._readablePulling=!0,V().catch(fe=>{Gtu(I,fe)})),cancel:fe=>(I._readableState="closed",X(fe))},{highWaterMark:K,size:k})}(b,q,x,$,P,E),b._backpressure=void 0,b._backpressureChangePromise=void 0,b._backpressureChangePromise_resolve=void 0,Htu(b,!0),b._transformStreamController=void 0})(this,Ek(b=>{c=b}),s,o,l,d),function(b,g){let O=Object.create(Upi.prototype),m,P;m=g.transform!==void 0?E=>g.transform(E,O):E=>{try{return l2_(O,E),YA(void 0)}catch(q){return hg(q)}},P=g.flush!==void 0?()=>g.flush(O):()=>YA(void 0),function(E,q,M,D){q._controlledTransformStream=E,E._transformStreamController=q,q._transformAlgorithm=M,q._flushAlgorithm=D}(b,O,m,P)}(this,u),u.start!==void 0?c(u.start(this._transformStreamController)):c(void 0)}get readable(){if(!y4_(this))throw b4_("readable");return this._readable}get writable(){if(!y4_(this))throw b4_("writable");return this._writable}};function y4_(e){return!!MJ(e)&&!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof WNa}function Wtu(e,t){Gtu(e,t),Xtu(e,t)}function Xtu(e,t){c2_(e._transformStreamController),function(r,i){r._writableController.error(i),r._writableState==="writable"&&p2_(r,i)}(e,t),e._backpressure&&Htu(e,!1)}function Htu(e,t){e._backpressureChangePromise!==void 0&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=Ek(r=>{e._backpressureChangePromise_resolve=r}),e._backpressure=t}Object.defineProperties(WNa.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof SE.toStringTag=="symbol"&&Object.defineProperty(WNa.prototype,SE.toStringTag,{value:"TransformStream",configurable:!0});var Upi=class{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Ttu(this))throw Ctu("desiredSize");return d2_(this._controlledTransformStream)}enqueue(t){if(!Ttu(this))throw Ctu("enqueue");l2_(this,t)}error(t){if(!Ttu(this))throw Ctu("error");var r;r=t,Wtu(this._controlledTransformStream,r)}terminate(){if(!Ttu(this))throw Ctu("terminate");(function(t){let r=t._controlledTransformStream;$tu(r)&&f2_(r);let i=new TypeError("TransformStream terminated");Xtu(r,i)})(this)}};function Ttu(e){return!!MJ(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof Upi}function c2_(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function l2_(e,t){let r=e._controlledTransformStream;if(!$tu(r))throw new TypeError("Readable side is not in a state that permits enqueue");try{(function(n,a){n._readablePulling=!1;try{n._readableController.enqueue(a)}catch(u){throw Gtu(n,u),u}})(r,t)}catch(n){throw Xtu(r,n),r._readableStoredError}(function(n){return!function(a){return $tu(a)?!!(a._readablePulling||d2_(a)>0):!1}(n)})(r)!==r._backpressure&&Htu(r,!0)}function v4_(e,t){return RHt(e._transformAlgorithm(t),void 0,r=>{throw Wtu(e._controlledTransformStream,r),r})}function Ctu(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function b4_(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}function $tu(e){return!e._readableCloseRequested&&e._readableState==="readable"}function f2_(e){e._readableState="closed",e._readableCloseRequested=!0,e._readableController.close()}function Gtu(e,t){e._readableState==="readable"&&(e._readableState="errored",e._readableStoredError=t),e._readableController.error(t)}function d2_(e){return e._readableController.desiredSize}function I1c(e,t){e._writableState!=="writable"?nSc(e):p2_(e,t)}function p2_(e,t){e._writableState="erroring",e._writableStoredError=t,!function(r){return r._writableHasInFlightOperation}(e)&&e._writableStarted&&nSc(e)}function nSc(e){e._writableState="errored"}function g4_(e){e._writableState==="erroring"&&nSc(e)}Object.defineProperties(Upi.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),bA(Upi.prototype.enqueue,"enqueue"),bA(Upi.prototype.error,"error"),bA(Upi.prototype.terminate,"terminate"),typeof SE.toStringTag=="symbol"&&Object.defineProperty(Upi.prototype,SE.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});var V3=e=>typeof e=="function";var _2_=65536;async function*UnM(e){let t=e.byteOffset+e.byteLength,r=e.byteOffset;for(;r!==t;){let i=Math.min(t-r,_2_),n=e.buffer.slice(r,r+i);r+=n.byteLength,yield new Uint8Array(n)}}async function*VnM(e){let t=0;for(;t!==e.size;){let i=await e.slice(t,Math.min(e.size,t+_2_)).arrayBuffer();t+=i.byteLength,yield new Uint8Array(i)}}async function*Ztu(e,t=!1){for(let r of e)ArrayBuffer.isView(r)?t?yield*UnM(r):yield r:V3(r.stream)?yield*r.stream():yield*VnM(r)}function*h2_(e,t,r=0,i){i??(i=t);let n=r<0?Math.max(t+r,0):Math.min(r,t),a=i<0?Math.max(t+i,0):Math.min(i,t),u=Math.max(a-n,0),l=0;for(let d of e){if(l>=u)break;let s=ArrayBuffer.isView(d)?d.byteLength:d.size;if(n&&s<=n)n-=s,a-=s;else{let o;ArrayBuffer.isView(d)?(o=d.subarray(n,Math.min(s,a)),l+=o.byteLength):(o=d.slice(n,Math.min(s,a)),l+=o.size),a-=s,n=0,yield o}}}var fqi=function(e,t,r,i){if(r==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?i:r==="a"?i.call(e):i?i.value:t.get(e)},y2_=function(e,t,r,i,n){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?n.call(e,r):n?n.value=r:t.set(e,r),r},dYi,ktu,HNa,rnr=class e{constructor(t=[],r={}){if(dYi.set(this,[]),ktu.set(this,""),HNa.set(this,0),r??(r={}),typeof t!="object"||t===null)throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");if(!V3(t[Symbol.iterator]))throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");if(typeof r!="object"&&!V3(r))throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");let i=new TextEncoder;for(let a of t){let u;ArrayBuffer.isView(a)?u=new Uint8Array(a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength)):a instanceof ArrayBuffer?u=new Uint8Array(a.slice(0)):a instanceof e?u=a:u=i.encode(String(a)),y2_(this,HNa,fqi(this,HNa,"f")+(ArrayBuffer.isView(u)?u.byteLength:u.size),"f"),fqi(this,dYi,"f").push(u)}let n=r.type===void 0?"":String(r.type);y2_(this,ktu,/^[\x20-\x7E]*$/.test(n)?n:"","f")}static[(dYi=new WeakMap,ktu=new WeakMap,HNa=new WeakMap,Symbol.hasInstance)](t){return!!(t&&typeof t=="object"&&V3(t.constructor)&&(V3(t.stream)||V3(t.arrayBuffer))&&/^(Blob|File)$/.test(t[Symbol.toStringTag]))}get type(){return fqi(this,ktu,"f")}get size(){return fqi(this,HNa,"f")}slice(t,r,i){return new e(h2_(fqi(this,dYi,"f"),this.size,t,r),{type:i})}async text(){let t=new TextDecoder,r="";for await(let i of Ztu(fqi(this,dYi,"f")))r+=t.decode(i,{stream:!0});return r+=t.decode(),r}async arrayBuffer(){let t=new Uint8Array(this.size),r=0;for await(let i of Ztu(fqi(this,dYi,"f")))t.set(i,r),r+=i.length;return t.buffer}stream(){let t=Ztu(fqi(this,dYi,"f"),!0);return new c4({async pull(r){let{value:i,done:n}=await t.next();if(n)return queueMicrotask(()=>r.close());r.enqueue(i)},async cancel(){await t.return()}})}get[Symbol.toStringTag](){return"Blob"}};Object.defineProperties(rnr.prototype,{type:{enumerable:!0},size:{enumerable:!0},slice:{enumerable:!0},stream:{enumerable:!0},text:{enumerable:!0},arrayBuffer:{enumerable:!0}});var v2_=function(e,t,r,i,n){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?n.call(e,r):n?n.value=r:t.set(e,r),r},b2_=function(e,t,r,i){if(r==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?i:r==="a"?i.call(e):i?i.value:t.get(e)},eru,tru,pYi=class extends rnr{constructor(t,r,i={}){if(super(t,i),eru.set(this,void 0),tru.set(this,0),arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);v2_(this,eru,String(r),"f");let n=i.lastModified===void 0?Date.now():Number(i.lastModified);Number.isNaN(n)||v2_(this,tru,n,"f")}static[(eru=new WeakMap,tru=new WeakMap,Symbol.hasInstance)](t){return t instanceof rnr&&t[Symbol.toStringTag]==="File"&&typeof t.name=="string"}get name(){return b2_(this,eru,"f")}get lastModified(){return b2_(this,tru,"f")}get webkitRelativePath(){return""}get[Symbol.toStringTag](){return"File"}};var g2_=e=>e instanceof pYi;var O2_=e=>e instanceof rnr;var m2_=require("util"),P2_=(0,m2_.deprecate)(()=>{},'Constructor "entries" argument is not spec-compliant and will be removed in next major release.');var inr=function(e,t,r,i){if(r==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?i:r==="a"?i.call(e):i?i.value:t.get(e)},rru,nnr,aSc,iru=class{constructor(t){rru.add(this),nnr.set(this,new Map),t&&(P2_(),t.forEach(({name:r,value:i,fileName:n})=>this.append(r,i,n)))}static[(nnr=new WeakMap,rru=new WeakSet,Symbol.hasInstance)](t){return!!(t&&V3(t.constructor)&&t[Symbol.toStringTag]==="FormData"&&V3(t.append)&&V3(t.set)&&V3(t.get)&&V3(t.getAll)&&V3(t.has)&&V3(t.delete)&&V3(t.entries)&&V3(t.values)&&V3(t.keys)&&V3(t[Symbol.iterator])&&V3(t.forEach))}append(t,r,i){inr(this,rru,"m",aSc).call(this,{name:t,fileName:i,append:!0,rawValue:r,argsLength:arguments.length})}set(t,r,i){inr(this,rru,"m",aSc).call(this,{name:t,fileName:i,append:!1,rawValue:r,argsLength:arguments.length})}get(t){let r=inr(this,nnr,"f").get(String(t));return r?r[0]:null}getAll(t){let r=inr(this,nnr,"f").get(String(t));return r?r.slice():[]}has(t){return inr(this,nnr,"f").has(String(t))}delete(t){inr(this,nnr,"f").delete(String(t))}*keys(){for(let t of inr(this,nnr,"f").keys())yield t}*entries(){for(let t of this.keys()){let r=this.getAll(t);for(let i of r)yield[t,i]}}*values(){for(let[,t]of this)yield t}[(aSc=function({name:r,rawValue:i,append:n,fileName:a,argsLength:u}){let l=n?"append":"set";if(u<2)throw new TypeError(`Failed to execute '${l}' on 'FormData': 2 arguments required, but only ${u} present.`);r=String(r);let d;if(g2_(i))d=a===void 0?i:new pYi([i],a,{type:i.type,lastModified:i.lastModified});else if(O2_(i))d=new pYi([i],a===void 0?"blob":a,{type:i.type});else{if(a)throw new TypeError(`Failed to execute '${l}' on 'FormData': parameter 2 is not of type 'Blob'.`);d=String(i)}let s=inr(this,nnr,"f").get(r);if(!s)return void inr(this,nnr,"f").set(r,[d]);if(!n)return void inr(this,nnr,"f").set(r,[d]);s.push(d)},Symbol.iterator)](){return this.entries()}forEach(t,r){for(let[i,n]of this)t.call(r,n,i,this)}get[Symbol.toStringTag](){return"FormData"}[j2_.inspect.custom](){return this[Symbol.toStringTag]}};var $Na=`\r
@@ -2020,8 +2019,7 @@ ${b}
2020
2019
  \`\`\``,b=b.split(`
2021
2020
  `).map(q=>s+q).join(`
2022
2021
  `),b=b+`
2023
- `,u=u.replace(d,b),i.logger.error(`Generated markdown:
2024
- ${u}`)}catch{i.logger.warn(`Failed to read markdown file "${o}" referenced in ${r}`);break}}return u}var JK_=require("fs/promises"),KK_=ci(Trr(),1);async function lhM(e){let{content:t}=(0,KK_.default)(await(0,JK_.readFile)(e));return t}async function wqc({markdown:e,absolutePathToFernFolder:t,absolutePathToMarkdownFile:r,context:i,markdownLoader:n=lhM}){if(!e.includes("<Markdown"))return e;let a=/([ \t]*)<Markdown\s+src={?['"]([^'"]+.mdx?)['"](?! \+)}?\s*\/>/g,u=e,l;for(;(l=a.exec(e))!=null;){let d=l[0],s=l[1],o=l[2];if(d==null||o==null)throw new Error(`Failed to parse regex "${l}" in ${r}`);let c=pb(o.startsWith("/")?t:Ud(r),Qa.of(o.replace(/^\//,"")));try{let b=await n(c);b=b.split(`
2022
+ `,u=u.replace(d,b)}catch{i.logger.warn(`Failed to read markdown file "${o}" referenced in ${r}`);break}}return u}var JK_=require("fs/promises"),KK_=ci(Trr(),1);async function lhM(e){let{content:t}=(0,KK_.default)(await(0,JK_.readFile)(e));return t}async function wqc({markdown:e,absolutePathToFernFolder:t,absolutePathToMarkdownFile:r,context:i,markdownLoader:n=lhM}){if(!e.includes("<Markdown"))return e;let a=/([ \t]*)<Markdown\s+src={?['"]([^'"]+.mdx?)['"](?! \+)}?\s*\/>/g,u=e,l;for(;(l=a.exec(e))!=null;){let d=l[0],s=l[1],o=l[2];if(d==null||o==null)throw new Error(`Failed to parse regex "${l}" in ${r}`);let c=pb(o.startsWith("/")?t:Ud(r),Qa.of(o.replace(/^\//,"")));try{let b=await n(c);b=b.split(`
2025
2023
  `).map(g=>s+g).join(`
2026
2024
  `),u=u.replace(d,b)}catch{i.logger.warn(`Failed to read markdown file "${o}" referenced in ${r}`);break}}return u}async function uau({domain:e,project:t,context:r,previousDocsDefinition:i,editedAbsoluteFilepaths:n}){let a=t.docsWorkspaces,u=t.apiWorkspaces;if(a==null)throw new Error("No docs workspace found in project");if(n!=null&&i!=null){let m=n.every(P=>P.endsWith(".mdx")||P.endsWith(".md"));for(let P of n){let E=xq(a.absoluteFilePath,P),q=(await(0,YK_.readFile)(P)).toString(),M=await wqc({markdown:q,absolutePathToFernFolder:a.absoluteFilePath,absolutePathToMarkdownFile:P,context:r}),D=i.pages[XA.PageId(E)];if(D==null)continue;let T=new Map(Object.entries(i.filesV2??{}).map(([$,I])=>{let L="/"+I.url.replace("/_local/","");return[hl.of(L),$]})),x=Pqc(M,T,{},{absolutePathToFernFolder:a.absoluteFilePath,absolutePathToMarkdownFile:P},r);x=await jqc({markdown:x,absolutePathToFernFolder:a.absoluteFilePath,absolutePathToMarkdownFile:P,context:r}),i.pages[XA.PageId(E)]={markdown:x,editThisPageUrl:D.editThisPageUrl}}if(m)return i}let l=await bH(t),d=new Sqc(r),s=new Dqc(r),o={},b=await new KHt(e,a,l,u,r,void 0,async m=>m.map(P=>{let E=zae();return o[E]={type:"url",url:So.Url(`/_local${f4s(P.absoluteFilePath)}`)},{absoluteFilePath:P.absoluteFilePath,relativeFilePath:P.relativeFilePath,fileId:E}}),async m=>d.addReferencedAPI(m),async m=>s.addReferencedAPI(m)).resolve(),g=aEc({writeShape:b,files:{}}),O=uEc({dbShape:g.config});return{apis:d.getAPIsForDefinition(),apisV2:s.getAPIsForDefinition(),config:O,files:{},filesV2:o,pages:g.pages,search:{type:"legacyMultiAlgoliaIndex",algoliaIndex:void 0},algoliaSearchIndex:void 0,jsFiles:g.jsFiles,id:void 0}}var Sqc=class{context;apis={};constructor(t){this.context=t}addReferencedAPI({ir:t,snippetsConfig:r,playgroundConfig:i}){try{let n=zae(),a=KNa(Mk({ir:t,snippetsConfig:r,playgroundConfig:i}),XA.ApiDefinitionId(n),new bYi({snippetsConfigWithSdkId:{},snippetsBySdkId:{},snippetTemplatesByEndpoint:{},snippetTemplatesByEndpointId:{},snippetsBySdkIdAndEndpointId:{}})),u=ZNa(a);return this.apis[n]=u,n}catch(n){let a=n;throw this.context.logger.debug(`Failed to read referenced API: ${a?.message} ${a?.stack}`),this.context.logger.error("An error occurred while trying to read an API definition. Please reach out to support."),a.stack!=null&&this.context.logger.error(a?.stack),n}}getAPIsForDefinition(){return this.apis}},Dqc=class{context;apis={};constructor(t){this.context=t}addReferencedAPI({api:t,snippetsConfig:r}){try{return t.snippetsConfiguration=r,this.apis[t.id]=t,t.id}catch(i){let n=i;throw this.context.logger.debug(`Failed to read referenced API: ${n?.message} ${n?.stack}`),this.context.logger.error("An error occurred while trying to read an API definition. Please reach out to support."),n.stack!=null&&this.context.logger.error(n?.stack),i}}getAPIsForDefinition(){return this.apis}};var fhM={pages:{},apis:{},apisV2:{},files:{},filesV2:{},config:{aiChatConfig:void 0,hideNavLinks:void 0,navigation:void 0,root:void 0,title:void 0,defaultLanguage:void 0,announcement:void 0,navbarLinks:void 0,footerLinks:void 0,logoHeight:void 0,logoHref:void 0,favicon:void 0,metadata:void 0,redirects:void 0,colorsV3:void 0,layout:void 0,typographyV2:void 0,analyticsConfig:void 0,integrations:void 0,css:void 0,js:void 0},search:{type:"legacyMultiAlgoliaIndex",algoliaIndex:void 0},algoliaSearchIndex:void 0,jsFiles:void 0,id:void 0};async function Mqc({initialProject:e,reloadProject:t,validateProject:r,context:i,port:n,bundlePath:a}){if(a!=null)i.logger.info(`Using bundle from path: ${a}`);else try{let $="https://prod-local-preview-bundle2.s3.amazonaws.com/";if($==null)throw new Error("Failed to connect to the docs preview server. Please contact support@buildwithfern.com");await i3a({bucketUrl:$,logger:i.logger,preferCached:!0,tryTar:!1})}catch($){let I=xYi({});if($ instanceof Error&&i.logger.debug(`Failed to download latest docs bundle: ${$.message}`),await Sf(I))i.logger.warn("Falling back to cached bundle...");else{i.logger.warn("Please reach out to support@buildwithfern.com.");return}}let u=Ud(e.config._absolutePath),l=(0,Eqc.default)(),d=ZK_.default.createServer(l),s=new PNa.default({server:d}),o=new Set;function c($){for(let I of o)I.send(JSON.stringify($))}s.on("connection",function(I){o.add(I),I.on("close",function(){o.delete(I)})}),l.use((0,XK_.default)());let b=new URL(Ak(e.docsWorkspaces?.config.instances[0]?.url??`http://localhost:${n}`)),g=e,O,m=null,P=!1,E=1e3,q=async $=>{i.logger.info("Reloading docs...");let I=Date.now();try{g=await t(),i.logger.info("Validating docs..."),await r(g);let L=await uau({domain:`${b.host}${b.pathname}`,project:g,context:i,previousDocsDefinition:O,editedAbsoluteFilepaths:$});return i.logger.info(`Reload completed in ${Date.now()-I}ms`),L}catch(L){return O==null?i.logger.error("Failed to read docs configuration. Rendering blank page."):i.logger.error("Failed to read docs configuration. Rendering last successful configuration."),L instanceof Error&&(i.logger.error(L.message),L instanceof Error&&L.stack&&i.logger.debug(`Stack Trace:
2027
2025
  ${L.stack}`)),O}};O=await q();let M=g.apiWorkspaces.flatMap($=>$.getAbsoluteFilePaths()),D=a?hl.of(sau.default.resolve(a)):xYi({}),T=new itu([u,...M],{recursive:!0,ignoreInitial:!0,debounce:100,renameDetection:!0}),x=[];T.on("all",async($,I,L)=>{i.logger.info(Gs.dim(`[${$}] ${I}`)),!P&&(x.push(hl.of(I)),m!=null&&clearTimeout(m),m=setTimeout(()=>{(async()=>{P=!0,c({version:1,type:"startReload"});let V=await q(x);V!=null&&(O=V),x.length=0,c({version:1,type:"finishReload"}),P=!1})()},E))}),l.post("/v2/registry/docs/load-with-url",async($,I)=>{try{let L=O??fhM,V={baseUrl:{domain:b.host,basePath:b.pathname},definition:L,lightModeEnabled:L.config.colorsV3?.type!=="dark",orgId:So.OrgId(e.config.organization)};I.send(V)}catch(L){i.logger.error("Stack trace:",L.stack??""),i.logger.error("Error loading docs",L.message),I.status(500).send()}}),l.get(/^\/_local\/(.*)/,($,I)=>I.sendFile(`/${$.params[0]}`)),l.get("/",($,I,L)=>$.headers.upgrade==="websocket"?s.handleUpgrade($,$.socket,Buffer.alloc(0),V=>{s.emit("connection",V,$)}):L()),l.use("/_next",Eqc.default.static(sau.default.join(D,"/_next"))),l.use("*",async($,I)=>I.sendFile(sau.default.join(D,"/[[...slug]].html"))),l.listen(n),i.logger.info(`Running server on http://localhost:${n}`),await new Promise(()=>{})}var kK_=ci(Djc(),1),eY_=ci(Xeu(),1),tY_=ci(require("http"),1),rY_=ci(require("path"),1);var dhM={pages:{},apis:{},apisV2:{},files:{},filesV2:{},config:{aiChatConfig:void 0,hideNavLinks:void 0,navigation:void 0,root:void 0,title:void 0,defaultLanguage:void 0,announcement:void 0,navbarLinks:void 0,footerLinks:void 0,logoHeight:void 0,logoHref:void 0,favicon:void 0,metadata:void 0,redirects:void 0,colorsV3:void 0,layout:void 0,typographyV2:void 0,analyticsConfig:void 0,integrations:void 0,css:void 0,js:void 0},search:{type:"legacyMultiAlgoliaIndex",algoliaIndex:void 0},algoliaSearchIndex:void 0,jsFiles:void 0,id:void 0};async function Aqc({initialProject:e,reloadProject:t,validateProject:r,context:i,port:n,bundlePath:a,backendPort:u}){if(a!=null)i.logger.info(`Using bundle from path: ${a}`);else try{let fe="https://prod-local-preview-bundle4.s3.amazonaws.com/";if(fe==null)throw new Error("Failed to connect to the docs preview server. Please contact support@buildwithfern.com");await i3a({bucketUrl:fe,logger:i.logger,preferCached:!0,app:!0,tryTar:!0})}catch(fe){fe instanceof Error&&(i.logger.debug(`Failed to download latest docs bundle: ${fe.message}`),i.logger.error("Failed to unzip .tar.gz bundle. Please report to support@buildwithfern.com")),i.logger.debug("Falling back to .zip bundle");try{let be="https://prod-local-preview-bundle3.s3.amazonaws.com/";if(be==null)throw new Error("Failed to connect to the docs preview server. Please contact support@buildwithfern.com");await i3a({bucketUrl:be,logger:i.logger,preferCached:!0,app:!0,tryTar:!1})}catch{if(await Sf(xYi({app:!0})))i.logger.warn("Falling back to cached bundle...");else{i.logger.warn("Please reach out to support@buildwithfern.com.");return}}}let l=a||xYi({app:!0}),d=rY_.default.join(l,"standalone/packages/fern-docs/bundle/server.js"),s={...process.env,PORT:n.toString(),HOSTNAME:"0.0.0.0",NEXT_PUBLIC_FDR_ORIGIN_PORT:u.toString(),NEXT_PUBLIC_FDR_ORIGIN:`http://localhost:${u}`,NEXT_PUBLIC_DOCS_DOMAIN:e.docsWorkspaces?.config.instances[0]?.url,NEXT_PUBLIC_IS_LOCAL:"1",NEXT_DISABLE_CACHE:"1",NODE_ENV:"production",NODE_PATH:l,NODE_OPTIONS:"--max-old-space-size=2048"},o=KXo(i.logger,"node",[d],{env:s,doNotPipeOutput:!0});o.stdout?.on("data",fe=>{i.logger.debug(`[Next.js] ${fe.toString()}`)}),o.stderr?.on("data",fe=>{i.logger.debug(`[Next.js] ${fe.toString()}`)}),i.logger.debug(`Next.js standalone server started with PID: ${o.pid}`),o.on("error",fe=>{i.logger.debug(`Server process error: ${fe.message}`)}),o.on("exit",(fe,be)=>{fe?i.logger.debug(`Server process exited with code: ${fe}`):be?i.logger.debug(`Server process killed with signal: ${be}`):i.logger.debug("Server process exited")});let c=()=>{if(!o.killed){i.logger.debug(`Killing server process with PID: ${o.pid}`);try{o.kill(),setTimeout(()=>{if(!o.killed){i.logger.debug(`Force killing server process with PID: ${o.pid}`);try{o.kill("SIGKILL")}catch(fe){i.logger.error(`Failed to force kill server process: ${fe}`)}}},2e3)}catch(fe){i.logger.error(`Failed to kill server process: ${fe}`)}}},b=["SIGTERM","SIGINT"],g=["SIGHUP"];for(let fe of b)process.on(fe,()=>{i.logger.debug("Shutting down server..."),c()});for(let fe of g)process.on(fe,()=>{i.logger.debug("Server failed, shutting down process..."),c()});process.on("exit",c),process.on("uncaughtException",fe=>{i.logger.debug(`Uncaught exception: ${fe}`),c(),process.exit(1)}),process.on("unhandledRejection",fe=>{i.logger.debug(`Unhandled rejection: ${fe}`),c(),process.exit(1)}),process.on("beforeExit",c),await new Promise(fe=>setTimeout(fe,3e3)),i.logger.debug(`Next.js server should now be running on http://localhost:${n}`);let O=Ud(e.config._absolutePath),m=(0,eY_.default)(),P=tY_.default.createServer(m),E=new PNa.default({server:P}),q=new Set;function M(fe){for(let be of q)be.send(JSON.stringify(fe))}E.on("connection",function(be){q.add(be);let _e=setInterval(()=>{be.readyState===xwc.default.OPEN&&(be.send(JSON.stringify({type:"ping"})),i.logger.debug("Server: Sent ping to keep connection alive"))},6e4);be.on("close",function(){clearInterval(_e),q.delete(be)})}),m.use((0,kK_.default)());let D=new URL(Ak(e.docsWorkspaces?.config.instances[0]?.url??`http://localhost:${n}`)),T=e,x,$=null,I=!1,L=1e3,V=async fe=>{i.logger.info("Reloading docs...");let be=Date.now();try{T=await t(),i.logger.info("Validating docs..."),await r(T);let _e=await uau({domain:`${D.host}${D.pathname}`,project:T,context:i,previousDocsDefinition:x,editedAbsoluteFilepaths:fe});return i.logger.info(`Reload completed in ${Date.now()-be}ms`),_e}catch(_e){return x==null?i.logger.error("Failed to read docs configuration. Rendering blank page."):i.logger.error("Failed to read docs configuration. Rendering last successful configuration."),_e instanceof Error&&(i.logger.error(_e.message),_e instanceof Error&&_e.stack&&i.logger.debug(`Stack Trace: