fern-api 0.56.3 → 0.56.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.cjs +4 -4
- package/package.json +1 -1
package/cli.cjs
CHANGED
|
@@ -1691,7 +1691,7 @@ ${c.indent}`:""}${_8f(o)}:${l.indent?" ":""}`;return u=!1,s=!0,l.objectItem=void
|
|
|
1691
1691
|
`}),r.replaceAll(/\n$/g,"")}function UOS(e){return e?Q_.green(Q3.radioOn):Q3.radioOff}var avo=vi(U1e(),1);function XYd(e,t){return e=String(e),t=typeof t=="string"?t:"*",e.length===0?"":Array.from({length:e.length+1}).join(t)}var Bna=class extends Z6{_run(t){this.done=t;let r=qU(this.rl),i=r.line.pipe((0,avo.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,avo.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=`
|
|
1692
1692
|
`+Q_.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?Q_.cyan(XYd(t,this.opt.mask)):Q_.italic.dim("[hidden]"):this.opt.mask?XYd(t,this.opt.mask):Q_.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 PZd=vi(HDs(),1),jZd=vi(U1e(),1);var Wna=class extends Z6{_run(t){this.done=t,this.editorResult=new jZd.Subject;let r=qU(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"?Q_.dim("Received"):Q_.dim("Press <enter> to launch your preferred editor."),t&&(r=Q_.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),(0,PZd.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 TZd=vi(DZd(),1);var AZd=vi(require("readline"),1),qZd=vi(MZd(),1),BCi=class{constructor(t){this.rl||=AZd.default.createInterface(TmS(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 TmS(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 qZd.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var Hna=class extends BCi{constructor(t={}){super(t),this.log=(0,TZd.default)(this.writeLog.bind(this)),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return Sna(this.rl,this.bottomBar.split(`
|
|
1693
1693
|
`).length),this}updateBottomBar(t){return Sna(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+`
|
|
1694
|
-
`}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&&tvo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var UZd=vi(xZd(),1),VZd=vi(Z1s(),1),WZd=vi(FZd(),1),qA=vi(U1e(),1),HZd=vi(xia(),1);var Svo=vi(U1e(),1),LZd=vi(xia(),1),Dvo=function(e,t,r){return typeof e[t]!="function"?(0,Svo.of)(e):(0,Svo.from)((0,LZd.default)(e[t])(r).then(i=>(e[t]=i,e)))};var $na={isPlainObject:UZd.default,set:WZd.default,get:VZd.default},zbn=class extends BCi{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=$na.isPlainObject(r)?{...r}:{},$na.isPlainObject(t)&&(t=Object.values(t).every(n=>$na.isPlainObject(n)&&n.name===void 0)?Object.entries(t).map(([n,a])=>({name:n,...a})):[t]);let i=Array.isArray(t)?(0,qA.from)(t):t;return this.process=i.pipe((0,qA.concatMap)(this.processQuestion.bind(this)),(0,qA.publish)()),this.process.connect(),this.process.pipe((0,qA.reduce)((n,a)=>($na.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,qA.defer)(()=>(0,qA.of)(t).pipe((0,qA.concatMap)(this.setDefaultType.bind(this)),(0,qA.concatMap)(this.filterIfRunnable.bind(this)),(0,qA.concatMap)(()=>Dvo(t,"message",this.answers)),(0,qA.concatMap)(()=>Dvo(t,"default",this.answers)),(0,qA.concatMap)(()=>Dvo(t,"choices",this.answers)),(0,qA.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,qA.defer)(()=>(0,qA.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,qA.defer)(()=>(0,qA.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&$na.get(this.answers,t.name)!==void 0)return(0,qA.empty)();if(t.when===!1)return(0,qA.empty)();if(typeof t.when!="function")return(0,qA.of)(t);let{answers:r}=this;return(0,qA.defer)(()=>(0,qA.from)((0,HZd.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,qA.filter)(i=>i!=null)))}};function $Zd(e){let t=function(r,i){let n;try{n=new zbn(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",Ena),this.registerPrompt("input",SCi),this.registerPrompt("number",Mna),this.registerPrompt("confirm",Ana),this.registerPrompt("rawlist",qna),this.registerPrompt("expand",Tna),this.registerPrompt("checkbox",Cna),this.registerPrompt("password",Bna),this.registerPrompt("editor",Wna)},t.restoreDefaultPrompts(),t}var QDs=$Zd();function KmS(e,t){QDs.registerPrompt(e,t)}function YmS(){QDs.restoreDefaultPrompts()}var XmS={prompt:QDs,ui:{BottomBar:Hna,Prompt:zbn},createPromptModule:$Zd,registerPrompt:KmS,restoreDefaultPrompts:YmS,Separator:Tre},Evo=XmS;var tep=vi(GZd()),mwS="4.2.1",n8t;(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"})(n8t||(n8t={}));function PwS(e,t){if(!e)throw new Error(t)}function jwS(e){return e?.replace(/\/+$/,"")}async function wwS(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 SwS(){return new Date().getTime()}function Qkd(){return new Date().toISOString()}function rep(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var iaa=String.fromCharCode,Jkd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Lvo={};function DwS(e,t){if(!Lvo[e]){Lvo[e]={};for(let r=0;r<e.length;r++)Lvo[e][e.charAt(r)]=r}return Lvo[e][t]}var naa={compressToBase64:function(e){if(e==null)return"";let t=naa._compress(e,6,function(r){return Jkd.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:naa._decompress(e.length,32,function(t){return DwS(Jkd,e.charAt(t))})},compress:function(e){return naa._compress(e,16,function(t){return iaa(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,w;for(w=0;w<e.length;w+=1)if(d=e.charAt(w),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:naa._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,w;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;w=iaa(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;w=iaa(b);break;case 2:return""}for(i[3]=w,c=w,n.push(w);;){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(w=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++]=iaa(b),w=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++]=iaa(b),w=l-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,d),d++),i[w])s=i[w];else if(w===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++)}}},BEs=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 Uvo="0123456789abcdef",Vvo=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+=Uvo.charAt(this.bytes[r]>>>4),t+=Uvo.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+=Uvo.charAt(this.bytes[r]>>>4),t+=Uvo.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}},xEs=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??EwS()}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 Vvo.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,Vvo.ofInner(t)}},EwS=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),Kkd,Ykd=()=>MwS().toString(),MwS=()=>(Kkd||(Kkd=new xEs)).generate(),Wvo=class extends Error{constructor(t){super("HTTP error while fetching PostHog: "+t.status),this.response=t,this.name="PostHogFetchHttpError"}},aaa=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};function Xkd(e){return typeof e=="object"&&(e instanceof Wvo||e instanceof aaa)}var IEs=class{constructor(t,r){this.flushPromise=null,this.disableGeoip=!0,this.historicalMigration=!1,this.disabled=!1,this.defaultOptIn=!0,this.pendingPromises={},this._events=new BEs,this._isInitialized=!1,PwS(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=jwS(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:Xkd},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(n8t.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(n8t.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(n8t.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=Ykd();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:Qkd(),uuid:i?.uuid?i.uuid:Ykd()};(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(n8t.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(n8t.Queue,u),this._events.emit(t,n),u.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=rep(()=>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(n8t.Queue)||[];if(!t.length)return[];let r=t.slice(0,this.maxBatchSize),i=r.map(s=>s.message),n=()=>{let s=this.getPersistedProperty(n8t.Queue)||[];this.setPersistedProperty(n8t.Queue,s.slice(r.length))},a={api_key:this.apiKey,batch:i,sent_at:Qkd()};this.historicalMigration&&(a.historical_migration=!0);let u=JSON.stringify(a),l=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${SwS()}&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(naa.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 aaa||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 wwS(async()=>{let u=null;try{u=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(d){throw new aaa(d)}if(!(r.mode==="no-cors")&&(u.status<200||u.status>=400))throw new Wvo(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(n8t.Queue)||[]).length!==0;){await this.flush();let n=Date.now();if(r<n)break}}catch(r){if(!Xkd(r))throw r;this.logMsgIfDebug(()=>console.error("Error while shutting down PostHog",r))}}},zEs=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},REs=typeof fetch<"u"?fetch:typeof global.fetch<"u"?global.fetch:void 0;if(!REs){let e=Gkd();REs=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 iep=REs,AwS=1152921504606847e3,qwS=["is_not"],Hvo=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},k6=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},NEs=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||iep,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 k6?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 k6||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 k6("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 k6("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 k6)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new k6("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=aep(l,n,this.cohorts,this.debugMode):s=nep(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&Zkd(t.key,r)>a/100)}getMatchingVariant(t,r){let i=Zkd(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 Hvo("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 Hvo&&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=rep(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}};function Zkd(e,t,r=""){let i=(0,tep.createHash)();return i.update(`${e}.${t}${r}`),parseInt(i.digest("hex").slice(0,15),16)/AwS}function nep(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 k6("Operator is_not_set is not supported")}else throw new k6(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!qwS.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 kkd(String(n))&&String(u).match(String(n))!==null;case"not_regex":return kkd(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=TwS(String(n));if(s==null&&(s=eep(n)),s==null)throw new k6(`Invalid date: ${n}`);let o=eep(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new k6(`Unknown operator: ${a}`)}}function aep(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new k6("can't match cohort without a given cohort property value");let a=r[n];return oep(a,t,r,i)}function oep(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=oep(l,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof k6)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new k6("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=aep(l,t,r,i):d=nep(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 k6)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new k6("can't match cohort without a given cohort property value");return n==="AND"}}function kkd(e){try{return new RegExp(e),!0}catch{return!1}}function eep(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 k6(`${e} is in an invalid date format`)}else throw new k6(`The date provided ${e} must be a string, number, or date object`)}function TwS(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 CwS=30*1e3,BwS=50*1e3,Wbn=class extends IEs{constructor(t,r={}){super(t,r),this._memoryStorage=new zEs,this.options=r,r.personalApiKey&&(this.featureFlagsPoller=new NEs({pollingInterval:typeof r.featureFlagsPollingInterval=="number"?r.featureFlagsPollingInterval:CwS,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||BwS}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):iep(t,r)}getLibraryId(){return"posthog-node"}getLibraryVersion(){return mwS}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,w]of Object.entries(b))g[`$feature/${m}`]=w;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}}},FEs=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})}};FEs.POSTHOG_ID_TAG="posthog_distinct_id";var $vo=class{posthog;constructor({posthogApiKey:t}){this.posthog=new Wbn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.56.3",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var oaa=class{async sendEvent(){}async identify(){}async flush(){}};var Hbn=require("fs/promises"),lep=require("os"),fep=require("path");var uep=vi(require("crypto")),Qvo=new Uint8Array(256),Gvo=Qvo.length;function LEs(){return Gvo>Qvo.length-16&&(uep.default.randomFillSync(Qvo),Gvo=0),Qvo.slice(Gvo,Gvo+=16)}var BU=[];for(let e=0;e<256;++e)BU.push((e+256).toString(16).slice(1));function sep(e,t=0){return BU[e[t+0]]+BU[e[t+1]]+BU[e[t+2]]+BU[e[t+3]]+"-"+BU[e[t+4]]+BU[e[t+5]]+"-"+BU[e[t+6]]+BU[e[t+7]]+"-"+BU[e[t+8]]+BU[e[t+9]]+"-"+BU[e[t+10]]+BU[e[t+11]]+BU[e[t+12]]+BU[e[t+13]]+BU[e[t+14]]+BU[e[t+15]]}var cep=vi(require("crypto")),UEs={randomUUID:cep.default.randomUUID};function xwS(e,t,r){if(UEs.randomUUID&&!t&&!e)return UEs.randomUUID();e=e||{};let i=e.random||(e.rng||LEs)();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 sep(i)}var zre=xwS;var IwS="id",zwS=".fern",uaa=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new Wbn(r),this.userId=t==null?void 0:tms(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.56.3",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Xu(Wl.of((0,lep.homedir)()),Xa.of(zwS),Xa.of(IwS));await Cf(t)||(await(0,Hbn.mkdir)((0,fep.dirname)(t),{recursive:!0}),await(0,Hbn.writeFile)(t,zre())),this.persistedDistinctId=(await(0,Hbn.readFile)(t)).toString()}return this.persistedDistinctId}};var VEs;async function $bn(){return VEs==null&&(VEs=await RwS()),VEs}async function RwS(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new oaa;let r=await tfo();return r!=null?new uaa({token:r,posthogApiKey:e}):await efo()!=null?new $vo({posthogApiKey:e}):new uaa({token:void 0,posthogApiKey:e})}catch{return new oaa}}function saa(e,t){return function(){return e.apply(t,arguments)}}var{toString:NwS}=Object.prototype,{getPrototypeOf:$Es}=Object,Kvo=(e=>t=>{let r=NwS.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),a8t=e=>(e=e.toLowerCase(),t=>Kvo(t)===e),Yvo=e=>t=>typeof t===e,{isArray:Gbn}=Array,caa=Yvo("undefined");function FwS(e){return e!==null&&!caa(e)&&e.constructor!==null&&!caa(e.constructor)&&W1e(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var _ep=a8t("ArrayBuffer");function LwS(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&_ep(e.buffer),t}var UwS=Yvo("string"),W1e=Yvo("function"),hep=Yvo("number"),Xvo=e=>e!==null&&typeof e=="object",VwS=e=>e===!0||e===!1,Jvo=e=>{if(Kvo(e)!=="object")return!1;let t=$Es(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},WwS=a8t("Date"),HwS=a8t("File"),$wS=a8t("Blob"),GwS=a8t("FileList"),QwS=e=>Xvo(e)&&W1e(e.pipe),JwS=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||W1e(e.append)&&((t=Kvo(e))==="formdata"||t==="object"&&W1e(e.toString)&&e.toString()==="[object FormData]"))},KwS=a8t("URLSearchParams"),[YwS,XwS,ZwS,kwS]=["ReadableStream","Request","Response","Headers"].map(a8t),e1S=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function laa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),Gbn(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 yep(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 RCi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,vep=e=>!caa(e)&&e!==RCi;function HEs(){let{caseless:e}=vep(this)&&this||{},t={},r=(i,n)=>{let a=e&&yep(t,n)||n;Jvo(t[a])&&Jvo(i)?t[a]=HEs(t[a],i):Jvo(i)?t[a]=HEs({},i):Gbn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&laa(arguments[i],r);return t}var t1S=(e,t,r,{allOwnKeys:i}={})=>(laa(t,(n,a)=>{r&&W1e(n)?e[a]=saa(n,r):e[a]=n},{allOwnKeys:i}),e),r1S=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),i1S=(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)},n1S=(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&&$Es(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},a1S=(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},o1S=e=>{if(!e)return null;if(Gbn(e))return e;let t=e.length;if(!hep(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},u1S=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&$Es(Uint8Array)),s1S=(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])}},c1S=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},l1S=a8t("HTMLFormElement"),f1S=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),dep=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),d1S=a8t("RegExp"),bep=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};laa(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},p1S=e=>{bep(e,(t,r)=>{if(W1e(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(W1e(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+"'")})}})},_1S=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return Gbn(e)?i(e):i(String(e).split(t)),r},h1S=()=>{},y1S=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t,WEs="abcdefghijklmnopqrstuvwxyz",pep="0123456789",gep={DIGIT:pep,ALPHA:WEs,ALPHA_DIGIT:WEs+WEs.toUpperCase()+pep},v1S=(e=16,t=gep.ALPHA_DIGIT)=>{let r="",{length:i}=t;for(;e--;)r+=t[Math.random()*i|0];return r};function b1S(e){return!!(e&&W1e(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var g1S=e=>{let t=new Array(10),r=(i,n)=>{if(Xvo(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=Gbn(i)?[]:{};return laa(i,(u,l)=>{let d=r(u,n+1);!caa(d)&&(a[l]=d)}),t[n]=void 0,a}}return i};return r(e,0)},O1S=a8t("AsyncFunction"),m1S=e=>e&&(Xvo(e)||W1e(e))&&W1e(e.then)&&W1e(e.catch),Oep=((e,t)=>e?setImmediate:t?((r,i)=>(RCi.addEventListener("message",({source:n,data:a})=>{n===RCi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),RCi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",W1e(RCi.postMessage)),P1S=typeof queueMicrotask<"u"?queueMicrotask.bind(RCi):typeof process<"u"&&process.nextTick||Oep,us={isArray:Gbn,isArrayBuffer:_ep,isBuffer:FwS,isFormData:JwS,isArrayBufferView:LwS,isString:UwS,isNumber:hep,isBoolean:VwS,isObject:Xvo,isPlainObject:Jvo,isReadableStream:YwS,isRequest:XwS,isResponse:ZwS,isHeaders:kwS,isUndefined:caa,isDate:WwS,isFile:HwS,isBlob:$wS,isRegExp:d1S,isFunction:W1e,isStream:QwS,isURLSearchParams:KwS,isTypedArray:u1S,isFileList:GwS,forEach:laa,merge:HEs,extend:t1S,trim:e1S,stripBOM:r1S,inherits:i1S,toFlatObject:n1S,kindOf:Kvo,kindOfTest:a8t,endsWith:a1S,toArray:o1S,forEachEntry:s1S,matchAll:c1S,isHTMLForm:l1S,hasOwnProperty:dep,hasOwnProp:dep,reduceDescriptors:bep,freezeMethods:p1S,toObjectSet:_1S,toCamelCase:f1S,noop:h1S,toFiniteNumber:y1S,findKey:yep,global:RCi,isContextDefined:vep,ALPHABET:gep,generateString:v1S,isSpecCompliantForm:b1S,toJSONObject:g1S,isAsyncFn:O1S,isThenable:m1S,setImmediate:Oep,asap:P1S};function Qbn(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)}us.inherits(Qbn,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:us.toJSONObject(this.config),code:this.code,status:this.status}}});var mep=Qbn.prototype,Pep={};["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=>{Pep[e]={value:e}});Object.defineProperties(Qbn,Pep);Object.defineProperty(mep,"isAxiosError",{value:!0});Qbn.from=(e,t,r,i,n,a)=>{let u=Object.create(mep);return us.toFlatObject(e,u,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),Qbn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var mp=Qbn;var jep=vi(JZn(),1),Zvo=jep.default;function GEs(e){return us.isPlainObject(e)||us.isArray(e)}function Sep(e){return us.endsWith(e,"[]")?e.slice(0,-2):e}function wep(e,t,r){return e?e.concat(t).map(function(n,a){return n=Sep(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function j1S(e){return us.isArray(e)&&!e.some(GEs)}var w1S=us.toFlatObject(us,{},null,function(t){return/^is[A-Z]/.test(t)});function S1S(e,t,r){if(!us.isObject(e))throw new TypeError("target must be an object");t=t||new(Zvo||FormData),r=us.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,w){return!us.isUndefined(w[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&us.isSpecCompliantForm(t);if(!us.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(us.isDate(O))return O.toISOString();if(!d&&us.isBlob(O))throw new mp("Blob is not supported. Use a Buffer instead.");return us.isArrayBuffer(O)||us.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,w){let E=O;if(O&&!w&&typeof O=="object"){if(us.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(us.isArray(O)&&j1S(O)||(us.isFileList(O)||us.endsWith(m,"[]"))&&(E=us.toArray(O)))return m=Sep(m),E.forEach(function(q,D){!(us.isUndefined(q)||q===null)&&t.append(u===!0?wep([m],D,a):u===null?m:m+"[]",s(q))}),!1}return GEs(O)?!0:(t.append(wep(w,m,a),s(O)),!1)}let c=[],b=Object.assign(w1S,{defaultVisitor:o,convertValue:s,isVisitable:GEs});function g(O,m){if(!us.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),us.forEach(O,function(E,A){(!(us.isUndefined(E)||E===null)&&n.call(t,E,us.isString(A)?A.trim():A,m,b))===!0&&g(E,m?m.concat(A):[A])}),c.pop()}}if(!us.isObject(e))throw new TypeError("data must be an object");return g(e),t}var Esi=S1S;function Dep(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function Eep(e,t){this._pairs=[],e&&Esi(e,this,t)}var Mep=Eep.prototype;Mep.append=function(t,r){this._pairs.push([t,r])};Mep.toString=function(t){let r=t?function(i){return t.call(this,i,Dep)}:Dep;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var Aep=Eep;function D1S(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function NCi(e,t,r){if(!t)return e;let i=r&&r.encode||D1S,n=r&&r.serialize,a;if(n?a=n(t,r):a=us.isURLSearchParams(t)?t.toString():new Aep(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var QEs=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){us.forEach(this.handlers,function(i){i!==null&&t(i)})}},JEs=QEs;var Jbn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var qep=vi(require("url"),1),Tep=qep.default.URLSearchParams;var Cep={isNode:!0,classes:{URLSearchParams:Tep,FormData:Zvo,Blob:typeof Blob<"u"&&Blob||null},protocols:["http","https","file","data"]};var XEs={};Io(XEs,{hasBrowserEnv:()=>YEs,hasStandardBrowserEnv:()=>E1S,hasStandardBrowserWebWorkerEnv:()=>M1S,navigator:()=>KEs,origin:()=>A1S});var YEs=typeof window<"u"&&typeof document<"u",KEs=typeof navigator=="object"&&navigator||void 0,E1S=YEs&&(!KEs||["ReactNative","NativeScript","NS"].indexOf(KEs.product)<0),M1S=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",A1S=YEs&&window.location.href||"http://localhost";var NT={...XEs,...Cep};function ZEs(e,t){return Esi(e,new NT.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return NT.isNode&&us.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function q1S(e){return us.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function T1S(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 C1S(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&&us.isArray(n)?n.length:u,d?(us.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!us.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&us.isArray(n[u])&&(n[u]=T1S(n[u])),!l)}if(us.isFormData(e)&&us.isFunction(e.entries)){let r={};return us.forEachEntry(e,(i,n)=>{t(q1S(i),n,r,0)}),r}return null}var kvo=C1S;function B1S(e,t,r){if(us.isString(e))try{return(t||JSON.parse)(e),us.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var kEs={transitional:Jbn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=us.isObject(t);if(a&&us.isHTMLForm(t)&&(t=new FormData(t)),us.isFormData(t))return n?JSON.stringify(kvo(t)):t;if(us.isArrayBuffer(t)||us.isBuffer(t)||us.isStream(t)||us.isFile(t)||us.isBlob(t)||us.isReadableStream(t))return t;if(us.isArrayBufferView(t))return t.buffer;if(us.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 ZEs(t,this.formSerializer).toString();if((l=us.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return Esi(l?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),B1S(t)):t}],transformResponse:[function(t){let r=this.transitional||kEs.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(us.isResponse(t)||us.isReadableStream(t))return t;if(t&&us.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"?mp.from(l,mp.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:NT.classes.FormData,Blob:NT.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};us.forEach(["delete","get","head","post","put","patch"],e=>{kEs.headers[e]={}});var Kbn=kEs;var x1S=us.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"]),Bep=e=>{let t={},r,i,n;return e&&e.split(`
|
|
1694
|
+
`}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&&tvo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var UZd=vi(xZd(),1),VZd=vi(Z1s(),1),WZd=vi(FZd(),1),qA=vi(U1e(),1),HZd=vi(xia(),1);var Svo=vi(U1e(),1),LZd=vi(xia(),1),Dvo=function(e,t,r){return typeof e[t]!="function"?(0,Svo.of)(e):(0,Svo.from)((0,LZd.default)(e[t])(r).then(i=>(e[t]=i,e)))};var $na={isPlainObject:UZd.default,set:WZd.default,get:VZd.default},zbn=class extends BCi{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=$na.isPlainObject(r)?{...r}:{},$na.isPlainObject(t)&&(t=Object.values(t).every(n=>$na.isPlainObject(n)&&n.name===void 0)?Object.entries(t).map(([n,a])=>({name:n,...a})):[t]);let i=Array.isArray(t)?(0,qA.from)(t):t;return this.process=i.pipe((0,qA.concatMap)(this.processQuestion.bind(this)),(0,qA.publish)()),this.process.connect(),this.process.pipe((0,qA.reduce)((n,a)=>($na.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,qA.defer)(()=>(0,qA.of)(t).pipe((0,qA.concatMap)(this.setDefaultType.bind(this)),(0,qA.concatMap)(this.filterIfRunnable.bind(this)),(0,qA.concatMap)(()=>Dvo(t,"message",this.answers)),(0,qA.concatMap)(()=>Dvo(t,"default",this.answers)),(0,qA.concatMap)(()=>Dvo(t,"choices",this.answers)),(0,qA.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,qA.defer)(()=>(0,qA.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,qA.defer)(()=>(0,qA.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&$na.get(this.answers,t.name)!==void 0)return(0,qA.empty)();if(t.when===!1)return(0,qA.empty)();if(typeof t.when!="function")return(0,qA.of)(t);let{answers:r}=this;return(0,qA.defer)(()=>(0,qA.from)((0,HZd.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,qA.filter)(i=>i!=null)))}};function $Zd(e){let t=function(r,i){let n;try{n=new zbn(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",Ena),this.registerPrompt("input",SCi),this.registerPrompt("number",Mna),this.registerPrompt("confirm",Ana),this.registerPrompt("rawlist",qna),this.registerPrompt("expand",Tna),this.registerPrompt("checkbox",Cna),this.registerPrompt("password",Bna),this.registerPrompt("editor",Wna)},t.restoreDefaultPrompts(),t}var QDs=$Zd();function KmS(e,t){QDs.registerPrompt(e,t)}function YmS(){QDs.restoreDefaultPrompts()}var XmS={prompt:QDs,ui:{BottomBar:Hna,Prompt:zbn},createPromptModule:$Zd,registerPrompt:KmS,restoreDefaultPrompts:YmS,Separator:Tre},Evo=XmS;var tep=vi(GZd()),mwS="4.2.1",n8t;(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"})(n8t||(n8t={}));function PwS(e,t){if(!e)throw new Error(t)}function jwS(e){return e?.replace(/\/+$/,"")}async function wwS(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 SwS(){return new Date().getTime()}function Qkd(){return new Date().toISOString()}function rep(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var iaa=String.fromCharCode,Jkd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Lvo={};function DwS(e,t){if(!Lvo[e]){Lvo[e]={};for(let r=0;r<e.length;r++)Lvo[e][e.charAt(r)]=r}return Lvo[e][t]}var naa={compressToBase64:function(e){if(e==null)return"";let t=naa._compress(e,6,function(r){return Jkd.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:naa._decompress(e.length,32,function(t){return DwS(Jkd,e.charAt(t))})},compress:function(e){return naa._compress(e,16,function(t){return iaa(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,w;for(w=0;w<e.length;w+=1)if(d=e.charAt(w),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:naa._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,w;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;w=iaa(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;w=iaa(b);break;case 2:return""}for(i[3]=w,c=w,n.push(w);;){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(w=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++]=iaa(b),w=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++]=iaa(b),w=l-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,d),d++),i[w])s=i[w];else if(w===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++)}}},BEs=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 Uvo="0123456789abcdef",Vvo=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+=Uvo.charAt(this.bytes[r]>>>4),t+=Uvo.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+=Uvo.charAt(this.bytes[r]>>>4),t+=Uvo.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}},xEs=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??EwS()}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 Vvo.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,Vvo.ofInner(t)}},EwS=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),Kkd,Ykd=()=>MwS().toString(),MwS=()=>(Kkd||(Kkd=new xEs)).generate(),Wvo=class extends Error{constructor(t){super("HTTP error while fetching PostHog: "+t.status),this.response=t,this.name="PostHogFetchHttpError"}},aaa=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};function Xkd(e){return typeof e=="object"&&(e instanceof Wvo||e instanceof aaa)}var IEs=class{constructor(t,r){this.flushPromise=null,this.disableGeoip=!0,this.historicalMigration=!1,this.disabled=!1,this.defaultOptIn=!0,this.pendingPromises={},this._events=new BEs,this._isInitialized=!1,PwS(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=jwS(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:Xkd},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(n8t.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(n8t.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(n8t.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=Ykd();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:Qkd(),uuid:i?.uuid?i.uuid:Ykd()};(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(n8t.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(n8t.Queue,u),this._events.emit(t,n),u.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=rep(()=>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(n8t.Queue)||[];if(!t.length)return[];let r=t.slice(0,this.maxBatchSize),i=r.map(s=>s.message),n=()=>{let s=this.getPersistedProperty(n8t.Queue)||[];this.setPersistedProperty(n8t.Queue,s.slice(r.length))},a={api_key:this.apiKey,batch:i,sent_at:Qkd()};this.historicalMigration&&(a.historical_migration=!0);let u=JSON.stringify(a),l=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${SwS()}&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(naa.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 aaa||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 wwS(async()=>{let u=null;try{u=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(d){throw new aaa(d)}if(!(r.mode==="no-cors")&&(u.status<200||u.status>=400))throw new Wvo(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(n8t.Queue)||[]).length!==0;){await this.flush();let n=Date.now();if(r<n)break}}catch(r){if(!Xkd(r))throw r;this.logMsgIfDebug(()=>console.error("Error while shutting down PostHog",r))}}},zEs=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},REs=typeof fetch<"u"?fetch:typeof global.fetch<"u"?global.fetch:void 0;if(!REs){let e=Gkd();REs=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 iep=REs,AwS=1152921504606847e3,qwS=["is_not"],Hvo=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},k6=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},NEs=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||iep,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 k6?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 k6||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 k6("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 k6("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 k6)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new k6("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=aep(l,n,this.cohorts,this.debugMode):s=nep(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&Zkd(t.key,r)>a/100)}getMatchingVariant(t,r){let i=Zkd(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 Hvo("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 Hvo&&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=rep(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}};function Zkd(e,t,r=""){let i=(0,tep.createHash)();return i.update(`${e}.${t}${r}`),parseInt(i.digest("hex").slice(0,15),16)/AwS}function nep(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 k6("Operator is_not_set is not supported")}else throw new k6(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!qwS.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 kkd(String(n))&&String(u).match(String(n))!==null;case"not_regex":return kkd(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=TwS(String(n));if(s==null&&(s=eep(n)),s==null)throw new k6(`Invalid date: ${n}`);let o=eep(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new k6(`Unknown operator: ${a}`)}}function aep(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new k6("can't match cohort without a given cohort property value");let a=r[n];return oep(a,t,r,i)}function oep(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=oep(l,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof k6)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new k6("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=aep(l,t,r,i):d=nep(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 k6)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new k6("can't match cohort without a given cohort property value");return n==="AND"}}function kkd(e){try{return new RegExp(e),!0}catch{return!1}}function eep(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 k6(`${e} is in an invalid date format`)}else throw new k6(`The date provided ${e} must be a string, number, or date object`)}function TwS(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 CwS=30*1e3,BwS=50*1e3,Wbn=class extends IEs{constructor(t,r={}){super(t,r),this._memoryStorage=new zEs,this.options=r,r.personalApiKey&&(this.featureFlagsPoller=new NEs({pollingInterval:typeof r.featureFlagsPollingInterval=="number"?r.featureFlagsPollingInterval:CwS,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||BwS}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):iep(t,r)}getLibraryId(){return"posthog-node"}getLibraryVersion(){return mwS}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,w]of Object.entries(b))g[`$feature/${m}`]=w;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}}},FEs=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})}};FEs.POSTHOG_ID_TAG="posthog_distinct_id";var $vo=class{posthog;constructor({posthogApiKey:t}){this.posthog=new Wbn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.56.5",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var oaa=class{async sendEvent(){}async identify(){}async flush(){}};var Hbn=require("fs/promises"),lep=require("os"),fep=require("path");var uep=vi(require("crypto")),Qvo=new Uint8Array(256),Gvo=Qvo.length;function LEs(){return Gvo>Qvo.length-16&&(uep.default.randomFillSync(Qvo),Gvo=0),Qvo.slice(Gvo,Gvo+=16)}var BU=[];for(let e=0;e<256;++e)BU.push((e+256).toString(16).slice(1));function sep(e,t=0){return BU[e[t+0]]+BU[e[t+1]]+BU[e[t+2]]+BU[e[t+3]]+"-"+BU[e[t+4]]+BU[e[t+5]]+"-"+BU[e[t+6]]+BU[e[t+7]]+"-"+BU[e[t+8]]+BU[e[t+9]]+"-"+BU[e[t+10]]+BU[e[t+11]]+BU[e[t+12]]+BU[e[t+13]]+BU[e[t+14]]+BU[e[t+15]]}var cep=vi(require("crypto")),UEs={randomUUID:cep.default.randomUUID};function xwS(e,t,r){if(UEs.randomUUID&&!t&&!e)return UEs.randomUUID();e=e||{};let i=e.random||(e.rng||LEs)();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 sep(i)}var zre=xwS;var IwS="id",zwS=".fern",uaa=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new Wbn(r),this.userId=t==null?void 0:tms(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.56.5",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Xu(Wl.of((0,lep.homedir)()),Xa.of(zwS),Xa.of(IwS));await Cf(t)||(await(0,Hbn.mkdir)((0,fep.dirname)(t),{recursive:!0}),await(0,Hbn.writeFile)(t,zre())),this.persistedDistinctId=(await(0,Hbn.readFile)(t)).toString()}return this.persistedDistinctId}};var VEs;async function $bn(){return VEs==null&&(VEs=await RwS()),VEs}async function RwS(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new oaa;let r=await tfo();return r!=null?new uaa({token:r,posthogApiKey:e}):await efo()!=null?new $vo({posthogApiKey:e}):new uaa({token:void 0,posthogApiKey:e})}catch{return new oaa}}function saa(e,t){return function(){return e.apply(t,arguments)}}var{toString:NwS}=Object.prototype,{getPrototypeOf:$Es}=Object,Kvo=(e=>t=>{let r=NwS.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),a8t=e=>(e=e.toLowerCase(),t=>Kvo(t)===e),Yvo=e=>t=>typeof t===e,{isArray:Gbn}=Array,caa=Yvo("undefined");function FwS(e){return e!==null&&!caa(e)&&e.constructor!==null&&!caa(e.constructor)&&W1e(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var _ep=a8t("ArrayBuffer");function LwS(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&_ep(e.buffer),t}var UwS=Yvo("string"),W1e=Yvo("function"),hep=Yvo("number"),Xvo=e=>e!==null&&typeof e=="object",VwS=e=>e===!0||e===!1,Jvo=e=>{if(Kvo(e)!=="object")return!1;let t=$Es(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},WwS=a8t("Date"),HwS=a8t("File"),$wS=a8t("Blob"),GwS=a8t("FileList"),QwS=e=>Xvo(e)&&W1e(e.pipe),JwS=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||W1e(e.append)&&((t=Kvo(e))==="formdata"||t==="object"&&W1e(e.toString)&&e.toString()==="[object FormData]"))},KwS=a8t("URLSearchParams"),[YwS,XwS,ZwS,kwS]=["ReadableStream","Request","Response","Headers"].map(a8t),e1S=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function laa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),Gbn(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 yep(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 RCi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,vep=e=>!caa(e)&&e!==RCi;function HEs(){let{caseless:e}=vep(this)&&this||{},t={},r=(i,n)=>{let a=e&&yep(t,n)||n;Jvo(t[a])&&Jvo(i)?t[a]=HEs(t[a],i):Jvo(i)?t[a]=HEs({},i):Gbn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&laa(arguments[i],r);return t}var t1S=(e,t,r,{allOwnKeys:i}={})=>(laa(t,(n,a)=>{r&&W1e(n)?e[a]=saa(n,r):e[a]=n},{allOwnKeys:i}),e),r1S=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),i1S=(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)},n1S=(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&&$Es(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},a1S=(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},o1S=e=>{if(!e)return null;if(Gbn(e))return e;let t=e.length;if(!hep(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},u1S=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&$Es(Uint8Array)),s1S=(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])}},c1S=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},l1S=a8t("HTMLFormElement"),f1S=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),dep=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),d1S=a8t("RegExp"),bep=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};laa(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},p1S=e=>{bep(e,(t,r)=>{if(W1e(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(W1e(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+"'")})}})},_1S=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return Gbn(e)?i(e):i(String(e).split(t)),r},h1S=()=>{},y1S=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t,WEs="abcdefghijklmnopqrstuvwxyz",pep="0123456789",gep={DIGIT:pep,ALPHA:WEs,ALPHA_DIGIT:WEs+WEs.toUpperCase()+pep},v1S=(e=16,t=gep.ALPHA_DIGIT)=>{let r="",{length:i}=t;for(;e--;)r+=t[Math.random()*i|0];return r};function b1S(e){return!!(e&&W1e(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var g1S=e=>{let t=new Array(10),r=(i,n)=>{if(Xvo(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=Gbn(i)?[]:{};return laa(i,(u,l)=>{let d=r(u,n+1);!caa(d)&&(a[l]=d)}),t[n]=void 0,a}}return i};return r(e,0)},O1S=a8t("AsyncFunction"),m1S=e=>e&&(Xvo(e)||W1e(e))&&W1e(e.then)&&W1e(e.catch),Oep=((e,t)=>e?setImmediate:t?((r,i)=>(RCi.addEventListener("message",({source:n,data:a})=>{n===RCi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),RCi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",W1e(RCi.postMessage)),P1S=typeof queueMicrotask<"u"?queueMicrotask.bind(RCi):typeof process<"u"&&process.nextTick||Oep,us={isArray:Gbn,isArrayBuffer:_ep,isBuffer:FwS,isFormData:JwS,isArrayBufferView:LwS,isString:UwS,isNumber:hep,isBoolean:VwS,isObject:Xvo,isPlainObject:Jvo,isReadableStream:YwS,isRequest:XwS,isResponse:ZwS,isHeaders:kwS,isUndefined:caa,isDate:WwS,isFile:HwS,isBlob:$wS,isRegExp:d1S,isFunction:W1e,isStream:QwS,isURLSearchParams:KwS,isTypedArray:u1S,isFileList:GwS,forEach:laa,merge:HEs,extend:t1S,trim:e1S,stripBOM:r1S,inherits:i1S,toFlatObject:n1S,kindOf:Kvo,kindOfTest:a8t,endsWith:a1S,toArray:o1S,forEachEntry:s1S,matchAll:c1S,isHTMLForm:l1S,hasOwnProperty:dep,hasOwnProp:dep,reduceDescriptors:bep,freezeMethods:p1S,toObjectSet:_1S,toCamelCase:f1S,noop:h1S,toFiniteNumber:y1S,findKey:yep,global:RCi,isContextDefined:vep,ALPHABET:gep,generateString:v1S,isSpecCompliantForm:b1S,toJSONObject:g1S,isAsyncFn:O1S,isThenable:m1S,setImmediate:Oep,asap:P1S};function Qbn(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)}us.inherits(Qbn,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:us.toJSONObject(this.config),code:this.code,status:this.status}}});var mep=Qbn.prototype,Pep={};["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=>{Pep[e]={value:e}});Object.defineProperties(Qbn,Pep);Object.defineProperty(mep,"isAxiosError",{value:!0});Qbn.from=(e,t,r,i,n,a)=>{let u=Object.create(mep);return us.toFlatObject(e,u,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),Qbn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var mp=Qbn;var jep=vi(JZn(),1),Zvo=jep.default;function GEs(e){return us.isPlainObject(e)||us.isArray(e)}function Sep(e){return us.endsWith(e,"[]")?e.slice(0,-2):e}function wep(e,t,r){return e?e.concat(t).map(function(n,a){return n=Sep(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function j1S(e){return us.isArray(e)&&!e.some(GEs)}var w1S=us.toFlatObject(us,{},null,function(t){return/^is[A-Z]/.test(t)});function S1S(e,t,r){if(!us.isObject(e))throw new TypeError("target must be an object");t=t||new(Zvo||FormData),r=us.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,w){return!us.isUndefined(w[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&us.isSpecCompliantForm(t);if(!us.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(us.isDate(O))return O.toISOString();if(!d&&us.isBlob(O))throw new mp("Blob is not supported. Use a Buffer instead.");return us.isArrayBuffer(O)||us.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,w){let E=O;if(O&&!w&&typeof O=="object"){if(us.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(us.isArray(O)&&j1S(O)||(us.isFileList(O)||us.endsWith(m,"[]"))&&(E=us.toArray(O)))return m=Sep(m),E.forEach(function(q,D){!(us.isUndefined(q)||q===null)&&t.append(u===!0?wep([m],D,a):u===null?m:m+"[]",s(q))}),!1}return GEs(O)?!0:(t.append(wep(w,m,a),s(O)),!1)}let c=[],b=Object.assign(w1S,{defaultVisitor:o,convertValue:s,isVisitable:GEs});function g(O,m){if(!us.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),us.forEach(O,function(E,A){(!(us.isUndefined(E)||E===null)&&n.call(t,E,us.isString(A)?A.trim():A,m,b))===!0&&g(E,m?m.concat(A):[A])}),c.pop()}}if(!us.isObject(e))throw new TypeError("data must be an object");return g(e),t}var Esi=S1S;function Dep(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function Eep(e,t){this._pairs=[],e&&Esi(e,this,t)}var Mep=Eep.prototype;Mep.append=function(t,r){this._pairs.push([t,r])};Mep.toString=function(t){let r=t?function(i){return t.call(this,i,Dep)}:Dep;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var Aep=Eep;function D1S(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function NCi(e,t,r){if(!t)return e;let i=r&&r.encode||D1S,n=r&&r.serialize,a;if(n?a=n(t,r):a=us.isURLSearchParams(t)?t.toString():new Aep(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var QEs=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){us.forEach(this.handlers,function(i){i!==null&&t(i)})}},JEs=QEs;var Jbn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var qep=vi(require("url"),1),Tep=qep.default.URLSearchParams;var Cep={isNode:!0,classes:{URLSearchParams:Tep,FormData:Zvo,Blob:typeof Blob<"u"&&Blob||null},protocols:["http","https","file","data"]};var XEs={};Io(XEs,{hasBrowserEnv:()=>YEs,hasStandardBrowserEnv:()=>E1S,hasStandardBrowserWebWorkerEnv:()=>M1S,navigator:()=>KEs,origin:()=>A1S});var YEs=typeof window<"u"&&typeof document<"u",KEs=typeof navigator=="object"&&navigator||void 0,E1S=YEs&&(!KEs||["ReactNative","NativeScript","NS"].indexOf(KEs.product)<0),M1S=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",A1S=YEs&&window.location.href||"http://localhost";var NT={...XEs,...Cep};function ZEs(e,t){return Esi(e,new NT.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return NT.isNode&&us.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function q1S(e){return us.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function T1S(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 C1S(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&&us.isArray(n)?n.length:u,d?(us.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!us.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&us.isArray(n[u])&&(n[u]=T1S(n[u])),!l)}if(us.isFormData(e)&&us.isFunction(e.entries)){let r={};return us.forEachEntry(e,(i,n)=>{t(q1S(i),n,r,0)}),r}return null}var kvo=C1S;function B1S(e,t,r){if(us.isString(e))try{return(t||JSON.parse)(e),us.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var kEs={transitional:Jbn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=us.isObject(t);if(a&&us.isHTMLForm(t)&&(t=new FormData(t)),us.isFormData(t))return n?JSON.stringify(kvo(t)):t;if(us.isArrayBuffer(t)||us.isBuffer(t)||us.isStream(t)||us.isFile(t)||us.isBlob(t)||us.isReadableStream(t))return t;if(us.isArrayBufferView(t))return t.buffer;if(us.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 ZEs(t,this.formSerializer).toString();if((l=us.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return Esi(l?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),B1S(t)):t}],transformResponse:[function(t){let r=this.transitional||kEs.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(us.isResponse(t)||us.isReadableStream(t))return t;if(t&&us.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"?mp.from(l,mp.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:NT.classes.FormData,Blob:NT.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};us.forEach(["delete","get","head","post","put","patch"],e=>{kEs.headers[e]={}});var Kbn=kEs;var x1S=us.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"]),Bep=e=>{let t={},r,i,n;return e&&e.split(`
|
|
1695
1695
|
`).forEach(function(u){n=u.indexOf(":"),r=u.substring(0,n).trim().toLowerCase(),i=u.substring(n+1).trim(),!(!r||t[r]&&x1S[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var xep=Symbol("internals");function faa(e){return e&&String(e).trim().toLowerCase()}function ebo(e){return e===!1||e==null?e:us.isArray(e)?e.map(ebo):String(e)}function I1S(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 z1S=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function eMs(e,t,r,i,n){if(us.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!us.isString(t)){if(us.isString(i))return t.indexOf(i)!==-1;if(us.isRegExp(i))return i.test(t)}}function R1S(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function N1S(e,t){let r=us.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 Ybn=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(l,d,s){let o=faa(d);if(!o)throw new Error("header name must be a non-empty string");let c=us.findKey(n,o);(!c||n[c]===void 0||s===!0||s===void 0&&n[c]!==!1)&&(n[c||d]=ebo(l))}let u=(l,d)=>us.forEach(l,(s,o)=>a(s,o,d));if(us.isPlainObject(t)||t instanceof this.constructor)u(t,r);else if(us.isString(t)&&(t=t.trim())&&!z1S(t))u(Bep(t),r);else if(us.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=faa(t),t){let i=us.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return I1S(n);if(us.isFunction(r))return r.call(this,n,i);if(us.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=faa(t),t){let i=us.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||eMs(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(u){if(u=faa(u),u){let l=us.findKey(i,u);l&&(!r||eMs(i,i[l],l,r))&&(delete i[l],n=!0)}}return us.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||eMs(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return us.forEach(this,(n,a)=>{let u=us.findKey(i,a);if(u){r[u]=ebo(n),delete r[a];return}let l=t?R1S(a):String(a).trim();l!==a&&delete r[a],r[l]=ebo(n),i[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return us.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&us.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(`
|
|
1696
1696
|
`)}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[xep]=this[xep]={accessors:{}}).accessors,n=this.prototype;function a(u){let l=faa(u);i[l]||(N1S(n,u),i[l]=!0)}return us.isArray(t)?t.forEach(a):a(t),this}};Ybn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);us.reduceDescriptors(Ybn.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});us.freezeMethods(Ybn);var VI=Ybn;function daa(e,t){let r=this||Kbn,i=t||r,n=VI.from(i.headers),a=i.data;return us.forEach(e,function(l){a=l.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function paa(e){return!!(e&&e.__CANCEL__)}function Iep(e,t,r){mp.call(this,e??"canceled",mp.ERR_CANCELED,t,r),this.name="CanceledError"}us.inherits(Iep,mp,{__CANCEL__:!0});var H1e=Iep;function mKt(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new mp("Request failed with status code "+r.status,[mp.ERR_BAD_REQUEST,mp.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function tMs(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function rMs(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function FCi(e,t){return e&&!tMs(t)?rMs(e,t):t}var Xep=vi(Qna(),1),Zep=vi(require("http"),1),kep=vi(require("https"),1),etp=vi(require("util"),1),ttp=vi(uEs(),1),k$r=vi(require("zlib"),1);var LCi="1.7.7";function _aa(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var F1S=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function iMs(e,t,r){let i=r&&r.Blob||NT.classes.Blob,n=_aa(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=F1S.exec(e);if(!a)throw new mp("Invalid URL",mp.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 mp("Blob is not supported",mp.ERR_NOT_SUPPORT);return new i([s],{type:u})}return s}throw new mp("Unsupported protocol "+n,mp.ERR_NOT_SUPPORT)}var UCi=vi(require("stream"),1);var zep=vi(require("stream"),1);var nMs=Symbol("internals"),aMs=class extends zep.default.Transform{constructor(t){t=us.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!us.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[nMs]={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[nMs];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[nMs],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),w=null,E=u,A,q=0;if(a){let D=Date.now();(!n.ts||(q=D-n.ts)>=l)&&(n.ts=D,A=s-n.bytes,n.bytes=A<0?-A:0,q=0),A=s-n.bytes}if(a){if(A<=0)return setTimeout(()=>{O(null,g)},l-q);A<E&&(E=A)}E&&m>E&&m-E>o&&(w=g.subarray(E),g=g.subarray(0,E)),c(g,w?()=>{process.nextTick(O,null,w)}:O)};b(t,function g(O,m){if(O)return i(O);m?b(m,g):i(null)})}},oMs=aMs;var rtp=require("events");var Nep=require("util"),Fep=require("stream");var{asyncIterator:Rep}=Symbol,L1S=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[Rep]?yield*e[Rep]():yield e},tbo=L1S;var U1S=us.ALPHABET.ALPHA_DIGIT+"-_",haa=new Nep.TextEncoder,Msi=`\r
|
|
1697
1697
|
`,V1S=haa.encode(Msi),W1S=2,uMs=class{constructor(t,r){let{escapeName:i}=this.constructor,n=us.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${Msi}`;n?r=haa.encode(String(r).replace(/\r?\n|\r\n?/g,Msi)):a+=`Content-Type: ${r.type||"application/octet-stream"}${Msi}`,this.headers=haa.encode(a+Msi),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+W1S,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;us.isTypedArray(t)?yield t:yield*tbo(t),yield V1S}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},H1S=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+us.generateString(n,U1S)}=r||{};if(!us.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=haa.encode("--"+a+Msi),l=haa.encode("--"+a+"--"+Msi+Msi),d=l.byteLength,s=Array.from(e.entries()).map(([c,b])=>{let g=new uMs(c,b);return d+=g.size,g});d+=u.byteLength*s.length,d=us.toFiniteNumber(d);let o={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(d)&&(o["Content-Length"]=d),t&&t(o),Fep.Readable.from(async function*(){for(let c of s)yield u,yield*c.encode();yield l}())},Lep=H1S;var Uep=vi(require("stream"),1),sMs=class extends Uep.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)}},Vep=sMs;var $1S=(e,t)=>us.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,Wep=$1S;function G1S(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 Hep=G1S;function Q1S(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 $ep=Q1S;var Z$r=(e,t,r=3)=>{let i=0,n=Hep(50,250);return $ep(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)},Xbn=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},Zbn=e=>(...t)=>us.asap(()=>e(...t));var Gep={flush:k$r.default.constants.Z_SYNC_FLUSH,finishFlush:k$r.default.constants.Z_SYNC_FLUSH},J1S={flush:k$r.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:k$r.default.constants.BROTLI_OPERATION_FLUSH},Qep=us.isFunction(k$r.default.createBrotliDecompress),{http:K1S,https:Y1S}=ttp.default,X1S=/https:?/,Jep=NT.protocols.map(e=>e+":"),Kep=(e,[t,r])=>(e.on("end",r).on("error",r),t);function Z1S(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function itp(e,t,r){let i=t;if(!i&&i!==!1){let n=(0,Xep.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){itp(a,t,a.href)}}var k1S=typeof process<"u"&&us.kindOf(process)==="process",eSS=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)}),tSS=({address:e,family:t})=>{if(!us.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},Yep=(e,t)=>tSS(us.isObject(e)?e:{address:e,family:t}),ntp=k1S&&function(t){return eSS(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=Wep(l,Ze=>us.isArray(Ze)?Ze:[Ze]);l=(Ze,Mt,De)=>{we(Ze,Mt,(Te,xt,Ee)=>{if(Te)return De(Te);let It=us.isArray(xt)?xt.map(st=>Yep(st)):[Yep(xt,Ee)];Mt.all?De(Te,It):De(Te,It[0].address,It[0].family)})}}let m=new rtp.EventEmitter,w=()=>{t.cancelToken&&t.cancelToken.unsubscribe(E),t.signal&&t.signal.removeEventListener("abort",E),m.removeAllListeners()};a((we,Ze)=>{b=!0,Ze&&(g=!0,w())});function E(we){m.emit("abort",!we||we.type?new H1e(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 A=FCi(t.baseURL,t.url),q=new URL(A,NT.hasBrowserEnv?NT.origin:void 0),D=q.protocol||Jep[0];if(D==="data:"){let we;if(c!=="GET")return mKt(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{we=iMs(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(Ze){throw mp.from(Ze,mp.ERR_BAD_REQUEST,t)}return s==="text"?(we=we.toString(o),(!o||o==="utf8")&&(we=us.stripBOM(we))):s==="stream"&&(we=UCi.default.Readable.from(we)),mKt(i,n,{data:we,status:200,statusText:"OK",headers:new VI,config:t})}if(Jep.indexOf(D)===-1)return n(new mp("Unsupported protocol "+D,mp.ERR_BAD_REQUEST,t));let C=VI.from(t.headers).normalize();C.set("User-Agent","axios/"+LCi,!1);let{onUploadProgress:R,onDownloadProgress:$}=t,I=t.maxRate,U,H;if(us.isSpecCompliantForm(u)){let we=C.getContentType(/boundary=([-_\w\d]{10,70})/i);u=Lep(u,Ze=>{C.set(Ze)},{tag:`axios-${LCi}-boundary`,boundary:we&&we[1]||void 0})}else if(us.isFormData(u)&&us.isFunction(u.getHeaders)){if(C.set(u.getHeaders()),!C.hasContentLength())try{let we=await etp.default.promisify(u.getLength).call(u);Number.isFinite(we)&&we>=0&&C.setContentLength(we)}catch{}}else if(us.isBlob(u))u.size&&C.setContentType(u.type||"application/octet-stream"),C.setContentLength(u.size||0),u=UCi.default.Readable.from(tbo(u));else if(u&&!us.isStream(u)){if(!Buffer.isBuffer(u))if(us.isArrayBuffer(u))u=Buffer.from(new Uint8Array(u));else if(us.isString(u))u=Buffer.from(u,"utf-8");else return n(new mp("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",mp.ERR_BAD_REQUEST,t));if(C.setContentLength(u.length,!1),t.maxBodyLength>-1&&u.length>t.maxBodyLength)return n(new mp("Request body larger than maxBodyLength limit",mp.ERR_BAD_REQUEST,t))}let k=us.toFiniteNumber(C.getContentLength());us.isArray(I)?(U=I[0],H=I[1]):U=H=I,u&&(R||U)&&(us.isStream(u)||(u=UCi.default.Readable.from(u,{objectMode:!1})),u=UCi.default.pipeline([u,new oMs({maxRate:us.toFiniteNumber(U)})],us.noop),R&&u.on("progress",Kep(u,Xbn(k,Z$r(Zbn(R),!1,3)))));let K;if(t.auth){let we=t.auth.username||"",Ze=t.auth.password||"";K=we+":"+Ze}if(!K&&q.username){let we=q.username,Ze=q.password;K=we+":"+Ze}K&&C.delete("authorization");let te;try{te=NCi(q.pathname+q.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(we){let Ze=new Error(we.message);return Ze.config=t,Ze.url=t.url,Ze.exists=!0,n(Ze)}C.set("Accept-Encoding","gzip, compress, deflate"+(Qep?", br":""),!1);let fe={path:te,method:c,headers:C.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:K,protocol:D,family:d,beforeRedirect:Z1S,beforeRedirects:{}};!us.isUndefined(l)&&(fe.lookup=l),t.socketPath?fe.socketPath=t.socketPath:(fe.hostname=q.hostname.startsWith("[")?q.hostname.slice(1,-1):q.hostname,fe.port=q.port,itp(fe,t.proxy,D+"//"+q.hostname+(q.port?":"+q.port:"")+fe.path));let me,be=X1S.test(fe.protocol);if(fe.agent=be?t.httpsAgent:t.httpAgent,t.transport?me=t.transport:t.maxRedirects===0?me=be?kep.default:Zep.default:(t.maxRedirects&&(fe.maxRedirects=t.maxRedirects),t.beforeRedirect&&(fe.beforeRedirects.config=t.beforeRedirect),me=be?Y1S:K1S),t.maxBodyLength>-1?fe.maxBodyLength=t.maxBodyLength:fe.maxBodyLength=1/0,t.insecureHTTPParser&&(fe.insecureHTTPParser=t.insecureHTTPParser),O=me.request(fe,function(Ze){if(O.destroyed)return;let Mt=[Ze],De=+Ze.headers["content-length"];if($||H){let st=new oMs({maxRate:us.toFiniteNumber(H)});$&&st.on("progress",Kep(st,Xbn(De,Z$r(Zbn($),!0,3)))),Mt.push(st)}let Te=Ze,xt=Ze.req||O;if(t.decompress!==!1&&Ze.headers["content-encoding"])switch((c==="HEAD"||Ze.statusCode===204)&&delete Ze.headers["content-encoding"],(Ze.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":Mt.push(k$r.default.createUnzip(Gep)),delete Ze.headers["content-encoding"];break;case"deflate":Mt.push(new Vep),Mt.push(k$r.default.createUnzip(Gep)),delete Ze.headers["content-encoding"];break;case"br":Qep&&(Mt.push(k$r.default.createBrotliDecompress(J1S)),delete Ze.headers["content-encoding"])}Te=Mt.length>1?UCi.default.pipeline(Mt,us.noop):Mt[0];let Ee=UCi.default.finished(Te,()=>{Ee(),w()}),It={status:Ze.statusCode,statusText:Ze.statusMessage,headers:new VI(Ze.headers),config:t,request:xt};if(s==="stream")It.data=Te,mKt(i,n,It);else{let st=[],ye=0;Te.on("data",function(Ot){st.push(Ot),ye+=Ot.length,t.maxContentLength>-1&&ye>t.maxContentLength&&(g=!0,Te.destroy(),n(new mp("maxContentLength size of "+t.maxContentLength+" exceeded",mp.ERR_BAD_RESPONSE,t,xt)))}),Te.on("aborted",function(){if(g)return;let Ot=new mp("maxContentLength size of "+t.maxContentLength+" exceeded",mp.ERR_BAD_RESPONSE,t,xt);Te.destroy(Ot),n(Ot)}),Te.on("error",function(Ot){O.destroyed||n(mp.from(Ot,null,t,xt))}),Te.on("end",function(){try{let Ot=st.length===1?st[0]:Buffer.concat(st);s!=="arraybuffer"&&(Ot=Ot.toString(o),(!o||o==="utf8")&&(Ot=us.stripBOM(Ot))),It.data=Ot}catch(Ot){return n(mp.from(Ot,null,t,It.request,It))}mKt(i,n,It)})}m.once("abort",st=>{Te.destroyed||(Te.emit("error",st),Te.destroy())})}),m.once("abort",we=>{n(we),O.destroy(we)}),O.on("error",function(Ze){n(mp.from(Ze,null,t,O))}),O.on("socket",function(Ze){Ze.setKeepAlive(!0,1e3*60)}),t.timeout){let we=parseInt(t.timeout,10);if(Number.isNaN(we)){n(new mp("error trying to parse `config.timeout` to int",mp.ERR_BAD_OPTION_VALUE,t,O));return}O.setTimeout(we,function(){if(b)return;let Mt=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",De=t.transitional||Jbn;t.timeoutErrorMessage&&(Mt=t.timeoutErrorMessage),n(new mp(Mt,De.clarifyTimeoutError?mp.ETIMEDOUT:mp.ECONNABORTED,t,O)),E()})}if(us.isStream(u)){let we=!1,Ze=!1;u.on("end",()=>{we=!0}),u.once("error",Mt=>{Ze=!0,O.destroy(Mt)}),u.on("close",()=>{!we&&!Ze&&E(new H1e("Request stream has been aborted",t,O))}),u.pipe(O)}else O.end(u)})};var atp=NT.hasStandardBrowserEnv?function(){let t=NT.navigator&&/(msie|trident)/i.test(NT.navigator.userAgent),r=document.createElement("a"),i;function n(a){let u=a;return t&&(r.setAttribute("href",u),u=r.href),r.setAttribute("href",u),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return i=n(window.location.href),function(u){let l=us.isString(u)?n(u):u;return l.protocol===i.protocol&&l.host===i.host}}():function(){return function(){return!0}}();var otp=NT.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let u=[e+"="+encodeURIComponent(t)];us.isNumber(r)&&u.push("expires="+new Date(r).toGMTString()),us.isString(i)&&u.push("path="+i),us.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 utp=e=>e instanceof VI?{...e}:e;function o8t(e,t){t=t||{};let r={};function i(s,o,c){return us.isPlainObject(s)&&us.isPlainObject(o)?us.merge.call({caseless:c},s,o):us.isPlainObject(o)?us.merge({},o):us.isArray(o)?o.slice():o}function n(s,o,c){if(us.isUndefined(o)){if(!us.isUndefined(s))return i(void 0,s,c)}else return i(s,o,c)}function a(s,o){if(!us.isUndefined(o))return i(void 0,o)}function u(s,o){if(us.isUndefined(o)){if(!us.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)=>n(utp(s),utp(o),!0)};return us.forEach(Object.keys(Object.assign({},e,t)),function(o){let c=d[o]||n,b=c(e[o],t[o],o);us.isUndefined(b)&&c!==l||(r[o]=b)}),r}var rbo=e=>{let t=o8t({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:u,auth:l}=t;t.headers=u=VI.from(u),t.url=NCi(FCi(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(us.isFormData(r)){if(NT.hasStandardBrowserEnv||NT.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(NT.hasStandardBrowserEnv&&(i&&us.isFunction(i)&&(i=i(t)),i||i!==!1&&atp(t.url))){let s=n&&a&&otp.read(a);s&&u.set(n,s)}return t};var rSS=typeof XMLHttpRequest<"u",stp=rSS&&function(e){return new Promise(function(r,i){let n=rbo(e),a=n.data,u=VI.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 w=new XMLHttpRequest;w.open(n.method.toUpperCase(),n.url,!0),w.timeout=n.timeout;function E(){if(!w)return;let q=VI.from("getAllResponseHeaders"in w&&w.getAllResponseHeaders()),C={data:!l||l==="text"||l==="json"?w.responseText:w.response,status:w.status,statusText:w.statusText,headers:q,config:e,request:w};mKt(function($){r($),m()},function($){i($),m()},C),w=null}"onloadend"in w?w.onloadend=E:w.onreadystatechange=function(){!w||w.readyState!==4||w.status===0&&!(w.responseURL&&w.responseURL.indexOf("file:")===0)||setTimeout(E)},w.onabort=function(){w&&(i(new mp("Request aborted",mp.ECONNABORTED,e,w)),w=null)},w.onerror=function(){i(new mp("Network Error",mp.ERR_NETWORK,e,w)),w=null},w.ontimeout=function(){let D=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",C=n.transitional||Jbn;n.timeoutErrorMessage&&(D=n.timeoutErrorMessage),i(new mp(D,C.clarifyTimeoutError?mp.ETIMEDOUT:mp.ECONNABORTED,e,w)),w=null},a===void 0&&u.setContentType(null),"setRequestHeader"in w&&us.forEach(u.toJSON(),function(D,C){w.setRequestHeader(C,D)}),us.isUndefined(n.withCredentials)||(w.withCredentials=!!n.withCredentials),l&&l!=="json"&&(w.responseType=n.responseType),s&&([b,O]=Z$r(s,!0),w.addEventListener("progress",b)),d&&w.upload&&([c,g]=Z$r(d),w.upload.addEventListener("progress",c),w.upload.addEventListener("loadend",g)),(n.cancelToken||n.signal)&&(o=q=>{w&&(i(!q||q.type?new H1e(null,e,w):q),w.abort(),w=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));let A=_aa(n.url);if(A&&NT.protocols.indexOf(A)===-1){i(new mp("Unsupported protocol "+A+":",mp.ERR_BAD_REQUEST,e));return}w.send(a||null)})};var iSS=(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 mp?o:new H1e(o instanceof Error?o.message:o))}},u=t&&setTimeout(()=>{u=null,a(new mp(`timeout ${t} of ms exceeded`,mp.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=()=>us.asap(l),d}},ctp=iSS;var nSS=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},aSS=async function*(e,t){for await(let r of oSS(e))yield*nSS(r,t)},oSS=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()}},cMs=(e,t,r,i)=>{let n=aSS(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 nbo=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",ftp=nbo&&typeof ReadableStream=="function",uSS=nbo&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),dtp=(e,...t)=>{try{return!!e(...t)}catch{return!1}},sSS=ftp&&dtp(()=>{let e=!1,t=new Request(NT.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),ltp=64*1024,lMs=ftp&&dtp(()=>us.isReadableStream(new Response("").body)),ibo={stream:lMs&&(e=>e.body)};nbo&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!ibo[t]&&(ibo[t]=us.isFunction(e[t])?r=>r[t]():(r,i)=>{throw new mp(`Response type '${t}' is not supported`,mp.ERR_NOT_SUPPORT,i)})})})(new Response);var cSS=async e=>{if(e==null)return 0;if(us.isBlob(e))return e.size;if(us.isSpecCompliantForm(e))return(await new Request(NT.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(us.isArrayBufferView(e)||us.isArrayBuffer(e))return e.byteLength;if(us.isURLSearchParams(e)&&(e=e+""),us.isString(e))return(await uSS(e)).byteLength},lSS=async(e,t)=>{let r=us.toFiniteNumber(e.getContentLength());return r??cSS(t)},ptp=nbo&&(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}=rbo(e);s=s?(s+"").toLowerCase():"text";let g=ctp([n,a&&a.toAbortSignal()],u),O,m=g&&g.unsubscribe&&(()=>{g.unsubscribe()}),w;try{if(d&&sSS&&r!=="get"&&r!=="head"&&(w=await lSS(o,i))!==0){let C=new Request(t,{method:"POST",body:i,duplex:"half"}),R;if(us.isFormData(i)&&(R=C.headers.get("content-type"))&&o.setContentType(R),C.body){let[$,I]=Xbn(w,Z$r(Zbn(d)));i=cMs(C.body,ltp,$,I)}}us.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 A=await fetch(O),q=lMs&&(s==="stream"||s==="response");if(lMs&&(l||q&&m)){let C={};["status","statusText","headers"].forEach(U=>{C[U]=A[U]});let R=us.toFiniteNumber(A.headers.get("content-length")),[$,I]=l&&Xbn(R,Z$r(Zbn(l),!0))||[];A=new Response(cMs(A.body,ltp,$,()=>{I&&I(),m&&m()}),C)}s=s||"text";let D=await ibo[us.findKey(ibo,s)||"text"](A,e);return!q&&m&&m(),await new Promise((C,R)=>{mKt(C,R,{data:D,headers:VI.from(A.headers),status:A.status,statusText:A.statusText,config:e,request:O})})}catch(E){throw m&&m(),E&&E.name==="TypeError"&&/fetch/i.test(E.message)?Object.assign(new mp("Network Error",mp.ERR_NETWORK,e,O),{cause:E.cause||E}):mp.from(E,E&&E.code,e,O)}});var fMs={http:ntp,xhr:stp,fetch:ptp};us.forEach(fMs,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var _tp=e=>`- ${e}`,fSS=e=>us.isFunction(e)||e===null||e===!1,abo={getAdapter:e=>{e=us.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,!fSS(r)&&(i=fMs[(u=String(r)).toLowerCase()],i===void 0))throw new mp(`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 :
|
|
@@ -1929,11 +1929,11 @@ ${q}${A}${D}${$Mp.default.cursorHide}`});var ala=vi(Qqi(),1);function i7s(e,t){i
|
|
|
1929
1929
|
Run ${Qs.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
|
|
1930
1930
|
Run ${Qs.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),e0n(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function _7s({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!hAp(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+=`
|
|
1931
1931
|
${await UiD(l.generatorName)} (${l.apiName!=null?"API: "+l.apiName+", ":""}Group: ${l.generatorGroup}) `+Qs.dim(l.currentVersion)+Qs.reset(" \u2192 ")+Qs.green(l.latestVersion);return n+=`
|
|
1932
|
-
`,i?e0n(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function UiD(e){let r=await new _Ap.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 ViD({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await vAp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=toi(o.name,c),g=await RGt({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 vAp({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=toi(s.name,o),b=await RGt({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 vAp({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 q4t({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 bAp(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=Qre(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 aSo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await ViD({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(...bAp(s,d,t.logger));else u.push(...bAp(l.versions,void 0,t.logger))}return u}var pla=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 Wmn=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var Hmn=e=>e!==null&&typeof e=="object";var _la=(...e)=>{for(let t of e)if((!Hmn(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return v7s({},...e)},h7s=(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 oSo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:v7s(e[r]??[],t[r]??[])}var y7s=(e={},t={})=>({beforeRequest:oSo(e,t,"beforeRequest"),beforeRetry:oSo(e,t,"beforeRetry"),afterResponse:oSo(e,t,"afterResponse"),beforeError:oSo(e,t,"beforeError")}),v7s=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(Hmn(n)){for(let[a,u]of Object.entries(n))Hmn(u)&&a in t&&(u=v7s(t[a],u)),t={...t,[a]:u};Hmn(n.hooks)&&(i=y7s(i,n.hooks),t.hooks=i),Hmn(n.headers)&&(r=h7s(r,n.headers),t.headers=r)}return t};var gAp=(()=>{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})(),OAp=typeof globalThis.AbortController=="function",mAp=typeof globalThis.ReadableStream=="function",PAp=typeof globalThis.FormData=="function",uSo=["get","post","put","patch","head","delete"],WiD=()=>{};WiD();var jAp={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},sSo=2147483647,cSo=Symbol("stop"),wAp={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},SAp={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 EAp=e=>uSo.includes(e)?e.toUpperCase():e,HiD=["get","put","head","delete","options","trace"],$iD=[408,413,429,500,502,503,504],GiD=[413,429,503],DAp={limit:2,methods:HiD,statusCodes:$iD,afterStatusCodes:GiD,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},MAp=(e={})=>{if(typeof e=="number")return{...DAp,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{...DAp,...e}};async function b7s(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new Wmn(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function g7s(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 AAp=(e,t)=>{let r={};for(let i in t)!(i in SAp)&&!(i in wAp)&&!(i in e)&&(r[i]=t[i]);return r};var hla=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>sSo)throw new RangeError(`The \`timeout\` option cannot be greater than ${sSo}`);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 pla(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(!mAp)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(jAp))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:h7s(this._input.headers,r.headers),hooks:y7s({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:EAp(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:MAp(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(OAp){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(gAp&&(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);(PAp&&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 Wmn)throw t;if(t instanceof pla){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),sSo);if(this._retryCount<1)throw r;await g7s(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})===cSo)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=AAp(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):b7s(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 O7s=e=>{let t=(r,i)=>hla.create(r,_la(e,i));for(let r of uSo)t[r]=(i,n)=>hla.create(i,_la(e,n,{method:r}));return t.create=r=>O7s(_la(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),O7s(_la(e,r))),t.stop=cSo,t},QiD=O7s(),qAp=QiD;var kAp=vi(ZAp(),1);function S7s(e){let t=(0,kAp.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var Qqp=vi(Gqp(),1),Jqp=vi(Qqi(),1),F7s=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},L7s=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function U7s(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??S7s(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,Qqp.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 qAp(u,{headers:d,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new F7s(e):c}if(t.allVersions)return s;let o=new L7s(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=Jqp.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 mla(e,t){let{version:r}=await U7s(e.toLowerCase(),t);return r}async function kci({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:mla(e.packageName,{version:t?"prerelease":"latest"})}var Kqp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],mSo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=B0.Info;constructor(t){this.ttyAwareLogger=new nSo(t);let r=this.getPackageName(),i=this.getPackageVersion(),n=this.getCliName();(r==null||i==null||n==null)&&this.exitProgram(),this.environment={packageName:r,packageVersion:i,cliName:n}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.56.3"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Qs.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new dte}failWithoutThrowing(t,r){this.didSucceed=!1,eSo({message:t,error:r,logger:this.logger})}async exit(){this._suppressUpgradeMessage||await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await $bn()).flush(),this.exitProgram()}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await yAp({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
1932
|
+
`,i?e0n(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function UiD(e){let r=await new _Ap.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 ViD({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await vAp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=toi(o.name,c),g=await RGt({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 vAp({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=toi(s.name,o),b=await RGt({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 vAp({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 q4t({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 bAp(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=Qre(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 aSo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await ViD({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(...bAp(s,d,t.logger));else u.push(...bAp(l.versions,void 0,t.logger))}return u}var pla=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 Wmn=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var Hmn=e=>e!==null&&typeof e=="object";var _la=(...e)=>{for(let t of e)if((!Hmn(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return v7s({},...e)},h7s=(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 oSo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:v7s(e[r]??[],t[r]??[])}var y7s=(e={},t={})=>({beforeRequest:oSo(e,t,"beforeRequest"),beforeRetry:oSo(e,t,"beforeRetry"),afterResponse:oSo(e,t,"afterResponse"),beforeError:oSo(e,t,"beforeError")}),v7s=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(Hmn(n)){for(let[a,u]of Object.entries(n))Hmn(u)&&a in t&&(u=v7s(t[a],u)),t={...t,[a]:u};Hmn(n.hooks)&&(i=y7s(i,n.hooks),t.hooks=i),Hmn(n.headers)&&(r=h7s(r,n.headers),t.headers=r)}return t};var gAp=(()=>{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})(),OAp=typeof globalThis.AbortController=="function",mAp=typeof globalThis.ReadableStream=="function",PAp=typeof globalThis.FormData=="function",uSo=["get","post","put","patch","head","delete"],WiD=()=>{};WiD();var jAp={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},sSo=2147483647,cSo=Symbol("stop"),wAp={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},SAp={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 EAp=e=>uSo.includes(e)?e.toUpperCase():e,HiD=["get","put","head","delete","options","trace"],$iD=[408,413,429,500,502,503,504],GiD=[413,429,503],DAp={limit:2,methods:HiD,statusCodes:$iD,afterStatusCodes:GiD,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},MAp=(e={})=>{if(typeof e=="number")return{...DAp,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{...DAp,...e}};async function b7s(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new Wmn(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function g7s(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 AAp=(e,t)=>{let r={};for(let i in t)!(i in SAp)&&!(i in wAp)&&!(i in e)&&(r[i]=t[i]);return r};var hla=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>sSo)throw new RangeError(`The \`timeout\` option cannot be greater than ${sSo}`);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 pla(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(!mAp)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(jAp))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:h7s(this._input.headers,r.headers),hooks:y7s({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:EAp(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:MAp(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(OAp){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(gAp&&(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);(PAp&&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 Wmn)throw t;if(t instanceof pla){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),sSo);if(this._retryCount<1)throw r;await g7s(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})===cSo)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=AAp(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):b7s(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 O7s=e=>{let t=(r,i)=>hla.create(r,_la(e,i));for(let r of uSo)t[r]=(i,n)=>hla.create(i,_la(e,n,{method:r}));return t.create=r=>O7s(_la(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),O7s(_la(e,r))),t.stop=cSo,t},QiD=O7s(),qAp=QiD;var kAp=vi(ZAp(),1);function S7s(e){let t=(0,kAp.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var Qqp=vi(Gqp(),1),Jqp=vi(Qqi(),1),F7s=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},L7s=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function U7s(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??S7s(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,Qqp.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 qAp(u,{headers:d,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new F7s(e):c}if(t.allVersions)return s;let o=new L7s(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=Jqp.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 mla(e,t){let{version:r}=await U7s(e.toLowerCase(),t);return r}async function kci({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:mla(e.packageName,{version:t?"prerelease":"latest"})}var Kqp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],mSo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=B0.Info;constructor(t){this.ttyAwareLogger=new nSo(t);let r=this.getPackageName(),i=this.getPackageVersion(),n=this.getCliName();(r==null||i==null||n==null)&&this.exitProgram(),this.environment={packageName:r,packageVersion:i,cliName:n}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.56.5"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Qs.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new dte}failWithoutThrowing(t,r){this.didSucceed=!1,eSo({message:t,error:r,logger:this.logger})}async exit(){this._suppressUpgradeMessage||await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await $bn()).flush(),this.exitProgram()}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await yAp({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
1933
1933
|
`)||(r+=`
|
|
1934
1934
|
`),this.logger.info(r))}catch{}}async exitIfFailed(){this.didSucceed||await this.exit()}exitProgram(){process.exit(this.didSucceed?0:1)}longestWorkspaceName;registerWorkspaces(t){let r=Nus(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 ola(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 dte}finally{i.finish()}return n}async instrumentPostHogEvent(t){(await $bn()).sendEvent(t)}logger=CHr(this.log.bind(this));constructTaskInitForWorkspace(t){let r=Yqp(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?Yqp(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=Kqp[this.numTasks++%Kqp.length],u=Qs.hex(a)(n);return{...this.constructTaskInit(),logPrefix:u}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===dC.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}])}logImmediately(t){let r=t.filter(i=>vai.indexOf(i.level)>=vai.indexOf(this.logLevel));this.ttyAwareLogger.log(r,{includeDebugInfo:this.logLevel===B0.Debug})}_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 kci({cliEnvironment:this.environment,includePreReleases:t}),i=Qre(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await aSo({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){return await X3s({message:t,default:r})}async getInput(t){return await Z3s({message:t.message,default:t.default})}};function Yqp(e){return`[${e}]:`}var _Hp=require("fs/promises");function Jre({breadcrumbs:e=[],title:t,subtitle:r}){let i=[];return e.length>0&&i.push(Qs.blue(e.join(" -> "))),i.push(t),r!=null&&i.push(Qs.dim(r)),i.join(`
|
|
1935
1935
|
`)}var E5p=require("fs/promises");var F8t=class e{generatorsConfiguration;workspaceName;cliVersion;absoluteFilePath;changelog;type=e.Type;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 cSe=class extends F8t{definition;sources;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 Pla=class{context;constructor(t){this.context=t}};var PSo=class e{files={};directories={};getAllFiles(){let t={},r=(i,n)=>{for(let[u,l]of Object.entries(i.files)){let d=n!=null?ry.of(`${n}${X2t}${u}`):ry.of(u);t[d]=l}let a=Object.keys(i.directories).sort();for(let u of a){let l=n!=null?`${n}${X2t}${u}`:u,d=i.directories[u];r(d,l)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split(X2t))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[ry.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 Yxi=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new PSo,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 o$r(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"]))ZnD(i)&&t.push(i.header);let r=this.getVersionHeader();return r!=null&&t.push(r),new Set(t)}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??vg((UCe(r)+"/"+XAi(r,{stripExtension:!0})).replaceAll("__package__","root"));if(t===ry.of(T3))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[n]=XKa(UCe(Zdn.of(`/${t}`)),Zdn.of(`/${r}`)),n;let a=this.getOrCreateFile(t);return a.imports==null&&(a.imports={}),a.imports[n]=XKa(UCe(Zdn.of(`/${t}`)),Zdn.of(`/${r}`)),n}addType(t,{name:r,schema:i}){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=>u1e(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=sR(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:sR(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:sR(r,u.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===W1?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 ZnD(e){return e?.header!=null}var Kre={openapi:e=>({...e,type:"openapi",_visit:function(t){return Kre._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return Kre._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 Xmn={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return Xmn._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var k8={basic:e=>({...e,type:"basic",_visit:function(t){return k8._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return k8._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return k8._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return k8._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return k8._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 Q0={primitive:e=>({value:e,type:"primitive",_visit:function(t){return Q0._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Q0._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return Q0._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return Q0._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return Q0._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return Q0._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Q0._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return Q0._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 i_={int:e=>({value:e,type:"int",_visit:function(t){return i_._visit(this,t)}}),int64:e=>({value:e,type:"int64",_visit:function(t){return i_._visit(this,t)}}),uint:e=>({value:e,type:"uint",_visit:function(t){return i_._visit(this,t)}}),uint64:e=>({value:e,type:"uint64",_visit:function(t){return i_._visit(this,t)}}),float:e=>({value:e,type:"float",_visit:function(t){return i_._visit(this,t)}}),double:e=>({value:e,type:"double",_visit:function(t){return i_._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return i_._visit(this,t)}}),datetime:e=>({value:e,type:"datetime",_visit:function(t){return i_._visit(this,t)}}),date:e=>({value:e,type:"date",_visit:function(t){return i_._visit(this,t)}}),base64:e=>({value:e,type:"base64",_visit:function(t){return i_._visit(this,t)}}),boolean:e=>({value:e,type:"boolean",_visit:function(t){return i_._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 Zmn={boolean:e=>({value:e,type:"boolean",_visit:function(t){return Zmn._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return Zmn._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 eli={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return eli._visit(this,t)}}),undiscriminated:e=>({value:e,type:"undiscriminated",_visit:function(t){return eli._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 $U={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated",_visit:(e,t)=>{switch(e){case $U.GenerallyAvailable:return t.generallyAvailable();case $U.Beta:return t.beta();case $U.Deprecated:return t.deprecated();default:return t._other()}}};var qIe={cursor:e=>({...e,type:"cursor",_visit(t){return qIe._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit(t){return qIe._visit(this,t)}}),custom:e=>({...e,type:"custom",_visit(t){return qIe._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 GGr={language:e=>({...e,type:"language",_visit:function(t){return GGr._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return GGr._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 GU={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 GU.Curl:return t.curl();case GU.Python:return t.python();case GU.Javascript:return t.javascript();case GU.Typescript:return t.typescript();case GU.Go:return t.go();case GU.Ruby:return t.ruby();case GU.Csharp:return t.csharp();case GU.Java:return t.java();case GU.Js:return t.js();case GU.Node:return t.node();case GU.Ts:return t.ts();case GU.Nodets:return t.nodets();case GU.Golang:return t.golang();case GU.Dotnet:return t.dotnet();case GU.Jvm:return t.jvm();default:return t._other()}}};var L8t={unknown:e=>({value:e,type:"unknown",_visit:function(t){return L8t._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return L8t._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 TIe={withStreaming:e=>({...e,type:"withStreaming",_visit:function(t){return TIe._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit:function(t){return TIe._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 W$={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE",_visit:(e,t)=>{switch(e){case W$.Get:return t.get();case W$.Post:return t.post();case W$.Put:return t.put();case W$.Patch:return t.patch();case W$.Delete:return t.delete();case W$.Head:return t.head();case W$.Options:return t.options();case W$.Trace:return t.trace();default:return t._other()}}};var tli={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return tli._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return tli._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return tli._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 CIe={file:e=>({...e,type:"file",_visit:function(t){return CIe._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return CIe._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 Yre={file:e=>({...e,type:"file",_visit:function(t){return Yre._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return Yre._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return Yre._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return Yre._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return Yre._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return Yre._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"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var py={primitive:e=>({...e,type:"primitive",_visit:function(t){return py._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return py._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return py._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return py._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return py._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return py._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return py._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return py._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return py._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return py._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return py._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 sj={int:e=>({...e,type:"int",_visit:function(t){return sj._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return sj._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return sj._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return sj._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return sj._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return sj._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return sj._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return sj._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return sj._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return sj._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return sj._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 YB={boolean:e=>({value:e,type:"boolean",_visit:function(t){return YB._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return YB._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 QGr={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return QGr._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return QGr._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 lSe={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return lSe._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return lSe._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return lSe._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 XB={file:e=>({...e,type:"file",_visit:function(t){return XB._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return XB._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return XB._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return XB._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return XB._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return XB._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"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var El={primitive:e=>({...e,type:"primitive",_visit:function(t){return El._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return El._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return El._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return El._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return El._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return El._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return El._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return El._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return El._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return El._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return El._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 PY={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return PY._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return PY._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 Jd={int:e=>({...e,type:"int",_visit:function(t){return Jd._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return Jd._visit(this,t)}}),uint:e=>({...e,type:"uint",_visit:function(t){return Jd._visit(this,t)}}),uint64:e=>({...e,type:"uint64",_visit:function(t){return Jd._visit(this,t)}}),float:e=>({...e,type:"float",_visit:function(t){return Jd._visit(this,t)}}),double:e=>({...e,type:"double",_visit:function(t){return Jd._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return Jd._visit(this,t)}}),datetime:e=>({...e,type:"datetime",_visit:function(t){return Jd._visit(this,t)}}),date:e=>({...e,type:"date",_visit:function(t){return Jd._visit(this,t)}}),base64:e=>({...e,type:"base64",_visit:function(t){return Jd._visit(this,t)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return Jd._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={};Io(ev,{AllOfPropertyConflict:()=>OPn,ArraySchema:()=>zDo,ArraySchemaWithExample:()=>lEo,Availability:()=>CSo,Base64WithExample:()=>aEo,BasicSecurityScheme:()=>ISo,BearerSecurityScheme:()=>zSo,BooleanSchema:()=>qDo,BooleanWithExample:()=>oEo,CasingOverrides:()=>FSo,CommonProperty:()=>HDo,CommonPropertyWithExample:()=>gEo,CursorPagination:()=>hDo,CustomCodeSample:()=>pDo,CustomCodeSampleLanguage:()=>lDo,CustomCodeSampleSdk:()=>dDo,CustomPagination:()=>vDo,DateWithExample:()=>nEo,DatetimeWithExample:()=>iEo,DiscriminatedOneOfSchema:()=>VDo,DiscriminatedOneOfSchemaWithExample:()=>vEo,DoubleSchema:()=>MDo,DoubleWithExample:()=>tEo,Encoding:()=>TSo,Endpoint:()=>bDo,EndpointExample:()=>hPn,EndpointResponseExample:()=>cDo,EndpointSdkName:()=>fYt,EndpointWithExample:()=>DTp,EnumSchema:()=>rPn,EnumSchemaWithExample:()=>sEo,EnumValue:()=>nli,ErrorExample:()=>nDo,FernExample:()=>oDo,FileResponse:()=>lPn,FileSchema:()=>XSo,FloatWithExample:()=>eEo,FullEndpointExample:()=>_Do,FullExample:()=>BA,FullObjectExample:()=>GSo,FullOneOfExample:()=>JSo,GlobalHeader:()=>CDo,Header:()=>oli,HeaderExample:()=>_Pn,HeaderSecurityScheme:()=>RSo,HeaderWithExample:()=>cli,HttpEndpointServer:()=>dPn,HttpError:()=>aDo,HttpErrorWithExample:()=>KDo,HttpMethod:()=>aPn,IdempotencyHeader:()=>BDo,Int64WithExample:()=>XDo,IntSchema:()=>DDo,IntWithExample:()=>YDo,JsonRequest:()=>tDo,JsonRequestWithExample:()=>GDo,JsonResponse:()=>fPn,JsonResponseWithExample:()=>jPn,KeyValuePair:()=>QSo,LiteralExample:()=>$So,LiteralSchema:()=>gPn,LiteralSchemaValue:()=>xDo,LongSchema:()=>EDo,MapSchema:()=>RDo,MapSchemaWithExample:()=>fEo,MultipartRequest:()=>cPn,MultipartRequestProperty:()=>eDo,MultipartRequestPropertyEncoding:()=>kSo,MultipartSchema:()=>ZSo,NamedFullExample:()=>pYt,Namespace:()=>LSo,NamespaceId:()=>HSo,NullableSchema:()=>FDo,NullableSchemaWithExample:()=>pEo,OauthSecurityScheme:()=>VSo,ObjectProperty:()=>UDo,ObjectPropertyConflictInfo:()=>mPn,ObjectPropertyWithExample:()=>yEo,ObjectSchema:()=>IDo,ObjectSchemaWithExample:()=>_Eo,OctetStreamRequest:()=>sPn,OffsetPagination:()=>yDo,OneOfSchema:()=>LDo,OneOfSchemaWithExample:()=>hEo,OpenApiIntermediateRepresentation:()=>wTp,OpenApiSource:()=>ESo,OptionalSchema:()=>NDo,OptionalSchemaWithExample:()=>dEo,Pagination:()=>yPn,PathParameter:()=>oPn,PathParameterExample:()=>uDo,PathParameterWithExample:()=>$Do,PrimitiveExample:()=>nPn,PrimitiveSchema:()=>sli,PrimitiveSchemaValue:()=>TDo,PrimitiveSchemaValueWithExample:()=>uEo,PrimitiveSchemaWithExample:()=>wPn,PropertyKey:()=>iPn,ProtobufEncoding:()=>qSo,ProtobufSource:()=>MSo,QueryParameter:()=>uPn,QueryParameterExample:()=>pPn,QueryParameterWithExample:()=>PPn,QuerySecurityScheme:()=>NSo,ReferencedSchema:()=>dYt,Request:()=>rDo,RequestWithExample:()=>QDo,Response:()=>iDo,ResponseWithExample:()=>JDo,Schema:()=>EO,SchemaId:()=>jY,SchemaWithExample:()=>vM,Schemas:()=>SDo,SdkGroup:()=>USo,SdkGroupInfo:()=>KSo,SdkGroupName:()=>ali,SecurityScheme:()=>WSo,SecuritySchemeId:()=>xSo,Server:()=>Dla,Source:()=>ASo,StatusCode:()=>sYt,StreamingResponseExample:()=>sDo,StringSchema:()=>ADo,StringSchemaWithExample:()=>rEo,SupportedSdkLanguage:()=>fDo,Tag:()=>BSo,TagId:()=>wY,Tags:()=>YSo,TextResponse:()=>uli,Uint64WithExample:()=>kDo,UintWithExample:()=>ZDo,UnDiscriminatedOneOfSchema:()=>WDo,UnDiscriminatedOneOfSchemaWithExample:()=>bEo,UnknownSchemaWithExample:()=>cEo,Webhook:()=>gDo,WebhookExampleCall:()=>bPn,WebhookHttpMethod:()=>vPn,WebhookWithExample:()=>ETp,WebsocketChannel:()=>wDo,WebsocketHandshake:()=>ODo,WebsocketHandshakeWithExample:()=>STp,WebsocketMessageExample:()=>PDo,WebsocketServer:()=>mDo,WebsocketSessionExample:()=>jDo,WithAvailability:()=>uh,WithDescription:()=>Of,WithEncoding:()=>Xre,WithInline:()=>XD,WithName:()=>Xb,WithNamespace:()=>lYt,WithSdkGroupName:()=>DO,WithSource:()=>ny,WithStatusCode:()=>cYt,WithTitle:()=>SO,commons:()=>G7s,example:()=>Q7s,finalIr:()=>J7s,parseIr:()=>K7s});var G7s={};Io(G7s,{BasicSecurityScheme:()=>ISo,BearerSecurityScheme:()=>zSo,Encoding:()=>TSo,HeaderSecurityScheme:()=>RSo,Namespace:()=>LSo,NamespaceId:()=>HSo,OauthSecurityScheme:()=>VSo,OpenApiSource:()=>ESo,ProtobufEncoding:()=>qSo,ProtobufSource:()=>MSo,QuerySecurityScheme:()=>NSo,SchemaId:()=>jY,SdkGroup:()=>USo,SdkGroupName:()=>ali,SecurityScheme:()=>WSo,SecuritySchemeId:()=>xSo,Server:()=>Dla,Source:()=>ASo,StatusCode:()=>sYt,Tag:()=>BSo,TagId:()=>wY,WithAvailability:()=>uh,WithDescription:()=>Of,WithEncoding:()=>Xre,WithInline:()=>XD,WithName:()=>Xb,WithNamespace:()=>lYt,WithSdkGroupName:()=>DO,WithSource:()=>ny,WithStatusCode:()=>cYt,WithTitle:()=>SO});var At={};Io(At,{JsonError:()=>kmn,ParseError:()=>ePn,any:()=>fTp,bigint:()=>Zqp,boolean:()=>dTp,booleanLiteral:()=>lTp,date:()=>kqp,discriminant:()=>mTp,enum_:()=>wSo,getObjectLikeUtils:()=>U8t,getObjectUtils:()=>Xxi,getSchemaUtils:()=>CA,isProperty:()=>ili,lazy:()=>eTp,lazyObject:()=>uTp,list:()=>DSo,number:()=>pTp,object:()=>SSo,objectWithoutOptionalProperties:()=>oTp,optional:()=>V7s,property:()=>rTp,record:()=>vTp,set:()=>bTp,string:()=>_Tp,stringLiteral:()=>cTp,transform:()=>W7s,undiscriminatedUnion:()=>OTp,union:()=>jTp,unknown:()=>hTp,withParsedProperties:()=>$7s});var FP={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 yM(e,t){return`Expected ${t}. Received ${knD(e)}.`}function knD(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 e5(e){return{...e,json:Xqp(e.json),parse:Xqp(e.parse)}}function Xqp(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(`
|
|
1936
|
-
`)),{ok:!0,value:t}):i}}function jSo(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var kmn=class e extends Error{errors;constructor(t){super(t.map(jSo).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var ePn=class e extends Error{errors;constructor(t){super(t.map(jSo).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function CA(e){return{optional:()=>V7s(e),transform:t=>W7s(e,t),parseOrThrow:(t,r)=>{let i=e.parse(t,r);if(i.ok)return i.value;throw new ePn(i.errors)},jsonOrThrow:(t,r)=>{let i=e.json(t,r);if(i.ok)return i.value;throw new kmn(i.errors)}}}function V7s(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:()=>FP.OPTIONAL};return{...t,...CA(t)}}function W7s(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,...CA(r)}}function Zqp(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:yM(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:yM(t,"bigint")}]},getType:()=>FP.BIGINT};return{...e5(e),...CA(e)}}var eaD=/^([+-]?\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 kqp(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:yM(t,"string")}]}:eaD.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:yM(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:yM(t,"Date object")}]},getType:()=>FP.DATE};return{...e5(e),...CA(e)}}function H$(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...e5(r),...CA(r)}}}function wSo(e){let t=new Set(e);return H$(FP.ENUM,(i,{allowUnrecognizedEnumValues:n,breadcrumbsPrefix:a=[]}={})=>typeof i!="string"?{ok:!1,errors:[{path:a,message:yM(i,"string")}]}:!t.has(i)&&!n?{ok:!1,errors:[{path:a,message:yM(i,"enum")}]}:{ok:!0,value:i})()}function eTp(e){let t=H7s(e);return{...t,...CA(t)}}function H7s(e){return{parse:(t,r)=>tPn(e).parse(t,r),json:(t,r)=>tPn(e).json(t,r),getType:()=>tPn(e).getType()}}function tPn(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function jla(e){return Object.entries(e)}function wla(e,t){let r=new Set(t);return Object.entries(e).reduce((i,[n,a])=>(r.has(n)&&(i[n]=a),i),{})}function rli(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 Sla(e){return Object.keys(e)}function tTp(e,t){let r=[],i=[];for(let n of e)t(n)?r.push(n):i.push(n);return[r,i]}function U8t(e){return{withParsedProperties:t=>$7s(e,t)}}function $7s(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(!rli(i))return{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:yM(i,"object")}]};let a=new Set(Object.keys(t)),u=wla(i,Object.keys(i).filter(l=>!a.has(l)));return e.json(u,n)},getType:()=>e.getType()};return{...r,...CA(r),...U8t(r)}}function rTp(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function ili(e){return e.isProperty}function SSo(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,i])=>ili(i)?i.rawKey:r),_getParsedProperties:()=>Sla(e),parse:(r,i)=>{let n={},a=[];for(let[u,l]of jla(e)){let d=ili(l)?l.rawKey:u,s=ili(l)?l.valueSchema:l,o={rawKey:d,parsedKey:u,valueSchema:s};n[d]=o,aTp(s)&&a.push(d)}return iTp({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 jla(e)){let l=ili(u)?u.valueSchema:u;aTp(l)&&n.push(a)}return iTp({value:r,requiredKeys:n,getProperty:a=>{let u=e[a];if(u!=null)return ili(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:()=>FP.OBJECT};return{...e5(t),...CA(t),...U8t(t),...Xxi(t)}}function iTp({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:i="fail",skipValidation:n=!1,breadcrumbsPrefix:a=[]}){if(!rli(e))return{ok:!1,errors:[{path:a,message:yM(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 Xxi(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(i,n)=>nTp({extensionKeys:t._getRawProperties(),value:i,transformBase:a=>e.parse(a,n),transformExtension:a=>t.parse(a,n)}),json:(i,n)=>nTp({extensionKeys:t._getParsedProperties(),value:i,transformBase:a=>e.json(a,n),transformExtension:a=>t.json(a,n)}),getType:()=>FP.OBJECT};return{...r,...CA(r),...U8t(r),...Xxi(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:()=>FP.OBJECT};return{...t,...CA(t),...U8t(t),...Xxi(t)}}}}function nTp({extensionKeys:e,value:t,transformBase:r,transformExtension:i}){let n=new Set(e),[a,u]=tTp(Sla(t),s=>n.has(s)),l=r(wla(t,u)),d=i(wla(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 aTp(e){return!taD(e)}function taD(e){switch(e.getType()){case FP.ANY:case FP.UNKNOWN:case FP.OPTIONAL:return!0;default:return!1}}function oTp(e){return SSo(e)}function uTp(e){let t={...H7s(e),_getRawProperties:()=>tPn(e)._getRawProperties(),_getParsedProperties:()=>tPn(e)._getParsedProperties()};return{...t,...CA(t),...U8t(t),...Xxi(t)}}function DSo(e){let t={parse:(r,i)=>sTp(r,(n,a)=>e.parse(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,i)=>sTp(r,(n,a)=>e.json(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>FP.LIST};return{...e5(t),...CA(t)}}function sTp(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:yM(e,"list"),path:[]}]}}function cTp(e){return H$(FP.STRING_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:yM(r,`"${e}"`)}]})()}function lTp(e){return H$(FP.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:yM(r,`${e.toString()}`)}]})()}var fTp=H$(FP.ANY,e=>({ok:!0,value:e}));var dTp=H$(FP.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:yM(e,"boolean")}]});var pTp=H$(FP.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:yM(e,"number")}]});var _Tp=H$(FP.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:yM(e,"string")}]});var hTp=H$(FP.UNKNOWN,e=>({ok:!0,value:e}));function vTp(e,t){let r={parse:(i,n)=>yTp({value:i,isKeyNumeric:e.getType()===FP.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)=>yTp({value:i,isKeyNumeric:e.getType()===FP.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:()=>FP.RECORD};return{...e5(r),...CA(r)}}function yTp({value:e,isKeyNumeric:t,transformKey:r,transformValue:i,breadcrumbsPrefix:n=[]}){return rli(e)?jla(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:yM(e,"object")}]}}function bTp(e){let t=DSo(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:yM(i,"Set")}]},getType:()=>FP.SET};return{...e5(r),...CA(r)}}function OTp(e){let t={parse:(r,i)=>gTp((n,a)=>n.parse(r,a),e,i),json:(r,i)=>gTp((n,a)=>n.json(r,a),e,i),getType:()=>FP.UNDISCRIMINATED_UNION};return{...e5(t),...CA(t)}}function gTp(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 mTp(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function jTp(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,i=typeof e=="string"?e:e.parsedDiscriminant,n=wSo(Sla(t)),a={parse:(u,l)=>PTp({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)=>PTp({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:()=>FP.UNION};return{...e5(a),...CA(a),...U8t(a)}}function PTp({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:i,getAdditionalPropertiesSchema:n,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:u,breadcrumbsPrefix:l=[]}){if(!rli(e))return{ok:!1,errors:[{path:l,message:yM(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 SO=At.objectWithoutOptionalProperties({title:At.string().optional()});var ESo=At.objectWithoutOptionalProperties({file:At.string()});var MSo=At.objectWithoutOptionalProperties({file:At.string()});var ASo=At.union("type",{openapi:ESo,protobuf:MSo}).transform({transform:e=>{switch(e.type){case"openapi":return Kre.openapi(e);case"protobuf":return Kre.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var ny=At.objectWithoutOptionalProperties({source:ASo.optional()});var qSo=At.objectWithoutOptionalProperties({typeName:At.string()});var TSo=At.union("type",{protobuf:qSo}).transform({transform:e=>{switch(e.type){case"protobuf":return Xmn.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var Xre=At.objectWithoutOptionalProperties({encoding:TSo.optional()});var Of=At.objectWithoutOptionalProperties({description:At.string().optional()});var CSo=At.enum_(["GenerallyAvailable","Beta","Deprecated"]);var uh=At.objectWithoutOptionalProperties({availability:CSo.optional()});var sYt=At.number();var cYt=At.objectWithoutOptionalProperties({statusCode:sYt.optional()});var Xb=At.objectWithoutOptionalProperties({nameOverride:At.string().optional(),generatedName:At.string()});var XD=At.objectWithoutOptionalProperties({inline:At.boolean().optional()});var jY=At.string();var wY=At.string();var BSo=At.objectWithoutOptionalProperties({id:wY}).extend(Of);var xSo=At.string();var ISo=At.objectWithoutOptionalProperties({usernameVariableName:At.string().optional(),usernameEnvVar:At.string().optional(),passwordVariableName:At.string().optional(),passwordEnvVar:At.string().optional()});var zSo=At.objectWithoutOptionalProperties({tokenVariableName:At.string().optional(),tokenEnvVar:At.string().optional()});var RSo=At.objectWithoutOptionalProperties({headerName:At.string(),prefix:At.string().optional(),headerVariableName:At.string().optional(),headerEnvVar:At.string().optional()});var NSo=At.objectWithoutOptionalProperties({queryParameterName:At.string()});var FSo=At.objectWithoutOptionalProperties({snake:At.string().optional(),camel:At.string().optional(),screamingSnake:At.string().optional(),pascal:At.string().optional()});var nli=At.objectWithoutOptionalProperties({nameOverride:At.string().optional(),generatedName:At.string(),value:At.string(),casing:FSo.optional()}).extend(Of).extend(uh);var LSo=At.objectWithoutOptionalProperties({type:At.stringLiteral("namespace"),name:At.string()});var USo=At.undiscriminatedUnion([At.string(),LSo]);var ali=At.list(USo);var DO=At.objectWithoutOptionalProperties({groupName:ali.optional()});var rPn=At.objectWithoutOptionalProperties({default:nli.optional(),values:At.list(nli)}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(ny).extend(SO).extend(XD);var VSo=At.objectWithoutOptionalProperties({scopesEnum:rPn.optional()});var WSo=At.union("type",{basic:ISo,bearer:zSo,header:RSo,query:NSo,oauth:VSo}).transform({transform:e=>{switch(e.type){case"basic":return k8.basic(e);case"bearer":return k8.bearer(e);case"header":return k8.header(e);case"query":return k8.query(e);case"oauth":return k8.oauth(e);default:return e}},untransform:({_visit:e,...t})=>t});var Dla=At.objectWithoutOptionalProperties({name:At.string().optional(),url:At.string(),audiences:At.list(At.string()).optional()}).extend(Of);var HSo=At.string();var lYt=At.objectWithoutOptionalProperties({namespace:At.string().optional()});var Q7s={};Io(Q7s,{FullExample:()=>BA,FullObjectExample:()=>GSo,FullOneOfExample:()=>JSo,KeyValuePair:()=>QSo,LiteralExample:()=>$So,PrimitiveExample:()=>nPn,PropertyKey:()=>iPn});var iPn=At.string();var nPn=At.union("type",{int:At.object({value:At.number()}),int64:At.object({value:At.number()}),uint:At.object({value:At.number()}),uint64:At.object({value:At.number()}),float:At.object({value:At.number()}),double:At.object({value:At.number()}),string:At.object({value:At.string()}),datetime:At.object({value:At.string()}),date:At.object({value:At.string()}),base64:At.object({value:At.string()}),boolean:At.object({value:At.boolean()})}).transform({transform:e=>{switch(e.type){case"int":return i_.int(e.value);case"int64":return i_.int64(e.value);case"uint":return i_.uint(e.value);case"uint64":return i_.uint64(e.value);case"float":return i_.float(e.value);case"double":return i_.double(e.value);case"string":return i_.string(e.value);case"datetime":return i_.datetime(e.value);case"date":return i_.date(e.value);case"base64":return i_.base64(e.value);case"boolean":return i_.boolean(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var $So=At.union("type",{boolean:At.object({value:At.boolean()}),string:At.object({value:At.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return Zmn.boolean(e.value);case"string":return Zmn.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var BA=At.union("type",{primitive:At.object({value:nPn}),object:At.lazyObject(()=>GSo),array:At.object({value:At.list(At.lazy(()=>BA))}),map:At.object({value:At.list(At.lazyObject(()=>QSo))}),enum:At.object({value:At.string()}),literal:At.object({value:$So}),oneOf:At.object({value:At.lazy(()=>JSo)}),unknown:At.object({value:At.lazy(()=>BA)})}).transform({transform:e=>{switch(e.type){case"primitive":return Q0.primitive(e.value);case"object":return Q0.object(e);case"array":return Q0.array(e.value);case"map":return Q0.map(e.value);case"enum":return Q0.enum(e.value);case"literal":return Q0.literal(e.value);case"oneOf":return Q0.oneOf(e.value);case"unknown":return Q0.unknown(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var GSo=At.objectWithoutOptionalProperties({properties:At.record(iPn,At.lazy(()=>BA))});var QSo=At.objectWithoutOptionalProperties({key:nPn,value:At.lazy(()=>BA)});var JSo=At.union("type",{discriminated:At.object({value:At.record(iPn,At.lazy(()=>BA))}),undiscriminated:At.object({value:At.lazy(()=>BA)})}).transform({transform:e=>{switch(e.type){case"discriminated":return eli.discriminated(e.value);case"undiscriminated":return eli.undiscriminated(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var J7s={};Io(J7s,{AllOfPropertyConflict:()=>OPn,ArraySchema:()=>zDo,Availability:()=>CSo,BooleanSchema:()=>qDo,CasingOverrides:()=>FSo,CommonProperty:()=>HDo,CursorPagination:()=>hDo,CustomCodeSample:()=>pDo,CustomCodeSampleLanguage:()=>lDo,CustomCodeSampleSdk:()=>dDo,CustomPagination:()=>vDo,DiscriminatedOneOfSchema:()=>VDo,DoubleSchema:()=>MDo,Endpoint:()=>bDo,EndpointExample:()=>hPn,EndpointResponseExample:()=>cDo,EndpointSdkName:()=>fYt,EnumSchema:()=>rPn,EnumValue:()=>nli,ErrorExample:()=>nDo,FernExample:()=>oDo,FileResponse:()=>lPn,FileSchema:()=>XSo,FullEndpointExample:()=>_Do,GlobalHeader:()=>CDo,Header:()=>oli,HeaderExample:()=>_Pn,HttpEndpointServer:()=>dPn,HttpError:()=>aDo,HttpMethod:()=>aPn,IdempotencyHeader:()=>BDo,IntSchema:()=>DDo,JsonRequest:()=>tDo,JsonResponse:()=>fPn,LiteralSchema:()=>gPn,LiteralSchemaValue:()=>xDo,LongSchema:()=>EDo,MapSchema:()=>RDo,MultipartRequest:()=>cPn,MultipartRequestProperty:()=>eDo,MultipartRequestPropertyEncoding:()=>kSo,MultipartSchema:()=>ZSo,NullableSchema:()=>FDo,ObjectProperty:()=>UDo,ObjectPropertyConflictInfo:()=>mPn,ObjectSchema:()=>IDo,OctetStreamRequest:()=>sPn,OffsetPagination:()=>yDo,OneOfSchema:()=>LDo,OpenApiIntermediateRepresentation:()=>wTp,OptionalSchema:()=>NDo,Pagination:()=>yPn,PathParameter:()=>oPn,PathParameterExample:()=>uDo,PrimitiveSchema:()=>sli,PrimitiveSchemaValue:()=>TDo,QueryParameter:()=>uPn,QueryParameterExample:()=>pPn,ReferencedSchema:()=>dYt,Request:()=>rDo,Response:()=>iDo,Schema:()=>EO,Schemas:()=>SDo,SdkGroupInfo:()=>KSo,StreamingResponseExample:()=>sDo,StringSchema:()=>ADo,SupportedSdkLanguage:()=>fDo,Tags:()=>YSo,TextResponse:()=>uli,UnDiscriminatedOneOfSchema:()=>WDo,Webhook:()=>gDo,WebhookExampleCall:()=>bPn,WebhookHttpMethod:()=>vPn,WebsocketChannel:()=>wDo,WebsocketHandshake:()=>ODo,WebsocketMessageExample:()=>PDo,WebsocketServer:()=>mDo,WebsocketSessionExample:()=>jDo});var KSo=At.objectWithoutOptionalProperties({summary:At.string().optional(),description:At.string().optional()});var YSo=At.objectWithoutOptionalProperties({tagsById:At.record(wY,BSo),orderedTagIds:At.list(wY).optional()});var aPn=At.enum_(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS","TRACE"]);var oPn=At.objectWithoutOptionalProperties({name:At.string(),schema:At.lazy(()=>EO),variableReference:At.string().optional(),parameterNameOverride:At.string().optional()}).extend(Of).extend(uh).extend(ny);var uPn=At.objectWithoutOptionalProperties({name:At.string(),schema:At.lazy(()=>EO),parameterNameOverride:At.string().optional()}).extend(Of).extend(uh).extend(ny);var oli=At.objectWithoutOptionalProperties({name:At.string(),schema:At.lazy(()=>EO),env:At.string().optional(),parameterNameOverride:At.string().optional()}).extend(Of).extend(uh).extend(ny);var fYt=At.objectWithoutOptionalProperties({groupName:ali,methodName:At.string()});var sPn=At.objectWithoutOptionalProperties({}).extend(Of).extend(ny);var XSo=At.objectWithoutOptionalProperties({isOptional:At.boolean(),isArray:At.boolean()});var ZSo=At.union("type",{file:XSo,json:At.object({value:At.lazy(()=>EO)})}).transform({transform:e=>{switch(e.type){case"file":return CIe.file(e);case"json":return CIe.json(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var kSo=At.enum_(["json","form"]);var eDo=At.objectWithoutOptionalProperties({key:At.string(),schema:ZSo,contentType:At.string().optional(),exploded:At.boolean().optional(),encoding:kSo.optional()}).extend(Of);var cPn=At.objectWithoutOptionalProperties({name:At.string().optional(),properties:At.list(eDo)}).extend(Of).extend(ny);var tDo=At.objectWithoutOptionalProperties({schema:At.lazy(()=>EO),contentType:At.string().optional(),additionalProperties:At.boolean()}).extend(Of).extend(ny);var rDo=At.union("type",{octetStream:sPn,multipart:cPn,json:tDo}).transform({transform:e=>{switch(e.type){case"octetStream":return tli.octetStream(e);case"multipart":return tli.multipart(e);case"json":return tli.json(e);default:return e}},untransform:({_visit:e,...t})=>t});var lPn=At.objectWithoutOptionalProperties({}).extend(Of).extend(ny).extend(cYt);var fPn=At.objectWithoutOptionalProperties({schema:At.lazy(()=>EO),responseProperty:At.string().optional()}).extend(Of).extend(ny).extend(cYt);var uli=At.objectWithoutOptionalProperties({}).extend(Of).extend(ny).extend(cYt);var iDo=At.union("type",{file:lPn,json:fPn,text:uli,streamingSse:fPn,streamingText:uli,streamingJson:fPn}).transform({transform:e=>{switch(e.type){case"file":return Yre.file(e);case"json":return Yre.json(e);case"text":return Yre.text(e);case"streamingSse":return Yre.streamingSse(e);case"streamingText":return Yre.streamingText(e);case"streamingJson":return Yre.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var nDo=At.objectWithoutOptionalProperties({name:At.string().optional(),description:At.string().optional(),example:At.lazy(()=>BA)});var aDo=At.objectWithoutOptionalProperties({schema:At.lazy(()=>EO).optional(),examples:At.list(nDo).optional()}).extend(Of).extend(Xb).extend(ny);var dPn=At.objectWithoutOptionalProperties({name:At.string().optional(),url:At.string().optional(),audiences:At.list(At.string()).optional()});var oDo=At.unknown();var uDo=At.objectWithoutOptionalProperties({name:At.string(),parameterNameOverride:At.string().optional(),value:At.lazy(()=>BA)});var pPn=At.objectWithoutOptionalProperties({name:At.string(),value:At.lazy(()=>BA)});var _Pn=At.objectWithoutOptionalProperties({name:At.string(),value:At.lazy(()=>BA)});var sDo=At.objectWithoutOptionalProperties({sse:At.boolean(),events:At.list(At.lazy(()=>BA))});var cDo=At.union("type",{withStreaming:sDo,withoutStreaming:At.object({value:At.lazy(()=>BA)})}).transform({transform:e=>{switch(e.type){case"withStreaming":return TIe.withStreaming(e);case"withoutStreaming":return TIe.withoutStreaming(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var lDo=At.objectWithoutOptionalProperties({name:At.string().optional(),language:At.string(),code:At.string(),install:At.string().optional()}).extend(Of);var fDo=At.enum_(["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm"]);var dDo=At.objectWithoutOptionalProperties({name:At.string().optional(),sdk:fDo,code:At.string()}).extend(Of);var pDo=At.union("type",{language:lDo,sdk:dDo}).transform({transform:e=>{switch(e.type){case"language":return GGr.language(e);case"sdk":return GGr.sdk(e);default:return e}},untransform:({_visit:e,...t})=>t});var _Do=At.objectWithoutOptionalProperties({name:At.string().optional(),pathParameters:At.list(uDo).optional(),queryParameters:At.list(pPn).optional(),headers:At.list(_Pn).optional(),request:At.lazy(()=>BA).optional(),response:cDo.optional(),codeSamples:At.list(pDo)}).extend(Of);var hPn=At.union("type",{unknown:At.object({value:oDo}),full:_Do}).transform({transform:e=>{switch(e.type){case"unknown":return L8t.unknown(e.value);case"full":return L8t.full(e);default:return e}},untransform:({_visit:e,...t})=>t});var hDo=At.objectWithoutOptionalProperties({cursor:At.string(),nextCursor:At.property("next_cursor",At.string()),results:At.string()});var yDo=At.objectWithoutOptionalProperties({offset:At.string(),results:At.string(),step:At.string().optional(),hasNextPage:At.string().optional()});var vDo=At.objectWithoutOptionalProperties({results:At.string()});var yPn=At.union("type",{cursor:hDo,offset:yDo,custom:vDo}).transform({transform:e=>{switch(e.type){case"cursor":return qIe.cursor(e);case"offset":return qIe.offset(e);case"custom":return qIe.custom(e);default:return e}},untransform:({_visit:e,...t})=>t});var bDo=At.objectWithoutOptionalProperties({authed:At.boolean(),internal:At.boolean().optional(),idempotent:At.boolean().optional(),method:aPn,audiences:At.list(At.string()),path:At.string(),summary:At.string().optional(),operationId:At.string().optional(),tags:At.list(wY),pathParameters:At.list(oPn),queryParameters:At.list(uPn),headers:At.list(oli),sdkName:fYt.optional(),generatedRequestName:At.string(),requestNameOverride:At.string().optional(),request:rDo.optional(),response:iDo.optional(),errors:At.record(sYt,aDo),servers:At.list(dPn),examples:At.list(hPn),pagination:yPn.optional()}).extend(Of).extend(uh).extend(ny).extend(lYt);var vPn=At.enum_(["GET","POST"]);var bPn=At.objectWithoutOptionalProperties({name:At.string().optional(),payload:At.lazy(()=>BA)}).extend(Of);var gDo=At.objectWithoutOptionalProperties({sdkName:fYt.optional(),method:vPn,summary:At.string().optional(),operationId:At.string(),tags:At.list(wY),headers:At.list(oli),generatedPayloadName:At.string(),payload:At.lazy(()=>EO),examples:At.list(bPn)}).extend(Of).extend(ny).extend(lYt);var ODo=At.objectWithoutOptionalProperties({queryParameters:At.list(uPn),headers:At.list(oli),pathParameters:At.list(oPn)});var mDo=At.objectWithoutOptionalProperties({name:At.string(),url:At.string()});var PDo=At.objectWithoutOptionalProperties({messageType:At.string(),payload:At.lazy(()=>BA)}).extend(Of);var jDo=At.objectWithoutOptionalProperties({name:At.string().optional(),queryParameters:At.list(pPn).optional(),headers:At.list(_Pn).optional(),messages:At.list(PDo)}).extend(Of);var wDo=At.objectWithoutOptionalProperties({audiences:At.list(At.string()),path:At.string(),groupName:ali,summary:At.string().optional(),handshake:ODo,publish:At.lazy(()=>EO).optional(),subscribe:At.lazy(()=>EO).optional(),servers:At.list(mDo),examples:At.list(jDo)}).extend(Of).extend(ny);var SDo=At.objectWithoutOptionalProperties({rootSchemas:At.record(jY,At.lazy(()=>EO)),namespacedSchemas:At.record(HSo,At.record(jY,At.lazy(()=>EO)))});var DDo=At.objectWithoutOptionalProperties({default:At.number().optional(),minimum:At.number().optional(),maximum:At.number().optional(),exclusiveMinimum:At.boolean().optional(),exclusiveMaximum:At.boolean().optional(),multipleOf:At.number().optional()});var EDo=At.objectWithoutOptionalProperties({default:At.number().optional()});var MDo=At.objectWithoutOptionalProperties({default:At.number().optional(),minimum:At.number().optional(),maximum:At.number().optional(),exclusiveMinimum:At.boolean().optional(),exclusiveMaximum:At.boolean().optional(),multipleOf:At.number().optional()});var ADo=At.objectWithoutOptionalProperties({default:At.string().optional(),pattern:At.string().optional(),format:At.string().optional(),minLength:At.number().optional(),maxLength:At.number().optional()});var qDo=At.objectWithoutOptionalProperties({default:At.boolean().optional()});var TDo=At.union("type",{int:DDo,int64:EDo,uint:At.object({}),uint64:At.object({}),float:At.object({}),double:MDo,string:ADo,datetime:At.object({}),date:At.object({}),base64:At.object({}),boolean:qDo}).transform({transform:e=>{switch(e.type){case"int":return sj.int(e);case"int64":return sj.int64(e);case"uint":return sj.uint();case"uint64":return sj.uint64();case"float":return sj.float();case"double":return sj.double(e);case"string":return sj.string(e);case"datetime":return sj.datetime();case"date":return sj.date();case"base64":return sj.base64();case"boolean":return sj.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var sli=At.objectWithoutOptionalProperties({schema:TDo}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(SO);var CDo=At.objectWithoutOptionalProperties({header:At.string(),name:At.string().optional(),optional:At.boolean().optional(),env:At.string().optional(),schema:At.lazy(()=>EO).optional()});var BDo=At.objectWithoutOptionalProperties({header:At.string(),name:At.string().optional(),env:At.string().optional(),schema:At.lazy(()=>EO).optional()});var wTp=At.objectWithoutOptionalProperties({apiVersion:At.unknown().optional(),title:At.string().optional(),description:At.string().optional(),basePath:At.string().optional(),servers:At.list(Dla),websocketServers:At.list(Dla),groups:At.record(At.string(),KSo),tags:YSo,hasEndpointsMarkedInternal:At.boolean(),endpoints:At.list(bDo),webhooks:At.list(gDo),channels:At.record(At.string(),wDo),groupedSchemas:SDo,variables:At.record(At.string(),sli),nonRequestReferencedSchemas:At.set(jY),securitySchemes:At.record(xSo,WSo),globalHeaders:At.list(CDo).optional(),idempotencyHeaders:At.list(BDo).optional()});var dYt=At.objectWithoutOptionalProperties({schema:jY}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(ny).extend(SO);var xDo=At.union("type",{boolean:At.object({value:At.boolean()}),string:At.object({value:At.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return YB.boolean(e.value);case"string":return YB.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var gPn=At.objectWithoutOptionalProperties({value:xDo}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(SO);var EO=At.union("type",{primitive:sli,object:At.lazyObject(()=>IDo),array:At.lazyObject(()=>zDo),map:At.lazyObject(()=>RDo),optional:At.lazyObject(()=>NDo),enum:rPn,reference:dYt,literal:gPn,oneOf:At.object({value:At.lazy(()=>LDo)}),nullable:At.lazyObject(()=>FDo),unknown:Xb}).transform({transform:e=>{switch(e.type){case"primitive":return py.primitive(e);case"object":return py.object(e);case"array":return py.array(e);case"map":return py.map(e);case"optional":return py.optional(e);case"enum":return py.enum(e);case"reference":return py.reference(e);case"literal":return py.literal(e);case"oneOf":return py.oneOf(e.value);case"nullable":return py.nullable(e);case"unknown":return py.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var OPn=At.objectWithoutOptionalProperties({propertyKey:At.string(),allOfSchemaIds:At.list(jY),conflictingTypeSignatures:At.boolean()});var IDo=At.objectWithoutOptionalProperties({allOf:At.list(dYt),properties:At.list(At.lazyObject(()=>UDo)),allOfPropertyConflicts:At.list(OPn),additionalProperties:At.boolean()}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(ny).extend(SO).extend(XD);var mPn=At.objectWithoutOptionalProperties({differentSchema:At.boolean()});var UDo=At.objectWithoutOptionalProperties({key:At.string(),schema:At.lazy(()=>EO),readonly:At.boolean().optional(),writeonly:At.boolean().optional(),conflict:At.record(jY,mPn),generatedName:At.string(),nameOverride:At.string().optional(),audiences:At.list(At.string())}).extend(uh);var zDo=At.objectWithoutOptionalProperties({value:At.lazy(()=>EO)}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(SO).extend(XD);var RDo=At.objectWithoutOptionalProperties({key:sli,value:At.lazy(()=>EO)}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(Xre).extend(SO).extend(XD);var NDo=At.objectWithoutOptionalProperties({value:At.lazy(()=>EO)}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(SO).extend(XD);var FDo=At.objectWithoutOptionalProperties({value:At.lazy(()=>EO)}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(SO).extend(XD);var LDo=At.union("type",{discriminated:At.lazyObject(()=>VDo),undiscriminated:At.lazyObject(()=>WDo)}).transform({transform:e=>{switch(e.type){case"discriminated":return QGr.discriminated(e);case"undiscriminated":return QGr.undiscriminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var VDo=At.objectWithoutOptionalProperties({discriminantProperty:At.string(),commonProperties:At.list(At.lazyObject(()=>HDo)),schemas:At.record(At.string(),At.lazy(()=>EO))}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(Xre).extend(ny).extend(SO).extend(XD);var HDo=At.objectWithoutOptionalProperties({key:At.string(),schema:At.lazy(()=>EO)});var WDo=At.objectWithoutOptionalProperties({schemas:At.list(At.lazy(()=>EO))}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(Xre).extend(ny).extend(SO).extend(XD);var K7s={};Io(K7s,{ArraySchemaWithExample:()=>lEo,Base64WithExample:()=>aEo,BooleanWithExample:()=>oEo,CommonPropertyWithExample:()=>gEo,DateWithExample:()=>nEo,DatetimeWithExample:()=>iEo,DiscriminatedOneOfSchemaWithExample:()=>vEo,DoubleWithExample:()=>tEo,EndpointWithExample:()=>DTp,EnumSchemaWithExample:()=>sEo,FloatWithExample:()=>eEo,HeaderWithExample:()=>cli,HttpErrorWithExample:()=>KDo,Int64WithExample:()=>XDo,IntWithExample:()=>YDo,JsonRequestWithExample:()=>GDo,JsonResponseWithExample:()=>jPn,MapSchemaWithExample:()=>fEo,NamedFullExample:()=>pYt,NullableSchemaWithExample:()=>pEo,ObjectPropertyWithExample:()=>yEo,ObjectSchemaWithExample:()=>_Eo,OneOfSchemaWithExample:()=>hEo,OptionalSchemaWithExample:()=>dEo,PathParameterWithExample:()=>$Do,PrimitiveSchemaValueWithExample:()=>uEo,PrimitiveSchemaWithExample:()=>wPn,QueryParameterWithExample:()=>PPn,RequestWithExample:()=>QDo,ResponseWithExample:()=>JDo,SchemaWithExample:()=>vM,StringSchemaWithExample:()=>rEo,Uint64WithExample:()=>kDo,UintWithExample:()=>ZDo,UnDiscriminatedOneOfSchemaWithExample:()=>bEo,UnknownSchemaWithExample:()=>cEo,WebhookWithExample:()=>ETp,WebsocketHandshakeWithExample:()=>STp});var pYt=At.objectWithoutOptionalProperties({name:At.string().optional(),value:At.unknown()}).extend(Of);var PPn=At.objectWithoutOptionalProperties({name:At.string(),schema:At.lazy(()=>vM),parameterNameOverride:At.string().optional()}).extend(Of).extend(uh).extend(ny);var cli=At.objectWithoutOptionalProperties({name:At.string(),schema:At.lazy(()=>vM),env:At.string().optional(),parameterNameOverride:At.string().optional()}).extend(Of).extend(uh).extend(ny);var STp=At.objectWithoutOptionalProperties({queryParameters:At.list(PPn),headers:At.list(cli)});var $Do=At.objectWithoutOptionalProperties({name:At.string(),schema:At.lazy(()=>vM),variableReference:At.string().optional(),parameterNameOverride:At.string().optional()}).extend(Of).extend(uh).extend(ny);var GDo=At.objectWithoutOptionalProperties({schema:At.lazy(()=>vM),contentType:At.string().optional(),fullExamples:At.list(pYt).optional(),additionalProperties:At.boolean()}).extend(Of).extend(ny);var QDo=At.union("type",{octetStream:sPn,multipart:cPn,json:GDo}).transform({transform:e=>{switch(e.type){case"octetStream":return lSe.octetStream(e);case"multipart":return lSe.multipart(e);case"json":return lSe.json(e);default:return e}},untransform:({_visit:e,...t})=>t});var jPn=At.objectWithoutOptionalProperties({schema:At.lazy(()=>vM),responseProperty:At.string().optional(),fullExamples:At.list(pYt).optional()}).extend(Of).extend(ny).extend(cYt);var JDo=At.union("type",{file:lPn,json:jPn,text:uli,streamingSse:jPn,streamingText:uli,streamingJson:jPn}).transform({transform:e=>{switch(e.type){case"file":return XB.file(e);case"json":return XB.json(e);case"text":return XB.text(e);case"streamingSse":return XB.streamingSse(e);case"streamingText":return XB.streamingText(e);case"streamingJson":return XB.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var KDo=At.objectWithoutOptionalProperties({statusCode:sYt,schema:At.lazy(()=>vM),fullExamples:At.list(pYt).optional()}).extend(Of).extend(Xb).extend(ny);var DTp=At.objectWithoutOptionalProperties({authed:At.boolean(),internal:At.boolean().optional(),idempotent:At.boolean().optional(),method:aPn,audiences:At.list(At.string()),path:At.string(),summary:At.string().optional(),operationId:At.string().optional(),tags:At.list(wY),pathParameters:At.list($Do),queryParameters:At.list(PPn),headers:At.list(cli),sdkName:fYt.optional(),generatedRequestName:At.string(),requestNameOverride:At.string().optional(),request:QDo.optional(),response:JDo.optional(),errors:At.record(sYt,KDo),servers:At.list(dPn),examples:At.list(hPn),pagination:yPn.optional()}).extend(Of).extend(uh).extend(ny).extend(lYt);var ETp=At.objectWithoutOptionalProperties({sdkName:fYt.optional(),method:vPn,summary:At.string().optional(),operationId:At.string(),tags:At.list(wY),headers:At.list(cli),generatedPayloadName:At.string(),payload:At.lazy(()=>vM),examples:At.list(bPn)}).extend(Of).extend(ny).extend(lYt);var YDo=At.objectWithoutOptionalProperties({default:At.number().optional(),minimum:At.number().optional(),maximum:At.number().optional(),exclusiveMinimum:At.boolean().optional(),exclusiveMaximum:At.boolean().optional(),multipleOf:At.number().optional(),example:At.number().optional()});var XDo=At.objectWithoutOptionalProperties({default:At.number().optional(),example:At.number().optional()});var ZDo=At.objectWithoutOptionalProperties({default:At.number().optional(),example:At.number().optional()});var kDo=At.objectWithoutOptionalProperties({default:At.number().optional(),example:At.number().optional()});var eEo=At.objectWithoutOptionalProperties({example:At.number().optional()});var tEo=At.objectWithoutOptionalProperties({default:At.number().optional(),minimum:At.number().optional(),maximum:At.number().optional(),exclusiveMinimum:At.boolean().optional(),exclusiveMaximum:At.boolean().optional(),multipleOf:At.number().optional(),example:At.number().optional()});var rEo=At.objectWithoutOptionalProperties({default:At.string().optional(),pattern:At.string().optional(),format:At.string().optional(),minLength:At.number().optional(),maxLength:At.number().optional(),example:At.string().optional()});var iEo=At.objectWithoutOptionalProperties({example:At.string().optional()});var nEo=At.objectWithoutOptionalProperties({example:At.string().optional()});var aEo=At.objectWithoutOptionalProperties({example:At.string().optional()});var oEo=At.objectWithoutOptionalProperties({default:At.boolean().optional(),example:At.boolean().optional()});var uEo=At.union("type",{int:YDo,int64:XDo,uint:ZDo,uint64:kDo,float:eEo,double:tEo,string:rEo,datetime:iEo,date:nEo,base64:aEo,boolean:oEo}).transform({transform:e=>{switch(e.type){case"int":return Jd.int(e);case"int64":return Jd.int64(e);case"uint":return Jd.uint(e);case"uint64":return Jd.uint64(e);case"float":return Jd.float(e);case"double":return Jd.double(e);case"string":return Jd.string(e);case"datetime":return Jd.datetime(e);case"date":return Jd.date(e);case"base64":return Jd.base64(e);case"boolean":return Jd.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var wPn=At.objectWithoutOptionalProperties({schema:uEo}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(SO);var sEo=At.objectWithoutOptionalProperties({default:nli.optional(),values:At.list(nli),example:At.string().optional()}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(ny).extend(SO).extend(XD);var cEo=At.objectWithoutOptionalProperties({example:At.unknown()}).extend(DO).extend(Xb).extend(Of).extend(uh).extend(SO);var vM=At.union("type",{primitive:wPn,object:At.lazyObject(()=>_Eo),array:At.lazyObject(()=>lEo),map:At.lazyObject(()=>fEo),optional:At.lazyObject(()=>dEo),enum:sEo,reference:dYt,literal:gPn,oneOf:At.object({value:At.lazy(()=>hEo)}),nullable:At.lazyObject(()=>pEo),unknown:cEo}).transform({transform:e=>{switch(e.type){case"primitive":return El.primitive(e);case"object":return El.object(e);case"array":return El.array(e);case"map":return El.map(e);case"optional":return El.optional(e);case"enum":return El.enum(e);case"reference":return El.reference(e);case"literal":return El.literal(e);case"oneOf":return El.oneOf(e.value);case"nullable":return El.nullable(e);case"unknown":return El.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var lEo=At.objectWithoutOptionalProperties({value:At.lazy(()=>vM),example:At.list(At.unknown()).optional()}).extend(DO).extend(Xb).extend(Of).extend(uh).extend(SO).extend(XD);var fEo=At.objectWithoutOptionalProperties({key:wPn,value:At.lazy(()=>vM),example:At.unknown().optional()}).extend(DO).extend(Xb).extend(Of).extend(uh).extend(Xre).extend(SO).extend(XD);var dEo=At.objectWithoutOptionalProperties({value:At.lazy(()=>vM)}).extend(DO).extend(Xb).extend(Of).extend(uh).extend(SO).extend(XD);var pEo=At.objectWithoutOptionalProperties({value:At.lazy(()=>vM)}).extend(DO).extend(Xb).extend(Of).extend(uh).extend(SO).extend(XD);var _Eo=At.objectWithoutOptionalProperties({allOf:At.list(dYt),properties:At.list(At.lazyObject(()=>yEo)),allOfPropertyConflicts:At.list(OPn),fullExamples:At.list(pYt).optional(),additionalProperties:At.boolean()}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(ny).extend(SO).extend(XD);var yEo=At.objectWithoutOptionalProperties({key:At.string(),schema:At.lazy(()=>vM),readonly:At.boolean().optional(),writeonly:At.boolean().optional(),audiences:At.list(At.string()),conflict:At.record(jY,mPn),nameOverride:At.string().optional(),generatedName:At.string()}).extend(uh);var hEo=At.union("type",{discriminated:At.lazyObject(()=>vEo),undiscriminated:At.lazyObject(()=>bEo)}).transform({transform:e=>{switch(e.type){case"discriminated":return PY.discriminated(e);case"undiscriminated":return PY.undiscriminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var vEo=At.objectWithoutOptionalProperties({discriminantProperty:At.string(),commonProperties:At.list(At.lazyObject(()=>gEo)),schemas:At.record(At.string(),At.lazy(()=>vM))}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(Xre).extend(ny).extend(SO).extend(XD);var gEo=At.objectWithoutOptionalProperties({key:At.string(),schema:At.lazy(()=>vM)});var bEo=At.objectWithoutOptionalProperties({schemas:At.list(At.lazy(()=>vM))}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(Xre).extend(ny).extend(SO).extend(XD);var MTp=/^(\d+)/,SPn=/^[a-zA-Z][a-zA-Z0-9_]*$/,ATp={"<":"LESS_THAN",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL_TO","<=":"LESS_THAN_OR_EQUAL_TO","!=":"NOT_EQUALS","=":"EQUAL_TO","==":"EQUAL_TO","*":"ALL","":"EMPTY",'""':"EMPTY_STRING","-":"HYPHEN","|":"PIPE",".":"DOT","/":"SLASH"};function lli(e){let t=["zero","one","two","three","four","five","six","seven","eight","nine"],r=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],i=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"];if(e<0||e>9999)return;if(e<10)return t[e];if(e<20)return r[e-10];if(e<100){let u=Math.floor(e/10),l=e%10;return l===0?i[u]:`${i[u]}_${t[l]}`}if(e<1e3){let u=Math.floor(e/100),l=e%100;return l===0?`${t[u]}_hundred`:`${t[u]}_hundred_${lli(l)}`}let n=Math.floor(e/1e3),a=e%1e3;return a===0?`${t[n]}_thousand`:`${t[n]}_thousand_${lli(a)}`}function Ela(e){let t=e.match(MTp);if(t&&t[0]!=null){let r=t[0],i=e.substring(r.length),n=parseFloat(r);if(!isNaN(n)&&isFinite(n)){let a=lli(n);return i.length>0?`${a}_${i}`:a}}}function DPn(e){let t=Ela(e),r=ATp[e];return t!=null?q3(vg(t)):r??(e.toLowerCase()==="n/a"?"NOT_APPLICABLE":q3(vg(e)))}function Zre(e,t){return e.type==="primitive"&&t.type==="primitive"?qTp(e.schema,t.schema):e.type==="enum"&&t.type==="enum"?raD(e.values,t.values):e.type==="array"&&t.type==="array"?Zre(e.value,t.value):e.type==="unknown"&&t.type==="unknown"?!0:e.type==="reference"&&t.type==="reference"?e.schema===t.schema:e.type==="optional"&&t.type==="optional"?Zre(e.value,t.value):e.type==="oneOf"&&t.type==="oneOf"?iaD(e.value,t.value):e.type==="object"&&t.type==="object"?naD(e,t):e.type==="map"&&t.type==="map"?qTp(e.key.schema,t.key.schema)&&Zre(e.value,t.value):e.type==="literal"&&t.type==="literal"?e.value===t.value:!1}function qTp(e,t){return e.type===t.type}function raD(e,t){let r=new Set(...e.map(n=>n.value)),i=new Set(...t.map(n=>n.value));return u1e(r,i)}function iaD(e,t){return e.type==="discriminated"&&t.type==="discriminated"?e.discriminantProperty===t.discriminantProperty&&Object.keys(e.schemas).length===Object.keys(t.schemas).length&&Object.entries(e.schemas).every(([r,i])=>{let n=t.schemas[r];return n==null?!1:Zre(i,n)}):e.type==="undiscriminated"&&t.type==="undiscriminated"?e.schemas.length===t.schemas.length&&e.schemas.every((r,i)=>{let n=t.schemas[i];return n==null?!1:Zre(r,n)}):!1}function naD(e,t){if(Object.keys(e.properties).length!==Object.keys(t.properties).length)return!1;let r=Object.fromEntries(e.properties.map(i=>[i.key,i.schema]));return Object.entries(t.properties).every(([i,n])=>{let a=r[i];return a==null?!1:Zre(a,n.schema)})}var a2;(function(e){e[e.Channel=0]="Channel",e[e.Endpoint=1]="Endpoint",e[e.Request=2]="Request",e[e.Webhook=3]="Webhook"})(a2||(a2={}));var OEo=class{logger;taskContext;ir;builder;environmentOverrides;authOverrides;globalHeaderOverrides;detectGlobalHeaders;objectQueryParameters;respectReadonlySchemas;respectNullableSchemas;onlyIncludeReferencedSchemas;inlinePathParameters;enableUniqueErrorsPerEndpoint;defaultServerName=void 0;unknownSchema=new Set;referencedSchemaIds;endpointMethod;state=new Set;constructor({taskContext:t,ir:r,options:i,environmentOverrides:n,globalHeaderOverrides:a,authOverrides:u}){this.logger=t.logger,this.taskContext=t,this.ir=r,this.environmentOverrides=n,this.authOverrides=u,this.globalHeaderOverrides=a,this.detectGlobalHeaders=i?.detectGlobalHeaders??!0,this.objectQueryParameters=i?.objectQueryParameters??!1,this.respectReadonlySchemas=i?.respectReadonlySchemas??!1,this.respectNullableSchemas=i?.respectNullableSchemas??!1,this.onlyIncludeReferencedSchemas=i?.onlyIncludeReferencedSchemas??!1,this.inlinePathParameters=i?.inlinePathParameters??!1,this.referencedSchemaIds=i?.onlyIncludeReferencedSchemas?new Set:void 0,this.enableUniqueErrorsPerEndpoint=i?.enableUniqueErrorsPerEndpoint??!1,this.builder=new Yxi(this.enableUniqueErrorsPerEndpoint),r.title!=null&&this.builder.setDisplayName({displayName:r.title});let l={};if(!this.enableUniqueErrorsPerEndpoint)for(let d of r.endpoints)for(let[s,o]of Object.entries(d.errors)){let c=parseInt(s),b=l[c];b==null&&o.schema!=null?l[c]=o.schema:b!=null&&o.schema!=null&&Zre(b,o.schema)||this.unknownSchema.add(c)}}getReferencedSchemaIds(){if(this.referencedSchemaIds!=null)return Array.from(this.referencedSchemaIds)}getSchema(t,r){return r==null?this.ir.groupedSchemas.rootSchemas[t]:this.ir.groupedSchemas.namespacedSchemas[r]?.[t]}getDefaultServerName(){return this.defaultServerName}setDefaultServerName(t){this.defaultServerName=t}isErrorUnknownSchema(t){return this.unknownSchema.has(t)}getEndpointMethod(){return this.endpointMethod}setEndpointMethod(t){this.endpointMethod=t}unsetEndpointMethod(){this.endpointMethod=void 0}isInState(t){return this.state.has(t)}setInState(t){this.state.add(t)}unsetInState(t){this.state.delete(t)}shouldMarkSchemaAsReferenced(){return this.onlyIncludeReferencedSchemas&&this.isInAnyState(a2.Channel,a2.Endpoint,a2.Webhook)}markSchemaAsReferenced(t,r){switch(t.type){case"primitive":return;case"object":this.markObjectSchemaAsReferenced(t,r);return;case"array":this.markSchemaAsReferenced(t.value,r);return;case"map":this.markSchemaAsReferenced(t.value,r);return;case"optional":this.markSchemaAsReferenced(t.value,r);return;case"reference":this.markSchemaIdAsReferenced(t.schema,r);return;case"oneOf":this.markOneofSchemaAsReferenced(t.value,r);return;case"nullable":this.markSchemaAsReferenced(t.value,r);return;case"enum":return;case"literal":return;case"unknown":return;default:Ko(t)}}markObjectSchemaAsReferenced(t,r){for(let i of t.allOf)this.markSchemaIdAsReferenced(i.schema,r);for(let i of t.properties)this.markSchemaAsReferenced(i.schema,r)}markOneofSchemaAsReferenced(t,r){switch(t.type){case"discriminated":for(let i of Object.values(t.schemas))this.markSchemaAsReferenced(i,r);return;case"undiscriminated":for(let i of t.schemas)this.markSchemaAsReferenced(i,r);return;default:Ko(t)}}markSchemaIdAsReferenced(t,r){if(this.referencedSchemaIds!=null&&!this.referencedSchemaIds.has(t)){this.referencedSchemaIds.add(t);let i=this.getSchema(t,r);i!=null&&this.markSchemaAsReferenced(i,r)}}isInAnyState(...t){return t.some(r=>this.isInState(r))}};function kx(e){switch(e){case $U.Deprecated:return"deprecated";case $U.Beta:return"pre-release";case $U.GenerallyAvailable:return"generally-available";default:return}}function aaD(e){let t=e.find(i=>typeof i=="object"&&i.type==="namespace"),r=e.filter(i=>typeof i=="string"||i.type!=="namespace");return t?[t,...r]:r}function TTp(e){let t=e?aaD(e):void 0;if(t==null||t.length===0)return TAi;let r=[];for(let[i,n]of t.entries())if(typeof n=="string")r.push(vg(n));else if(typeof n=="object")switch(n.type){case"namespace":{i<t.length-1?r.push(vg(n.name)):r.push(n.name,TAi);break}default:Ko(n.type)}else Ko(n);return r.join("/")}function EPn(e){return ry.of(`${TTp(e)}.yml`)}function Y7s({sdkName:e,namespaceOverride:t}){let r;return e==null||e.groupName.length===0&&t==null?TAi:(t!=null?r=[{type:"namespace",name:t},...e.groupName.filter(i=>typeof i=="string"||i.type!=="namespace")]:r=e.groupName,TTp(r))}function CTp({sdkName:e,namespaceOverride:t}){return ry.of(`${Y7s({sdkName:e,namespaceOverride:t})}.yml`)}function BTp({location:e,namespaceOverride:t}){return t!=null?sR(ry.of(t),e):e}function mEo(e){switch(e.type){case"protobuf":return{proto:{type:e.typeName}};default:Ko(e.type)}}function MPn(e){switch(e.type){case"object":case"enum":case"array":case"map":case"reference":case"literal":case"optional":case"nullable":case"primitive":return e.groupName??void 0;case"oneOf":return e.value.groupName??void 0;case"unknown":return;default:Ko(e)}}function bM(e){return typeof e=="string"?e:e.type}function APn(e){if(typeof e!="string")return e.docs}function Mla(e){if(typeof e!="string")return e.default}function X7s(e){if(typeof e!="string")return e.validation}var oaD=-2147483648,uaD=2147483647,saD=-17976931348623157e292,caD=17976931348623157e292;function I0({schema:e,fileContainingReference:t,declarationFile:r=t,context:i,namespace:n,declarationDepth:a}){switch(i.shouldMarkSchemaAsReferenced()&&i.markSchemaAsReferenced(e,n),e.type){case"primitive":return PEo(e);case"array":return e6s({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"map":return t6s({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"reference":return k7s({schema:e,fileContainingReference:t,context:i,namespace:n});case"unknown":return i6s();case"optional":return jEo({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"nullable":return r6s({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"enum":return baD({schema:e,fileContainingReference:t,context:i,declarationFile:r,declarationDepth:a});case"literal":return e.value,n6s(e);case"object":return gaD({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"oneOf":return OaD({schema:e.value,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});default:Ko(e)}}function PEo(e){switch(e.schema.type){case"string":return daD({description:e.description,schema:e.schema});case"int":return paD({description:e.description,schema:e.schema});case"float":return _aD({description:e.description,schema:e.schema});case"double":return haD({description:e.description,schema:e.schema});case"boolean":return laD({description:e.description,schema:e.schema});case"int64":return faD({description:e.description,schema:e.schema})}let t=e.schema._visit({int:()=>"integer",int64:()=>"long",uint:()=>"uint",uint64:()=>"uint64",float:()=>"double",double:()=>"double",string:()=>"string",datetime:()=>"datetime",date:()=>"date",base64:()=>"base64",boolean:()=>"boolean",_other:()=>"unknown"});return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:kx(e.availability)}:{}}}function laD({description:e,schema:t}){let r="boolean";if(e==null&&t.default==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),i}function faD({description:e,schema:t}){let r="long";if(e==null&&t.default==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),i}function daD({description:e,schema:t}){let r="string",i=yaD(t);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function paD({description:e,schema:t}){let r="integer",i=ITp(t,r);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function _aD({description:e,schema:t}){let r="float";if(e==null)return r;let i={type:r};return e!=null&&(i.docs=e),i}function haD({description:e,schema:t}){let r="double",i=ITp(t,r);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function yaD(e){if(e==null)return;let{format:t,pattern:r,minLength:i,maxLength:n}=e,a=vaD(t);if(!(a==null&&r==null&&i==null&&n==null))return{format:a,pattern:r,minLength:i,maxLength:n}}function vaD(e){switch(e){case"date":case"date-time":case"password":case"byte":case"bytes":case"binary":case"email":case"uuid":case"uri":case"hostname":case"ipv4":case"ipv6":return e;default:return}}function ITp(e,t){if(e==null)return;let{minimum:r,maximum:i,multipleOf:n}=e,{exclusiveMinimum:a,exclusiveMaximum:u}=e;if(r=Z7s(r,t),i=Z7s(i,t),n=Z7s(n,t),!(r==null&&i==null&&a==null&&u==null&&n==null))return{min:r,max:i,exclusiveMin:a,exclusiveMax:u,multipleOf:n}}function Z7s(e,t){if(e===void 0)return;let[r,i]=t==="integer"?[oaD,uaD]:[saD,caD];return e<r||e>i?void 0:e}function k7s({schema:e,fileContainingReference:t,context:r,namespace:i}){let n=r.getSchema(e.schema,i);if(n==null)return"unknown";let a=maD(n)??e.schema,u=MPn(n),l=PaD(n),d=wEo({context:r,fileContainingReference:t,declarationFile:EPn(u),type:a}),s=n.type==="nullable"?`optional<${d}>`:d;return e.description==null&&l==null?s:{type:n.type==="nullable"?`optional<${d}>`:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:kx(e.availability)}:{}}}function e6s({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=I0({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=`list<${bM(u)}>`;return e.description==null&&e.title==null?l:{...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:kx(e.availability)}:{},type:l}}function t6s({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=PEo(e.key),l=I0({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),d=e.encoding!=null?mEo(e.encoding):void 0,s=`map<${bM(u)}, ${bM(l)}>`;if(e.description==null&&d==null&&e.title==null)return s;let o={type:s};return e.description!=null&&(o.docs=e.description),e.encoding!=null&&(o.encoding=d),e.availability!=null&&(o.availability=kx(e.availability)),o}function r6s({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){if(!i.respectNullableSchemas)return jEo({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});let u=I0({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=bM(u),d=APn(u),s=Mla(u),o=X7s(u),c=l.startsWith("nullable<")?l:`nullable<${l}>`;if(e.availability==null&&e.description==null&&d==null&&s==null&&o==null&&e.title==null)return xTp({typeReference:c,itemType:l});let b={type:c};return(e.description!=null||d!=null)&&(b.docs=e.description??d),s!=null&&(b.default=s),o!=null&&(b.validation=o),e.availability!=null&&(b.availability=kx(e.availability)),xTp({typeReference:b,itemType:l})}function jEo({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=I0({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=bM(u),d=APn(u),s=Mla(u),o=X7s(u),c=l.startsWith("optional<")?l:`optional<${l}>`;if(e.availability==null&&e.description==null&&d==null&&s==null&&o==null&&e.title==null)return c;let b={type:c};return(e.description!=null||d!=null)&&(b.docs=e.description??d),s!=null&&(b.default=s),o!=null&&(b.validation=o),e.availability!=null&&(b.availability=kx(e.availability)),b}function i6s(){return"unknown"}function n6s(e){let t;switch(e.value.type){case"boolean":{t=`literal<${e.value.value}>`;break}case"string":{t=`literal<"${e.value.value}">`;break}default:Ko(e.value)}return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:kx(e.availability)}:{}}}function baD({schema:e,fileContainingReference:t,declarationFile:r,context:i,declarationDepth:n}){let a=Ala(e,n),u=e.nameOverride??e.generatedName;i.builder.addType(r,{name:u,schema:a.schema});let l=wEo({type:u,fileContainingReference:t,declarationFile:r,context:i});if(e.description==null&&e.default==null&&e.title==null)return l;let d={type:l};return e.description!=null&&(d.docs=e.description),e.default!=null&&(d.default=e.default.value),e.availability!=null&&(d.availability=kx(e.availability)),d}function gaD({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=a6s({schema:e,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=e.nameOverride??e.generatedName;i.builder.addType(r,{name:l,schema:u.schema});let d=wEo({type:l,fileContainingReference:t,declarationFile:r,context:i});return e.description==null&&e.title==null?d:{type:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:kx(e.availability)}:{}}}function OaD({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=o6s({schema:e,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=e.nameOverride??e.generatedName;i.builder.addType(r,{name:l,schema:u.schema});let d=wEo({type:l,fileContainingReference:t,declarationFile:r,context:i});return e.description==null&&e.title==null?d:{...e.title!=null?{"display-name":e.title}:{},type:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:kx(e.availability)}:{}}}function wEo({type:e,fileContainingReference:t,declarationFile:r,context:i}){if(r===t)return e;let n=i.builder.addImport({file:t,fileToImport:r});return n!=null?`${n}.${e}`:e}function maD(e){return py._visit(e,{primitive:t=>t.nameOverride??t.generatedName,object:t=>t.nameOverride??t.generatedName,array:t=>t.nameOverride??t.generatedName,map:t=>t.nameOverride??t.generatedName,enum:t=>t.nameOverride??t.generatedName,reference:t=>t.nameOverride??t.generatedName,literal:t=>t.nameOverride??t.generatedName,oneOf:t=>t.nameOverride??t.generatedName,optional:t=>t.nameOverride??t.generatedName,nullable:t=>t.nameOverride??t.generatedName,unknown:t=>t.nameOverride??t.generatedName,_other:()=>{}})}function PaD(e){return py._visit(e,{primitive:t=>t.title,object:t=>t.title,array:t=>t.title,map:t=>t.title,enum:t=>t.title,reference:t=>t.title,literal:t=>t.title,oneOf:t=>t.title,optional:t=>t.title,nullable:t=>t.title,unknown:t=>{},_other:()=>{}})}function xTp({typeReference:e,itemType:t}){return t.startsWith("optional<")?e:typeof e=="string"?`optional<${e}>`:{...e,type:`optional<${e.type}>`}}function JGr(e){switch(e.type){case"openapi":return{openapi:e.file};case"protobuf":return{proto:e.file};default:Ko(e)}}function RTp({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a;switch(e.type){case"primitive":a=SaD(e);break;case"array":a=jaD({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"map":a=waD({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"reference":a=DaD({schema:e,context:t,declarationFile:r,namespace:i});break;case"unknown":a=MaD(e.nameOverride,e.generatedName);break;case"optional":a=NTp({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"nullable":a=EaD({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"enum":a=Ala(e,n);break;case"literal":a=AaD(e,e.nameOverride,e.generatedName);break;case"object":a=a6s({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"oneOf":a=o6s({schema:e.value,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;default:Ko(e)}return a}function a6s({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a=t.isInState(a2.Request)&&t.respectReadonlySchemas&&(t.getEndpointMethod()==="POST"||t.getEndpointMethod()==="PUT"||t.getEndpointMethod()==="PATCH"),u=!1,l={},d=new Set;for(let g of e.properties){if(g.readonly&&(u=!0),a&&g.readonly)continue;if(Object.keys(g.conflict).length>0){if(Object.entries(g.conflict).every(([D,C])=>!C.differentSchema))continue;Object.entries(g.conflict).forEach(([D])=>{u6s({property:g.key,schemaId:D,context:t,namespace:i}).forEach(R=>{d.add(R)})})}let O=I0({schema:g.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1}),m=g.audiences,w=g.nameOverride,E=kx(g.availability),A=BaD(g);l[g.key]=CaD({typeReference:O,audiences:m,name:w,availability:E,propertyAccess:A})}let s=new Set;for(let g of e.allOfPropertyConflicts)g.allOfSchemaIds.forEach(O=>d.add(O)),g.conflictingTypeSignatures&&s.add(g.propertyKey);let o=[];for(let g of e.allOf){let O=FTp({schema:g.schema,context:t,namespace:i});if(O==null||d.has(g.schema)||d.has(O))continue;let m=I0({schema:py.reference(g),context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});o.push(bM(m))}for(let g of d){let O=s6s(t,g,i);for(let m of O.properties)l[m.key]==null&&(s.has(m.key)&&(l[m.key]="unknown"),l[m.key]=I0({schema:m.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1}));for(let m of O.allOf){if(d.has(m.schema))continue;let w=I0({schema:py.reference(m),context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});o.push(bM(w))}}let c={docs:e.description??void 0,properties:Object.fromEntries(Object.entries(l).map(([g,O])=>TaD(g)?[g,typeof O=="string"?{type:O,name:`_${g}`}:{...O,name:`_${g}`}]:[g,O]))};o.length>0&&(c.extends=o),e.additionalProperties&&(c["extra-properties"]=!0),e.availability!=null&&(c.availability=kx(e.availability)),e.source!=null&&(c.source=JGr(e.source)),c.inline=c6s(e,n);let b=e.nameOverride??e.generatedName;return{name:u&&t.respectReadonlySchemas&&!a?`${b}Read`:b,schema:c}}function u6s({property:e,schemaId:t,context:r,namespace:i}){let n=r.getSchema(t,i);if(n==null)return[];if(n.type==="reference")return u6s({property:e,schemaId:n.schema,context:r,namespace:i});if(n.type==="object"){let{properties:a,allOf:u}=s6s(r,t,i),l=a.some(s=>s.key===e),d=[...u.flatMap(s=>u6s({property:e,context:r,schemaId:s.schema,namespace:i}))];if(l||d.length>0)return[t,...d]}return[]}function s6s(e,t,r){let i=e.getSchema(t,r);if(i==null)return{properties:[],allOf:[]};if(i.type==="object")return{properties:i.properties,allOf:i.allOf};if(i.type==="reference")return s6s(e,i.schema,r);throw new Error(`Cannot getAllProperties for a non-object schema. schemaId=${t}, type=${i.type}`)}function jaD({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:e6s({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:i,declarationDepth:n})}}function waD({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:t6s({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:i,declarationDepth:n})}}function SaD(e){let t=PEo(e);if(typeof t=="string")return{name:e.nameOverride??e.generatedName,schema:t};let{default:r,...i}=t;return{name:e.nameOverride??e.generatedName,schema:{...i}}}function zTp(e){return e.camel==null&&e.pascal==null&&e.screamingSnake==null&&e.snake==null}function Ala(e,t){let r={enum:e.values.map(a=>{let u=a.nameOverride??a.generatedName,l=a.value;if(u===l&&a.description==null&&(a.casing==null||zTp(a.casing)))return u;let d={value:a.value};if(u!==l&&(d.name=u),a.description!=null&&(d.docs=a.description),a.casing!=null&&!zTp(a.casing)){let s={},o=!1;a.casing.camel!=null&&(s.camel=a.casing.camel,o=!0),a.casing.screamingSnake!=null&&(s["screaming-snake"]=a.casing.screamingSnake,o=!0),a.casing.snake!=null&&(s.snake=a.casing.snake,o=!0),a.casing.pascal!=null&&(s.pascal=a.casing.pascal,o=!0),o&&(d.casing=s)}return d})};e.description!=null&&(r.docs=e.description),e.default!=null&&(r.default=e.default.value),r.inline=c6s(e,t);let i=new Set,n={...r,enum:[],source:e.source!=null?JGr(e.source):void 0};for(let a of r.enum){let u=typeof a=="string"?a:a.name??a.value;i.has(u.toLowerCase())||(n.enum.push(a),i.add(u.toLowerCase()))}return{name:e.nameOverride??e.generatedName,schema:n}}function DaD({schema:e,context:t,declarationFile:r,namespace:i}){return{name:e.nameOverride??e.generatedName,schema:k7s({schema:e,context:t,fileContainingReference:r,namespace:i})}}function EaD({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return t.respectNullableSchemas?{name:e.nameOverride??e.generatedName,schema:r6s({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:i,declarationDepth:n})}:NTp({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n})}function NTp({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:jEo({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:i,declarationDepth:n})}}function MaD(e,t){return{name:e??t,schema:i6s()}}function AaD(e,t,r){return{name:t??r,schema:n6s(e)}}function o6s({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a=e.encoding!=null?mEo(e.encoding):void 0;if(e.type==="discriminated"){let l={};for(let s of e.commonProperties)l[s.key]=I0({schema:s.schema,fileContainingReference:r,context:t,namespace:i,declarationDepth:n+1});let d={};for(let[s,o]of Object.entries(e.schemas))d[s]=I0({schema:o,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});return{name:e.nameOverride??e.generatedName,schema:{discriminant:e.discriminantProperty,"base-properties":l,docs:e.description??void 0,availability:e.availability!=null?kx(e.availability):void 0,union:d,encoding:a,source:e.source!=null?JGr(e.source):void 0}}}let u=[];for(let l of e.schemas)u.push(I0({schema:l,fileContainingReference:r,context:t,namespace:i,declarationDepth:n+1}));return{name:e.nameOverride??e.generatedName,schema:{discriminated:!1,docs:e.description??void 0,union:u,encoding:a,source:e.source!=null?JGr(e.source):void 0,inline:c6s(e,n)}}}var qaD=/^[0-9]/;function TaD(e){return qaD.test(e)}function FTp({schema:e,context:t,namespace:r}){let i=t.getSchema(e,r);if(i!=null)return i.type==="reference"?FTp({context:t,schema:i.schema,namespace:r}):e}function CaD({typeReference:e,audiences:t,name:r,availability:i,propertyAccess:n}){return t.length===0&&r==null&&i==null&&n==null?e:{...typeof e=="string"?{type:e}:{...e},...t.length>0?{audiences:t}:{},...r!=null?{name:r}:{},...i!=null?{availability:i}:{},...n!=null?{access:n}:{}}}function c6s(e,t){return e.inline===!0||t>0?!0:void 0}function BaD(e){if(!(e.readonly&&e.writeonly)){if(e.readonly)return G6.ObjectPropertyAccess.ReadOnly;if(e.writeonly)return G6.ObjectPropertyAccess.WriteOnly}}function LTp(e){let t=e.replace(/^x-|^X-/,"");return vg(t)}var UTp="BasicAuthScheme",SEo="BearerAuthScheme";function VTp(e){if(e.authOverrides!=null){for(let[r,i]of Object.entries(e.authOverrides["auth-schemes"]??{}))e.builder.addAuthScheme({name:r,schema:i});e.authOverrides.auth!=null&&e.builder.setAuth(e.authOverrides.auth);return}let t=!1;for(let[r,i]of Object.entries(e.ir.securitySchemes))if(i.type==="basic"){let n={scheme:"basic"};i.usernameVariableName!=null&&(n.username===void 0?n.username={name:i.usernameVariableName}:n.username.name=i.usernameVariableName),i.usernameEnvVar!=null&&(n.username===void 0?n.username={env:i.usernameEnvVar}:n.username.env=i.usernameEnvVar),i.passwordVariableName!=null&&(n.password===void 0?n.password={name:i.passwordVariableName}:n.password.name=i.passwordVariableName),i.passwordEnvVar!=null&&(n.password===void 0?n.password={env:i.passwordEnvVar}:n.password.env=i.passwordEnvVar),e.builder.addAuthScheme({name:UTp,schema:n}),t||(e.builder.setAuth(UTp),t=!0)}else if(i.type==="bearer"){let n={scheme:"bearer"};i.tokenVariableName!=null&&(n.token===void 0?n.token={name:i.tokenVariableName}:n.token.name=i.tokenVariableName),i.tokenEnvVar!=null&&(n.token===void 0?n.token={env:i.tokenEnvVar}:n.token.env=i.tokenEnvVar),e.builder.addAuthScheme({name:SEo,schema:n}),t||(e.builder.setAuth(SEo),t=!0)}else if(i.type==="header")if(t)e.builder.addGlobalHeader({name:i.headerName,schema:{type:"string",name:i.headerVariableName??LTp(i.headerName),env:i.headerEnvVar}});else{let n={header:i.headerName,name:i.headerVariableName??"apiKey",type:"string"};i.headerEnvVar!=null&&(n.env=i.headerEnvVar),i.prefix!=null&&(n.prefix=i.prefix),e.builder.addAuthScheme({name:r,schema:n}),e.builder.setAuth(r),t=!0}else if(i.type==="oauth"){let n={scheme:"bearer"};e.builder.addAuthScheme({name:SEo,schema:n}),t||(e.builder.setAuth(SEo),t=!0),i.scopesEnum!=null&&i.scopesEnum.values.length>0&&e.builder.addType(ry.of("__package__.yml"),{name:"OauthScope",schema:Ala(i.scopesEnum,0).schema})}}function _Yt({header:e,context:t,fileContainingReference:r,namespace:i}){let n=I0({schema:e.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),a=bM(n),u=e.name.replace(/^x-|^X-/,""),l=e.parameterNameOverride!=null?e.parameterNameOverride:vg(u);if(e.description==null&&e.name===l&&e.env==null&&e.availability==null)return a;let d={type:a};return l!==e.name&&(d.name=l),e.description!=null&&(d.docs=e.description),e.env!=null&&(d.env=e.env),e.availability!=null&&(d.availability=kx(e.availability)),d}function DEo({pathParameter:e,context:t,fileContainingReference:r,namespace:i}){let n=I0({schema:e.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:0});if(e.variableReference==null&&e.description==null&&e.availability==null)return bM(n);let a=e.variableReference!=null?{variable:`$${e.variableReference}`}:{type:bM(n)};return e.description!=null&&(a.docs=e.description),e.availability!=null&&(a.availability=kx(e.availability)),a}function MEo({queryParameter:e,context:t,fileContainingReference:r,namespace:i}){let n=l6s({schema:e.schema,context:t,fileContainingReference:r,namespace:i});if(n==null)return;let a=bM(n.value),u=Mla(n.value);if(a==="unknown"?a="string":a==="optional<unknown>"&&(a="optional<string>"),e.description==null&&!n.allowMultiple&&e.parameterNameOverride==null&&e.availability==null)return a;let l={type:a};return u!=null&&(l.default=u),n.allowMultiple&&(l["allow-multiple"]=!0),e.description!=null&&(l.docs=e.description),e.parameterNameOverride!=null&&(l.name=e.parameterNameOverride),e.availability!=null&&(l.availability=kx(e.availability)),xaD(n.value)&&n.value.validation!==void 0&&(l.validation=n.value.validation),l}function l6s({schema:e,context:t,fileContainingReference:r,namespace:i}){if(e.type==="reference"){let n=t.getSchema(e.schema,i);if(n==null)return;if(n.type==="array")return{value:I0({schema:py.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:n.value,description:e.description??n.description,availability:e.availability,groupName:void 0,inline:void 0}),context:t,declarationFile:ry.of(W1),fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(n.type==="oneOf"&&n.value.type==="undiscriminated"){let a=[];for(let[u,l]of Object.entries(n.value.schemas))l.type==="literal"&&l.value.type==="string"&&(SPn.test(l.value.value)?a.push(l.value.value):a.push({value:l.value.value,name:DPn(l.value.value)}));if(a.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:a}}),{value:e.generatedName,allowMultiple:!1};if(n.value.schemas.length===2){let[u,l]=n.value.schemas;if(u!=null&&l!=null&&EEo({array:u,primitive:l}))return{value:I0({schema:py.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:l,description:e.description,availability:e.availability,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(u!=null&&l!=null&&EEo({array:u,primitive:l}))return{value:I0({schema:py.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:u,description:e.description,availability:e.availability,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}}for(let[u,l]of Object.entries(n.value.schemas))return l6s({schema:l,context:t,fileContainingReference:r,namespace:i})}else if(t.objectQueryParameters)return{value:I0({schema:e,context:t,fileContainingReference:r,declarationFile:ry.of(W1),namespace:i,declarationDepth:0}),allowMultiple:!1}}if(e.type==="optional"||e.type==="nullable"){if(e.value.type==="reference"){let n=t.getSchema(e.value.schema,i);if(n==null)return;if(n.type==="array")return{value:I0({schema:py.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:n.value,description:e.description??n.description,availability:e.availability,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,declarationFile:ry.of(W1),namespace:i,declarationDepth:0}),allowMultiple:!0};if(t.objectQueryParameters)return{value:I0({schema:e,context:t,fileContainingReference:r,declarationFile:ry.of(W1),namespace:i,declarationDepth:0}),allowMultiple:!1}}if(e.value.type==="array")return{value:I0({schema:py.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value.value,description:e.description,availability:e.availability,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(e.value.type==="oneOf"&&e.value.value.type==="undiscriminated"){let n=[];for(let[a,u]of Object.entries(e.value.value.schemas))u.type==="literal"&&u.value.type==="string"&&(SPn.test(u.value.value)?n.push(u.value.value):n.push({value:u.value.value,name:DPn(u.value.value)}));if(n.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:n}}),{value:`optional<${e.value.value.generatedName}>`,allowMultiple:!1};if(e.value.value.schemas.length===2){let[a,u]=e.value.value.schemas;if(a!=null&&u!=null&&EEo({array:a,primitive:u}))return{value:I0({schema:py.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:u,description:e.description,availability:e.availability,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(a!=null&&u!=null&&EEo({array:u,primitive:a}))return{value:I0({schema:py.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:a,description:e.description,availability:e.availability,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}}for(let[a,u]of Object.entries(e.value.value.schemas))return l6s({schema:py.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:u,description:void 0,availability:e.availability,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i})}else if(e.value.type==="object")return t.objectQueryParameters?{value:I0({schema:e,context:t,fileContainingReference:r,declarationFile:ry.of(W1),namespace:i,declarationDepth:0}),allowMultiple:!1}:void 0;return{value:I0({schema:e,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!1}}return e.type==="array"?{value:I0({schema:py.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:e.description,availability:e.availability,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}:{value:I0({schema:e,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!1}}function EEo({array:e,primitive:t}){return e?.type==="array"&&e.value.type==="primitive"&&t?.type==="primitive"&&e.value.schema.type===t.schema.type}function xaD(e){return e.type!=null}function WTp({websocketExample:e,context:t}){let r={messages:[]};e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=IaD(e.queryParameters)),e.headers!=null&&e.headers.length>0&&(r.headers=zaD({context:t,namedFullExamples:e.headers}));for(let i of e.messages){let n=fli(i.payload);n!=null&&r.messages.push({type:i.messageType,body:n})}return r}function IaD(e){let t={};return e.forEach(r=>{let i=fli(r.value);Array.isArray(i)?t[r.name]=i[0]:i!=null&&(t[r.name]=i)}),t}function zaD({context:e,namedFullExamples:t}){let r=e.builder.getGlobalHeaderNames(),i={};return t.forEach(n=>{let a=fli(n.value);r.has(n.name)||a!=null&&(i[n.name]=a)}),i}function fli(e){switch(e.type){case"primitive":return HTp(e.value);case"object":return $Tp(e.properties);case"array":return RaD(e.value);case"map":return NaD(e.value);case"oneOf":return FaD(e.value);case"enum":return e.value;case"literal":return LaD(e.value);case"unknown":return fli(e.value);default:Ko(e)}}function HTp(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`${e.value.slice(1)}`:e.value;case"datetime":try{return new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"date":return e.value;case"base64":case"boolean":return e.value;default:Ko(e)}}function $Tp(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,fli(r)]))}function RaD(e){return e.map(t=>fli(t))}function NaD(e){return Object.fromEntries(e.map(t=>[HTp(t.key),fli(t.value)]))}function FaD(e){return e.type==="discriminated"?$Tp(e.value):fli(e.value)}function LaD(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:Ko(e)}}function KGr(e){return e.find(t=>typeof t!="string"&&t.type==="namespace")?.name}function AEo(e,t){return t??(e?.groupName!=null?KGr(e.groupName):void 0)}function GTp({channel:e,context:t,declarationFile:r}){let i={path:e.path,url:e.servers[0]?.name,auth:!1};e.audiences!=null&&e.audiences.length>0&&(i.audiences=e.audiences),e.summary!=null&&(i["display-name"]=e.summary);let n=KGr(e.groupName),a={};if(e.handshake.pathParameters.length>0)for(let d of e.handshake.pathParameters)a[d.name]=DEo({pathParameter:d,context:t,fileContainingReference:r,namespace:n});Object.keys(a).length>0&&(i["path-parameters"]=a);let u={};if(e.handshake.queryParameters.length>0)for(let d of e.handshake.queryParameters){let s=MEo({queryParameter:d,context:t,fileContainingReference:r,namespace:n});s!=null&&(u[d.name]=s)}Object.keys(u).length>0&&(i["query-parameters"]=u);let l={};if(e.handshake.headers.length>0)for(let d of e.handshake.headers){let s=_Yt({header:d,context:t,fileContainingReference:r,namespace:n});l[d.name]=s}Object.keys(l).length>0&&(i.headers=l),t.builder.addChannel(r,{channel:i}),e.subscribe!=null&&t.builder.addChannelMessage(r,{messageId:"subscribe",message:{origin:"server",body:I0({schema:e.subscribe,context:t,fileContainingReference:r,namespace:n,declarationDepth:0})}}),e.publish!=null&&t.builder.addChannelMessage(r,{messageId:"publish",message:{origin:"client",body:I0({schema:e.publish,context:t,fileContainingReference:r,namespace:n,declarationDepth:0})}});for(let d of e.examples){let s=WTp({context:t,websocketExample:d});t.builder.addChannelExample(r,{example:s})}}var dli="Base",UaD="Default";function pli(e){return Object.entries(e).reduce((t,[r,i])=>(Dhn(i)?Object.entries(i.urls).forEach(([n,a])=>{t[n]=a}):t[r]=typeof i=="string"?i:i.url,t),{})}function QTp(e){if(e.environmentOverrides!=null){for(let[b,g]of Object.entries(e.environmentOverrides.environments??{}))e.builder.addEnvironment({name:b,schema:g});e.environmentOverrides["default-environment"]!=null&&e.builder.setDefaultEnvironment(e.environmentOverrides["default-environment"]),e.environmentOverrides["default-url"]!=null&&e.builder.setDefaultUrl(e.environmentOverrides["default-url"]);return}let t={},r=[];for(let b of e.ir.servers){let g=b.audiences?{url:b.url,audiences:b.audiences}:b.url;if(b.name==null){r.push(g);continue}t[b.name]=g}let i={},n=[];for(let b of e.ir.endpoints)for(let g of b.servers){if(g.url==null)continue;let O=g.audiences?{url:g.url,audiences:g.audiences}:g.url;if(g.name==null){n.push(O);continue}i[g.name]=O}let a={},u=[];for(let b of e.ir.websocketServers){let g=b.audiences?{url:b.url,audiences:b.audiences}:b.url;if(b.name==null){u.push(g);continue}a[b.name]=g}let l=Object.keys(t).length,d=Object.keys(i).length>0,s=Object.keys(a).length>0;if(n.length>0&&e.logger.error(`Skipping endpoint level servers ${n.map(b=>typeof b=="string"?b:b.url).join(", ")} because x-fern-server-name was not provided.`),l===0){let b=e.ir.servers[0]?.url,g=e.ir.servers[0]?.audiences;if(b!=null){let O=g?{url:b,audiences:g}:b;t[UaD]=O}}let o=Object.values(t).map(b=>typeof b=="string"?b:b.url),c=r.filter(b=>{let g=typeof b=="string"?b:b.url;return!o.includes(g)});if(c.length>0&&e.logger.error(`Skipping top level servers ${c.map(b=>typeof b=="string"?b:b.url).join(", ")} because x-fern-server-name was not provided.`),d)if(l===1){let b=Object.keys(t)[0],g=Object.values(t)[0],O=typeof g=="string"?g:g.url;e.builder.addEnvironment({name:b,schema:{urls:{[dli]:O,...pli(i),...pli(a)}}}),e.builder.setDefaultEnvironment(b),e.builder.setDefaultUrl(dli)}else{let b=!0;for(let[g,O]of Object.entries(t))b?(e.builder.addEnvironment({name:g,schema:{urls:{[dli]:typeof O=="string"?O:O.url,...pli(i),...pli(a)}}}),e.builder.setDefaultEnvironment(g),b=!1):e.builder.addEnvironment({name:g,schema:{urls:{[dli]:typeof O=="string"?O:O.url,...pli(i),...pli(a)}}});e.builder.setDefaultUrl(dli)}else{let b=!0;for(let[g,O]of Object.entries(t))b?(s?e.builder.addEnvironment({name:g,schema:{urls:{[dli]:typeof O=="string"?O:O.url,...pli(a)}}}):e.builder.addEnvironment({name:g,schema:O}),e.builder.setDefaultEnvironment(g),b=!1):s?e.builder.addEnvironment({name:g,schema:{urls:{[dli]:typeof O=="string"?O:O.url,...pli(a)}}}):e.builder.addEnvironment({name:g,schema:O});s&&e.builder.setDefaultUrl(dli)}}function qEo(e){return bM(e).startsWith("optional")?e:typeof e=="string"?`optional<${e}>`:{...e,type:`optional<${e.type}>`}}var f6s=class{schema;count=0;constructor(t){this.schema=t}increment(){this.count+=1}},VaD=.75,WaD=new Set("authorization");function JTp(e){if(e.globalHeaderOverrides!=null){for(let[r,i]of Object.entries(e.globalHeaderOverrides.headers??{}))e.builder.addGlobalHeader({name:r,schema:i});return}let t=Object.fromEntries((e.ir.globalHeaders??[]).map(r=>[r.header,r]));for(let[r,i]of Object.entries(t)){let n="optional<string>";if(i.name==null&&i.env==null&&typeof i.schema=="string")n=i.schema;else if(i!=null){let a=i.schema?MPn(i.schema):void 0,u=a!=null?KGr(a):void 0,l=ry.of("api.yml");n={name:i.name,env:i.env,type:i.schema!=null?bM(I0({schema:i.schema,context:e,fileContainingReference:u?sR(ry.of(vg(u)),l):l,namespace:u,declarationDepth:0}))??"optional<string>":"optional<string>"}}e.builder.addGlobalHeader({name:r,schema:n})}if(e.detectGlobalHeaders){let r={};for(let n of e.ir.endpoints)for(let a of n.headers){if(WaD.has(a.name.toLowerCase()))continue;let u=r[a.name];if(u==null){let l=t[a.name],d=_Yt({header:{...a,schema:l?.schema??a.schema,name:l?.name??a.name},fileContainingReference:ry.of(T3),context:e,namespace:void 0});u=new f6s(d),r[a.name]=u}u.increment()}let i=e.ir.endpoints.length*VaD;for(let[n,a]of Object.entries(r)){let u=t[n],l=a.count===e.ir.endpoints.length,d=a.count>=i;u==null&&(l?e.builder.addGlobalHeader({name:n,schema:a.schema}):d&&e.builder.addGlobalHeader({name:n,schema:qEo(a.schema)}))}}}function KTp(e){for(let t of e.ir.idempotencyHeaders??[]){let r=t.schema?MPn(t.schema):void 0,i=r!=null?KGr(r):void 0,n=_Yt({header:{...t,schema:t.schema??py.primitive({description:void 0,availability:void 0,generatedName:"",title:void 0,groupName:void 0,nameOverride:void 0,schema:sj.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0})}),name:t.name??t.header,parameterNameOverride:void 0,description:void 0,availability:void 0,source:void 0},fileContainingReference:ry.of(T3),context:e,namespace:i});e.builder.addIdempotencyHeader({name:t.header,schema:qEo(n)})}}function $$(e){switch(e.type){case"primitive":return XTp(e.value);case"object":return ZTp(e.properties);case"array":return kTp(e.value);case"map":return $aD(e.value);case"oneOf":return GaD(e.value);case"enum":return e.value;case"literal":return QaD(e.value);case"unknown":return $$(e.value);default:Ko(e)}}function YTp(e){switch(e.type){case"withStreaming":return e.sse?{stream:HaD(e.events)}:{stream:kTp(e.events)};case"withoutStreaming":return{body:$$(e.value)};default:Ko(e)}}function XTp(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`${e.value.slice(1)}`:e.value;case"datetime":try{return!e.value.endsWith("Z")&&!e.value.includes("+")&&(e.value+="Z"),new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"date":return e.value;case"base64":case"boolean":return e.value;default:Ko(e)}}function ZTp(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,$$(r)]))}function HaD(e){return e.map(t=>({event:"",data:$$(t)}))}function kTp(e){return e.map(t=>$$(t))}function $aD(e){return Object.fromEntries(e.map(t=>[XTp(t.key),$$(t.value)]))}function GaD(e){return e.type==="discriminated"?ZTp(e.value):$$(e.value)}function QaD(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:Ko(e)}}function eCp({endpointExample:e,context:t}){let r={};return e.type!=="full"?e.value:(e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.pathParameters!=null&&e.pathParameters.length>0&&(r["path-parameters"]=JaD(e.pathParameters)),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=KaD(e.queryParameters)),e.headers!=null&&e.headers.length>0&&(r.headers=YaD({context:t,namedFullExamples:e.headers})),e.request!=null&&(r.request=$$(e.request)),e.response!=null&&(r.response=YTp(e.response)),e.codeSamples!=null&&e.codeSamples.length>0&&(r["code-samples"]=e.codeSamples.map(i=>i.type==="language"?{name:i.name??void 0,docs:i.description??void 0,language:i.language,code:i.code,install:i.install??void 0}:{name:i.name??void 0,docs:i.description??void 0,sdk:i.sdk,code:i.code}).filter(u0)),r)}function JaD(e){let t={};return e.forEach(r=>{let i=$$(r.value);i!=null&&(t[r.parameterNameOverride??r.name]=i)}),t}function KaD(e){let t={};return e.forEach(r=>{let i=$$(r.value);Array.isArray(i)?t[r.name]=i[0]:i!=null&&(t[r.name]=i)}),t}function YaD({context:e,namedFullExamples:t}){let r=e.builder.getGlobalHeaderNames(),i={};return t.forEach(n=>{let a=$$(n.value);r.has(n.name)||a!=null&&(i[n.name]=a)}),i}function tCp(e){return W$._visit(e,{get:()=>G6.HttpMethodSchema.Get,post:()=>G6.HttpMethodSchema.Post,put:()=>G6.HttpMethodSchema.Put,patch:()=>G6.HttpMethodSchema.Patch,delete:()=>G6.HttpMethodSchema.Delete,head:()=>{throw new Error("HEAD is unsupported")},options:()=>{throw new Error("HEAD is unsupported")},trace:()=>{throw new Error("HEAD is unsupported")},_other:()=>{throw new Error("Unknown http method is unsupported")}})}function rCp(e){return e==="POST"||e==="PUT"||e==="PATCH"}function iCp({endpoint:e,declarationFile:t,context:r}){let{nonRequestReferencedSchemas:i}=r.ir,n=[],a=new Set,u=e.path,l=AEo(e.sdkName,e.namespace),d={};for(let m of e.pathParameters)m.parameterNameOverride&&(u=u.replace(m.name,m.parameterNameOverride)),d[m.parameterNameOverride??m.name]=DEo({pathParameter:m,context:r,fileContainingReference:t,namespace:l}),a.add(m.name);let s={};for(let m of e.queryParameters){let w=MEo({queryParameter:m,context:r,fileContainingReference:t,namespace:l});w!=null&&(s[m.name]=w,a.add(m.name))}let o;if(e.pagination!=null)switch(e.pagination.type){case"cursor":o={cursor:e.pagination.cursor,next_cursor:e.pagination.nextCursor,results:e.pagination.results};break;case"offset":o={offset:e.pagination.offset,step:e.pagination.step,results:e.pagination.results,"has-next-page":e.pagination.hasNextPage};break;case"custom":o={type:"custom",results:e.pagination.results};break;default:Ko(e.pagination)}let c={path:u,method:tCp(e.method),auth:e.authed,docs:e.description??void 0,pagination:o,source:e.source!=null?JGr(e.source):void 0};!kaD({context:r,request:e.request})&&Object.keys(d).length>0&&(c["path-parameters"]=d),e.summary!=null&&(c["display-name"]=e.summary);let b={},g=r.builder.getGlobalHeaderNames(),O=e.headers.filter(m=>!g.has(m.name));for(let m of O){let w=_Yt({header:m,context:r,fileContainingReference:t,namespace:l});b[m.name]=w,a.add(typeof w=="string"?m.name:w.name??m.name)}if(e.request!=null){r.setInState(a2.Request);let m=ZaD({endpoint:e,context:r,declarationFile:t,request:e.request,generatedRequestName:e.generatedRequestName,requestNameOverride:e.requestNameOverride??void 0,pathParameters:r.inlinePathParameters&&Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,nonRequestReferencedSchemas:Array.from(i),headers:Object.keys(b).length>0?b:void 0,usedNames:a,namespace:l});c.request=m.value,n=[...n,...m.schemaIdsToExclude??[]],r.unsetInState(a2.Request)}else{let m=r.inlinePathParameters&&Object.keys(d).length>0,w=Object.keys(s).length>0,E=Object.keys(b).length>0,A={};(m||w||E)&&(A.name=e.requestNameOverride??e.generatedRequestName),m&&(A["path-parameters"]=d),w&&(A["query-parameters"]=s),E&&(A.headers=b),Object.keys(A).length>0&&(c.request=A)}if(e.response!=null&&e.response._visit({json:m=>{let w=I0({schema:m.schema,context:r,fileContainingReference:t,namespace:l,declarationDepth:0});c.response={docs:m.description??void 0,type:bM(w)},m.statusCode!=null&&(c.response["status-code"]=m.statusCode),m.responseProperty!=null&&(c.response.property=m.responseProperty)},streamingJson:m=>{let w=I0({schema:m.schema,context:r,fileContainingReference:t,namespace:l,declarationDepth:0});c["response-stream"]={docs:m.description??void 0,type:bM(w),format:"json"}},streamingSse:m=>{let w=I0({schema:m.schema,context:r,fileContainingReference:t,namespace:l,declarationDepth:0});c["response-stream"]={docs:m.description??void 0,type:bM(w),format:"sse"}},file:m=>{c.response={docs:m.description??void 0,type:"file","status-code":m.statusCode}},streamingText:m=>{c["response-stream"]={docs:m.description??void 0,type:"text"}},text:m=>{c.response={docs:m.description??void 0,type:"text","status-code":m.statusCode}},_other:()=>{throw new Error("Unrecognized Response type: "+e.response?.type)}}),r.builder.getEnvironmentType()==="multi"){let m=r.getDefaultServerName(),w=e.servers[0];w==null?m!=null&&(c.url=m):c.url=w.name??void 0}return e.idempotent&&(c.idempotent=!0),e.availability!=null&&(c.availability=kx(e.availability)),Object.entries(e.errors).forEach(([m,w])=>{let E=w.generatedName,A=ry.of(W1);r.builder.enableUniqueErrorsPerEndpoint&&(E=`${e.generatedRequestName}${w.generatedName}`,w.schema!=null&&(w.schema.type!=="reference"&&w.schema.type!=="oneOf"?w.schema.generatedName=`${e.generatedRequestName}${w.schema.generatedName}`:w.schema.type==="oneOf"&&(w.schema.value.generatedName=`${e.generatedRequestName}${w.schema.value.generatedName}`)));let q={"status-code":parseInt(m)},D=BTp({location:nCp,namespaceOverride:l});if(w.schema!=null){let $=I0({schema:w.schema,context:r,fileContainingReference:D,declarationFile:D,namespace:l,declarationDepth:0});q.type=bM($),q.docs=w.description}r.builder.addError(D,{name:E,schema:r.isErrorUnknownSchema(parseInt(m))?{...q,type:"unknown"}:q}),c.errors==null&&(c.errors=[]);let C=r.builder.addImport({file:t,fileToImport:D});c.errors.push(C!=null?`${C}.${E}`:E),q.type!=null&&w.examples?.forEach($=>{let I={value:$$($.example),name:$.name,docs:$.description};r.builder.addErrorExample(D,{name:E,example:I})})}),e.examples.length>0&&(c.examples=XaD({endpointExamples:e.examples,context:r})),r.ir.hasEndpointsMarkedInternal&&(e.internal==null||!e.internal)?c.audiences=[d6s,...e.audiences]:e.audiences.length>0&&(c.audiences=e.audiences),{value:c,schemaIdsToExclude:n}}function XaD({endpointExamples:e,context:t}){return e.map(r=>{try{return eCp({endpointExample:r,context:t})}catch(i){throw console.error(`Error building endpoint example: ${i}`),i}})}function ZaD({endpoint:e,declarationFile:t,context:r,request:i,requestNameOverride:n,generatedRequestName:a,pathParameters:u,queryParameters:l,nonRequestReferencedSchemas:d,headers:s,usedNames:o,namespace:c}){if(i.type==="json"){let b=i.schema.type==="reference"?i.schema.schema:void 0,g=i.schema.type==="reference"?r.getSchema(i.schema.schema,c):i.schema;if(g?.type!=="object"||b!=null&&d.includes(b)){let A=I0({schema:i.schema,fileContainingReference:t,context:r,namespace:c,declarationDepth:0}),q={schemaIdsToExclude:[],value:{body:A}},D=Object.keys(u??{}).length>0,C=Object.keys(l??{}).length>0,R=Object.keys(s??{}).length>0;return D&&(q.value["path-parameters"]=u),C&&(q.value["query-parameters"]=l),R&&(q.value.headers=s),(D||C||R)&&(q.value.name=n??a),i.contentType!=null&&(q.value["content-type"]=i.contentType),i.description!=null&&(q.value.docs=i.description),q}let O=Object.fromEntries(g.properties.filter(A=>A.readonly==null?!0:!(rCp(e.method)&&A.readonly)).map(A=>{let q=I0({schema:A.schema,fileContainingReference:t,context:r,namespace:c,declarationDepth:1}),D=A.nameOverride??A.key,C=kx(A.availability);if(!o.has(D)&&A.audiences.length<=0)return o.add(D),A.nameOverride!=null?[A.key,{type:bM(q),docs:APn(q),name:A.nameOverride,availability:C}]:[A.key,C?{...typeof q=="string"?{type:q}:q,availability:C}:q];let R={type:bM(q),docs:APn(q)};return o.has(D)&&(R.name=A.generatedName),A.audiences.length>0&&(R.audiences=A.audiences),C!=null&&(R.availability=C),o.add(D),[A.key,R]})),m=g.allOf.map(A=>{let q=I0({schema:py.reference(A),fileContainingReference:t,context:r,namespace:c,declarationDepth:0});return bM(q)}),w={properties:O};m.length>0&&(w.extends=m),i.additionalProperties&&(w["extra-properties"]=!0);let E={name:n??g.nameOverride??g.generatedName,"path-parameters":u,"query-parameters":l,headers:s,body:w};return i.contentType!=null&&(E["content-type"]=i.contentType),i.description!=null&&(E.docs=i.description),{schemaIdsToExclude:b!=null?[b]:[],value:E}}else{if(i.type==="octetStream")return{schemaIdsToExclude:[],value:{body:"bytes","content-type":zB.APPLICATION_OCTET_STREAM,...i.description?{docs:i.description}:{}}};if(i.type==="multipart"){let b=Object.fromEntries(i.properties.map(g=>{if(g.schema.type==="file"){let O=g.schema.isArray?"list<file>":"file";if(O=g.schema.isOptional?`optional<${O}>`:O,g.description!=null||g.contentType!=null){let m={type:O};if(g.description!=null&&(m.docs=g.description),g.contentType!=null){let w=g.contentType.split(",")[0];m["content-type"]=w}return[g.key,m]}return[g.key,O]}else{let O=I0({schema:g.schema.value,fileContainingReference:t,context:r,namespace:c,declarationDepth:1});if(g.contentType!=null||g.exploded||g.encoding==="form"){let m=typeof O=="string"?{type:O}:O;g.contentType!=null&&(m["content-type"]=g.contentType),g.encoding==="form"?m.style="form":g.exploded&&(m.style="exploded"),O=m}return[g.key,O]}}));return{schemaIdsToExclude:i.name==null?[]:[i.name],value:{name:n??i.name??a,"path-parameters":u,"query-parameters":l,headers:s,body:{properties:b},"content-type":zB.MULTIPART_FORM_DATA,...i.description?{docs:i.description}:{}}}}else Ko(i)}}function kaD({context:e,request:t}){if(!e.inlinePathParameters)return!1;if(t==null)return!0;switch(t.type){case"octetStream":return!1;case"multipart":return!0;case"json":return!0;default:Ko(t)}}function eoD({location:e,namespaceOverride:t}){return t!=null?{...e,file:sR(ry.of(t),e.file)}:e}function toD(e){let t=e.namespace,r=e.tags.filter(d=>d!==t)[0],i=e.operationId;if(i==null)return r!=null?{file:ry.of(`${vg(r)}.yml`),endpointId:e.summary!=null?vg(e.summary):vg(`${e.method}_${e.path.split("/").join("_")}`)}:e.summary!=null?{file:ry.of(W1),endpointId:vg(e.summary)}:{file:ry.of(W1),endpointId:vg(`${e.method}_${e.path.split("/").join("_")}`)};if(r==null)return{file:ry.of(W1),endpointId:i};let n=qla(r),a=qla(i);if(u1e(n,a))return{file:ry.of("__package__.yml"),endpointId:r};let u=noD({operationId:i,tag:r,path:e.path,method:e.method});if(u!=null)return u;let l=[];for(let d=0;d<n.length;++d){let s=n[d];if(s!=null&&s===a[d])l.push(s);else{let o=vg(r);return{file:ry.of(`${o}.yml`),endpointId:i,tag:r}}}if(l.length>=a.length)throw new Error(`Cannot get file for endpoint ${JSON.stringify(e)}`);return{file:ry.of(vg(l.join("_"))+".yml"),endpointId:vg(a.slice(l.length).join("_")),tag:r}}function Tla(e){let t=e.tags[0];if(e.sdkName!=null){let r=Y7s({sdkName:e.sdkName,namespaceOverride:e.namespace}),i=`${r}.yml`,n=r.toLowerCase()===t?.toLowerCase().replaceAll(" ","");return{file:ry.of(i),endpointId:e.sdkName.methodName,tag:n?t:void 0}}return eoD({namespaceOverride:e.namespace,location:toD(e)})}function qla(e){let t;return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)?t=e.split(/(?=[A-Z])/):t=e.split(/[^a-zA-Z0-9]+/),t=t.map(r=>r.toLowerCase()),t=CCe(t),t}var roD=new RegExp("[^a-zA-Z0-9{}]+"),ioD=new RegExp("[{}]","g");function noD({operationId:e,tag:t,path:r,method:i}){let a=`${r.split(roD).join("_").replaceAll(ioD,"_")}_${i.toLowerCase()}`;if(e.endsWith(a))return{file:ry.of(vg(t)+".yml"),endpointId:vg(e.slice(0,-1*a.length)),tag:t}}function aCp(e){let t=new Set,{endpoints:r,tags:i}=e.ir,n=[];for(let a of r){let{endpointId:u,file:l,tag:d}=Tla(a),s=l.split(".")[0];s!=null&&t.add(s);let o;if(a.sdkName!=null){let g=e.ir.groups;for(let O of a.sdkName.groupName){let m=typeof O=="string"?O:O.name,w=g[m];if(w==null)break;if(w.summary!=null||w.description!=null){o=g[m];break}}}let c=d==null?void 0:i.tagsById[d];e.setInState(a2.Endpoint),e.setEndpointMethod(a.method);let b=iCp({context:e,endpoint:a,declarationFile:l});e.unsetEndpointMethod(),e.unsetInState(a2.Endpoint),n=[...n,...b.schemaIdsToExclude],e.builder.addEndpoint(l,{name:u,schema:b.value,source:a.source!=null?JGr(a.source):void 0}),(c?.id!=null||c?.description!=null)&&e.builder.setServiceInfo(l,{"display-name":o?.summary??c?.id,docs:o?.description??c?.description??void 0})}return{schemaIdsToExclude:n,sdkGroups:t}}function oCp(e){for(let[t,r]of Object.entries(e.ir.variables)){let i=r.groupName!=null?KGr(r.groupName):void 0,n=I0({schema:py.primitive(r),context:e,fileContainingReference:ry.of(W1),namespace:i,declarationDepth:0});e.builder.addVariable({name:t,schema:{type:bM(n),docs:r.description??void 0}})}}function uCp(e){for(let t of e.ir.webhooks){let r=uoD({webhook:t,context:e});if(r==null)continue;let i=AEo(t.sdkName,t.namespace),n={};for(let u of t.headers)n[u.name]=_Yt({header:u,context:e,fileContainingReference:r.file,namespace:i});let a={method:t.method,"display-name":t.summary??void 0,headers:n,payload:I0({schema:t.payload,context:e,fileContainingReference:r.file,namespace:i,declarationDepth:0}),examples:t.examples!=null?t.examples.map(u=>({docs:u.description,name:u.name,payload:$$(u.payload)})):void 0};e.builder.addWebhook(r.file,{name:r.endpointId,schema:a}),t.description!=null&&(a.docs=t.description)}}function aoD({location:e,namespaceOverride:t}){if(e!=null)return t!=null?{...e,file:sR(ry.of(t),e.file)}:e}function ooD({webhook:e,context:t}){let r=e.tags[0],i=e.operationId;if(r==null)return{file:ry.of(W1),endpointId:i};let n=qla(r),a=qla(i);if(u1e(n,a))return{file:ry.of("__package__.yml"),endpointId:r};let u=[];for(let l=0;l<n.length;++l){let d=n[l];if(d!=null&&d===a[l])u.push(d);else{let s=vg(r);return{file:ry.of(`${s}.yml`),endpointId:i,tag:r}}}if(u.length>=a.length){t.logger.warn(`Skipping webhook ${e.operationId} because couldn't compute file location`);return}return{file:ry.of(vg(u.join("_"))+".yml"),endpointId:vg(a.slice(u.length).join("_")),tag:r}}function uoD({webhook:e,context:t}){return e.sdkName!=null?{file:CTp({sdkName:e.sdkName,namespaceOverride:e.namespace}),endpointId:e.sdkName.methodName}:aoD({namespaceOverride:e.namespace,location:ooD({webhook:e,context:t})})}var soD=ry.of(W1);function sCp(e){switch(e.type){case"object":return hYt(e.groupName);case"enum":return hYt(e.groupName);case"oneOf":return hYt(e.value.groupName);case"array":return hYt(e.groupName);case"map":return hYt(e.groupName);case"reference":return hYt(e.groupName);case"literal":return hYt(e.groupName);case"optional":return hYt(e.groupName);case"nullable":return hYt(e.groupName);case"primitive":return hYt(e.groupName);case"unknown":return soD;default:Ko(e)}}function hYt(e){return EPn(e)}var d6s="external",nCp=ry.of(W1);function cCp({schemas:e,schemaIdsToExclude:t,namespace:r,context:i}){for(let[n,a]of Object.entries(e)){if(t.includes(n))continue;let u=sCp(a),l=RTp({schema:a,context:i,declarationFile:u,namespace:r,declarationDepth:0});if(Foi(l.schema)){let d=bM(l.schema);if(d===(l.name??n)||d===`optional<${l.name??n}>`)continue}i.builder.addType(u,{name:l.name??n,schema:l.schema})}}function lCp(e){e.ir.apiVersion!=null&&e.builder.setApiVersion(e.ir.apiVersion),QTp(e),JTp(e),KTp(e),VTp(e),oCp(e),e.ir.basePath!=null&&e.builder.setBasePath(e.ir.basePath),e.ir.hasEndpointsMarkedInternal&&e.builder.addAudience(d6s);let t=aCp(e),r=t.sdkGroups;e.setInState(a2.Webhook),uCp(e),e.unsetInState(a2.Webhook),e.setInState(a2.Channel);for(let n of Object.values(e.ir.channels)){let a=EPn(n.groupName);GTp({channel:n,context:e,declarationFile:a})}e.unsetInState(a2.Channel);let i=coD({context:e,schemaIdsToExcludeFromServices:t.schemaIdsToExclude});cCp({schemas:e.ir.groupedSchemas.rootSchemas,schemaIdsToExclude:i,namespace:void 0,context:e});for(let[n,a]of Object.entries(e.ir.groupedSchemas.namespacedSchemas))cCp({schemas:a,schemaIdsToExclude:i,namespace:n,context:e});return e.ir.tags.orderedTagIds!=null&&e.ir.tags.orderedTagIds.length>0&&e.ir.tags.orderedTagIds.every(a=>r.has(a))&&e.builder.addNavigation({navigation:e.ir.tags.orderedTagIds}),e.builder.build()}function coD({context:e,schemaIdsToExcludeFromServices:t}){let r=e.getReferencedSchemaIds();if(r==null)return t;let i=new Set([...Object.keys(e.ir.groupedSchemas.rootSchemas),...Object.values(e.ir.groupedSchemas.namespacedSchemas).flatMap(a=>Object.keys(a))]),n=new Set(t);for(let a of i)r.includes(a)||n.add(a);return Array.from(n)}function p6s(e){let t=new OEo(e);return lCp(t)}var Zxi={enableUniqueErrorsPerEndpoint:!1,detectGlobalHeaders:!0,objectQueryParameters:!1,respectReadonlySchemas:!1,respectNullableSchemas:!1,onlyIncludeReferencedSchemas:!1,inlinePathParameters:!1};function _6s({options:e,overrides:t}){return{enableUniqueErrorsPerEndpoint:t?.enableUniqueErrorsPerEndpoint??e?.enableUniqueErrorsPerEndpoint??Zxi.enableUniqueErrorsPerEndpoint,detectGlobalHeaders:t?.detectGlobalHeaders??e?.detectGlobalHeaders??Zxi.detectGlobalHeaders,objectQueryParameters:t?.objectQueryParameters??e?.objectQueryParameters??Zxi.objectQueryParameters,respectReadonlySchemas:t?.respectReadonlySchemas??e?.respectReadonlySchemas??Zxi.respectReadonlySchemas,respectNullableSchemas:t?.respectNullableSchemas??e?.respectNullableSchemas??Zxi.respectNullableSchemas,onlyIncludeReferencedSchemas:t?.onlyIncludeReferencedSchemas??e?.onlyIncludeReferencedSchemas??Zxi.onlyIncludeReferencedSchemas,inlinePathParameters:t?.inlinePathParameters??e?.inlinePathParameters??Zxi.inlinePathParameters}}var TEo=class{args;constructor(t){this.args=t}convert({context:t,ir:r,settings:i,absoluteFilePath:n}){let a=p6s({taskContext:t,ir:r,options:_6s({overrides:{...i,respectReadonlySchemas:i?.respectReadonlySchemas??this.args.respectReadonlySchemas,respectNullableSchemas:i?.respectNullableSchemas??this.args.respectNullableSchemas,onlyIncludeReferencedSchemas:i?.onlyIncludeReferencedSchemas??this.args.onlyIncludeReferencedSchemas,inlinePathParameters:i?.inlinePathParameters??this.args.inlinePathParameters,objectQueryParameters:i?.objectQueryParameters??this.args.objectQueryParameters}}),authOverrides:this.args.generatorsConfiguration?.api?.auth!=null?{...this.args.generatorsConfiguration?.api}:void 0,environmentOverrides:this.args.generatorsConfiguration?.api?.environments!=null?{...this.args.generatorsConfiguration?.api}:void 0,globalHeaderOverrides:this.args.generatorsConfiguration?.api?.headers!=null?{...this.args.generatorsConfiguration?.api}:void 0});return{absoluteFilePath:n??this.args.absoluteFilePath,rootApiFile:{defaultUrl:a.rootApiFile["default-url"],contents:a.rootApiFile,rawContents:rp.dump(a.rootApiFile)},namedDefinitionFiles:{...od(a.definitionFiles,u=>({absoluteFilepath:n??this.args.absoluteFilePath,rawContents:rp.dump(u),contents:u})),[ry.of(W1)]:{absoluteFilepath:n??this.args.absoluteFilePath,rawContents:rp.dump(a.packageMarkerFile),contents:a.packageMarkerFile}},packageMarkers:{},importedDefinitions:{}}}};var Cla=class extends F8t{inlinePathParameters;objectQueryParameters;onlyIncludeReferencedSchemas;respectReadonlySchemas;respectNullableSchemas;exampleGeneration;converter;constructor(t){super(t),this.inlinePathParameters=t.inlinePathParameters,this.objectQueryParameters=t.objectQueryParameters,this.onlyIncludeReferencedSchemas=t.onlyIncludeReferencedSchemas,this.respectReadonlySchemas=t.respectReadonlySchemas,this.respectNullableSchemas=t.respectNullableSchemas,this.exampleGeneration=t.exampleGeneration,this.converter=new TEo(t)}async getDefinition({context:t,absoluteFilePath:r,relativePathToDependency:i},n){let a=await this.getOpenAPIIr({context:t,relativePathToDependency:i},n);return this.converter.convert({context:t,ir:a,settings:n,absoluteFilePath:r})}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new cSe({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:i,cliVersion:this.cliVersion})}};function qPn(e){if(e.settings==null)return;let t={detectGlobalHeaders:!0};return e.settings.unions==="v1"&&(t.discriminatedUnionV2=!0),t}var p6p=vi(Cqo(),1);var kU={BEARER_FORMAT:"x-bearer-format",ENUM_VAR_NAMES:"x-enum-varnames",INTERNAL:"x-internal",EXAMPLES:"x-examples",TAGS:"x-tags",REDOCLY_CODE_SAMPLES_KEBAB:"x-code-samples",REDOCLY_CODE_SAMPLES_CAMEL:"x-codeSamples"};var Cfa={of(e){return e}};var z3p={properties:{"stream-condition":{type:"string"},response:"Schema","response-stream":"Schema"},required:["stream-condition","response","response-stream"],extensionsPrefix:"x-"},n9s={id:"",typeExtension:{oas3:e=>({...e,XFernStreaming:z3p,Operation:{...e.Operation,properties:{...e.Operation?.properties,"x-fern-streaming":"XFernStreaming"}}})}},fd={SOURCE:Cfa.of("source"),SDK_METHOD_NAME:Cfa.of("x-fern-sdk-method-name"),SDK_GROUP_NAME:Cfa.of("x-fern-sdk-group-name"),REQUEST_NAME_V1:"x-request-name",REQUEST_NAME_V2:"x-fern-request-name",TYPE_NAME:"x-fern-type-name",BOOLEAN_LITERAL:"x-fern-boolean-literal",SERVER_NAME_V1:"x-name",SERVER_NAME_V2:"x-fern-server-name",BASE_PATH:"x-fern-base-path",GROUPS:Cfa.of("x-fern-groups"),OPENAPI_OVERIDES_FILEPATH:"x-fern-overrides-filepath",TYPE_DEFINITION:"x-fern-type",STREAMING:"x-fern-streaming",PAGINATION:"x-fern-pagination",WEBHOOK:"x-fern-webhook",ASYNC_CONFIG:"x-fern-async-config",SDK_VARIABLES:"x-fern-sdk-variables",SDK_VARIABLE:"x-fern-sdk-variable",PARAMETER_NAME:"x-fern-parameter-name",BASIC_AUTH_USERNAME_VARIABLE_NAME:"x-fern-username-variable-name",BASIC_AUTH_PASSWORD_VARIABLE_NAME:"x-fern-password-variable-name",BEARER_TOKEN_VARIABLE_NAME:"x-fern-token-variable-name",HEADER_VARIABLE_NAME:"x-fern-header-variable-name",FERN_ENUM:"x-fern-enum",AUDIENCES:"x-fern-audiences",IGNORE:"x-fern-ignore",AVAILABILITY:"x-fern-availability",RESPONSE_PROPERTY:"x-fern-sdk-return-value",RESOLUTIONS:"x-fern-resolutions",EXAMPLES:"x-fern-examples",FERN_BEARER_TOKEN:"x-fern-bearer",FERN_HEADER_AUTH:"x-fern-header",FERN_BASIC_AUTH:"x-fern-basic",FERN_GLOBAL_HEADERS:"x-fern-global-headers",FERN_IDEMPOTENCY_HEADERS:"x-fern-idempotency-headers",IDEMPOTENT:"x-fern-idempotent",FERN_PROPERTY_NAME:"x-fern-property-name",IS_UNDISCRIMINATED:"x-fern-undiscriminated",FERN_VERSION:"x-fern-version",ENCODING:"x-fern-encoding",TRANSPORT:"x-fern-transport"};var Y$={disableExamples:!1,discriminatedUnionV2:!1,useTitlesAsName:!0,audiences:void 0,optionalAdditionalProperties:!0,coerceEnumsToLiterals:!0,respectReadonlySchemas:!1,respectNullableSchemas:!1,onlyIncludeReferencedSchemas:!1,inlinePathParameters:!1,preserveSchemaIds:!1,objectQueryParameters:!1,shouldUseUndiscriminatedUnionsWithLiterals:!1,shouldUseIdiomaticRequestNames:!1,filter:void 0,asyncApiNaming:"v1",exampleGeneration:void 0,defaultFormParameterEncoding:"json"};function a9s({options:e,overrides:t}){return{disableExamples:t?.disableExamples??Y$.disableExamples,discriminatedUnionV2:t?.discriminatedUnionV2??e?.discriminatedUnionV2??Y$.discriminatedUnionV2,useTitlesAsName:t?.useTitlesAsName??e?.useTitlesAsName??Y$.useTitlesAsName,audiences:t?.audiences??e?.audiences??Y$.audiences,optionalAdditionalProperties:t?.optionalAdditionalProperties??e?.optionalAdditionalProperties??Y$.optionalAdditionalProperties,coerceEnumsToLiterals:t?.coerceEnumsToLiterals??e?.coerceEnumsToLiterals??Y$.coerceEnumsToLiterals,respectReadonlySchemas:t?.respectReadonlySchemas??e?.respectReadonlySchemas??Y$.respectReadonlySchemas,respectNullableSchemas:t?.respectNullableSchemas??e?.respectNullableSchemas??Y$.respectNullableSchemas,onlyIncludeReferencedSchemas:t?.onlyIncludeReferencedSchemas??e?.onlyIncludeReferencedSchemas??Y$.onlyIncludeReferencedSchemas,inlinePathParameters:t?.inlinePathParameters??e?.inlinePathParameters??Y$.inlinePathParameters,preserveSchemaIds:t?.preserveSchemaIds??Y$.preserveSchemaIds,shouldUseUndiscriminatedUnionsWithLiterals:t?.shouldUseUndiscriminatedUnionsWithLiterals??e?.shouldUseUndiscriminatedUnionsWithLiterals??Y$.shouldUseUndiscriminatedUnionsWithLiterals,shouldUseIdiomaticRequestNames:t?.shouldUseIdiomaticRequestNames??e?.shouldUseIdiomaticRequestNames??Y$.shouldUseIdiomaticRequestNames,objectQueryParameters:t?.objectQueryParameters??e?.objectQueryParameters??Y$.objectQueryParameters,filter:t?.filter??e?.filter??Y$.filter,asyncApiNaming:t?.asyncApiNaming??e?.asyncApiNaming??Y$.asyncApiNaming,exampleGeneration:t?.exampleGeneration??e?.exampleGeneration??void 0,defaultFormParameterEncoding:t?.defaultFormParameterEncoding??e?.defaultFormParameterEncoding??void 0}}var R3p={naming:"v1"};function bf(e,t){let r=Array.isArray(t)?t:[t];for(let i of r){let n=e[i];if(n!=null)return n}}function Bfa(e,t,r,i,n=[]){try{let a=bf(e,t);if(a!=null)return r.parse(a)}catch{let u=CCe(n).join(" -> ");i.error(`${u.length>0?`${u}: `:""}Failed to parse ${t}`)}}function MIi(e){let t=bf(e,"examples");return t!=null&&Array.isArray(t)?t:[]}function N3p({schema:e,logger:t}){return bf(e,fd.ENCODING)??void 0}function F3p(e){return bf(e,fd.FERN_ENUM)}function L3p({nameOverride:e,generatedName:t,title:r,schema:i,description:n,availability:a}){let u=bf(i,fd.SDK_GROUP_NAME),l=bf(i,fd.TYPE_DEFINITION);if(l!=null)return xfa({fernType:l,nameOverride:e,generatedName:t,title:r,description:n,availability:a,groupName:typeof u=="string"?[u]:u})}function xfa({fernType:e,nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u}){return yU({type:e,_default:void 0,validation:void 0,visitor:{primitive:l=>{switch(l.v1){case"BASE_64":return El.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:Jd.base64({example:void 0})});case"BOOLEAN":return El.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:Jd.boolean({default:void 0,example:void 0})});case"DATE":return El.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:Jd.date({example:void 0})});case"DATE_TIME":return El.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:Jd.datetime({example:void 0})});case"FLOAT":return El.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:Jd.float({example:void 0})});case"DOUBLE":return El.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:Jd.double({default:void 0,minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,example:void 0})});case"UINT":return El.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:Jd.uint({default:void 0,example:void 0})});case"INTEGER":return El.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:Jd.int({default:void 0,minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,example:void 0})});case"UINT_64":return El.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:Jd.uint64({default:void 0,example:void 0})});case"LONG":return El.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:Jd.int64({default:void 0,example:void 0})});case"STRING":case"UUID":case"BIG_INTEGER":return El.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:Jd.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})});default:Ko(l.v1)}},unknown:()=>El.unknown({nameOverride:t,generatedName:r,title:i,example:void 0,description:n,availability:a,groupName:u}),map:({keyType:l,valueType:d})=>l?.type==="primitive"&&d!=null?El.map({nameOverride:t,generatedName:r,title:i,key:l,value:d,description:n,availability:a,groupName:u,encoding:void 0,example:void 0,inline:void 0}):void 0,list:l=>l!=null?El.array({nameOverride:t,generatedName:r,title:i,value:l,description:n,availability:a,groupName:u,example:void 0,inline:void 0}):void 0,optional:l=>l!=null?El.optional({nameOverride:t,generatedName:r,title:i,value:l,description:n,availability:a,groupName:u,inline:void 0}):void 0,nullable:l=>l!=null?El.nullable({nameOverride:t,generatedName:r,title:i,value:l,description:n,availability:a,groupName:u,inline:void 0}):void 0,set:l=>l!=null?El.array({nameOverride:t,generatedName:r,title:i,value:l,description:n,availability:a,groupName:u,example:void 0,inline:void 0}):void 0,literal:l=>El.literal({nameOverride:t,generatedName:r,title:i,value:l._visit({string:d=>YB.string(d),boolean:d=>YB.boolean(d),_other:()=>{throw new Error("Unexpected literal type")}}),description:n,availability:a,groupName:u}),named:()=>{}}})}function U3p(e){let t=bf(e,fd.SOURCE);if(t!=null)return t.endsWith(".proto")?Kre.protobuf({file:t}):Kre.openapi({file:t})}function AIi(e){if(e!=null&&typeof e=="boolean")return e}function Kd(e){return e.$ref!=null}function V3p({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,additionalProperties:n,description:a,availability:u,wrapAsNullable:l,context:d,groupName:s,example:o,encoding:c,source:b,namespace:g}){return typeof n=="boolean"||mjn(n)?Bqo({nameOverride:e,generatedName:t,title:r,wrapAsNullable:l,description:a,availability:u,keySchema:{nameOverride:void 0,generatedName:`${t}Key`,title:void 0,description:void 0,availability:void 0,schema:Jd.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:void 0}),groupName:void 0},valueSchema:El.unknown({nameOverride:void 0,generatedName:`${t}Value`,title:void 0,description:void 0,availability:void 0,example:void 0,groupName:void 0}),groupName:s,example:o,encoding:c}):Bqo({nameOverride:e,generatedName:t,title:r,wrapAsNullable:l,description:a,availability:u,keySchema:{nameOverride:void 0,generatedName:`${t}Key`,title:void 0,description:void 0,availability:void 0,schema:Jd.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:void 0}),groupName:void 0},valueSchema:W3p(Pb(n,d.options.optionalAdditionalProperties?l:!1,d,[...i,"Value"],b,g,void 0,void 0,void 0)),groupName:s,example:o,encoding:c})}function W3p(e){switch(e.type){case"array":case"enum":case"map":case"object":e.inline=!0;break;case"literal":case"primitive":case"reference":case"unknown":break;case"nullable":case"optional":e.inline=!0,e.value=W3p(e.value);break;case"oneOf":e.value.inline=!0;break;default:Ko(e)}return e}function Bqo({nameOverride:e,generatedName:t,title:r,keySchema:i,valueSchema:n,wrapAsNullable:a,description:u,availability:l,groupName:d,example:s,encoding:o}){return a?El.nullable({nameOverride:e,generatedName:t,title:r,value:El.map({nameOverride:e,generatedName:t,title:r,description:u,availability:i.availability,key:i,value:n,groupName:d,encoding:o,example:s,inline:void 0}),description:u,availability:l,groupName:d,inline:void 0}):El.map({nameOverride:e,generatedName:t,title:r,description:u,availability:l,key:i,value:n,groupName:d,encoding:o,example:s,inline:void 0})}function mjn(e){return e==null?!1:typeof e=="boolean"?e:!Kd(e)&&Object.keys(e).length===0}function H3p({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,item:n,description:a,availability:u,wrapAsNullable:l,context:d,groupName:s,example:o,source:c,namespace:b}){let g=n==null?El.unknown({nameOverride:e,generatedName:t,title:r,description:void 0,availability:void 0,example:void 0,groupName:s}):Pb(n,!1,d,[...i,"Item"],c,b);return uDD({nameOverride:e,generatedName:t,title:r,groupName:s,itemSchema:g,wrapAsNullable:l,description:a,availability:u,example:o})}function uDD({nameOverride:e,generatedName:t,title:r,itemSchema:i,wrapAsNullable:n,description:a,availability:u,groupName:l,example:d}){return n?El.nullable({nameOverride:e,generatedName:t,title:r,value:El.array({nameOverride:e,generatedName:t,title:r,value:i,description:a,availability:u,groupName:l,example:d,inline:void 0}),description:a,availability:u,groupName:l,inline:void 0}):El.array({nameOverride:e,generatedName:t,title:r,value:i,description:a,availability:u,groupName:l,example:d,inline:void 0})}function nie(e){switch(bf(e,fd.AVAILABILITY)){case"deprecated":return $U.Deprecated;case"beta":return $U.Beta;case"generally-available":return $U.GenerallyAvailable;default:break}if(!Kd(e)&&e.deprecated)return $U.Deprecated}function o9s({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,availability:u,required:l,wrapAsNullable:d,discriminator:s,context:o,groupName:c,encoding:b,source:g,namespace:O}){let m=s.propertyName,w=Object.fromEntries(Object.entries(s.mapping??{}).map(([A,q])=>{let D=Pjn({$ref:q},!1,o,[q],b,g,O);return o.markReferencedByDiscriminatedUnion({$ref:q},m,1),[A,D]})),E=Object.entries(n).filter(([A])=>A!==m).map(([A,q])=>{let D=l!=null&&l.includes(A),C=Pb(q,!D,o,[...i,A],g,O);return{key:A,schema:C}});return $3p({nameOverride:e,generatedName:t,title:r,wrapAsNullable:d,properties:E,description:a,availability:u,discriminant:m,subtypes:w,groupName:c,source:g})}function u9s({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,availability:u,required:l,wrapAsNullable:d,discriminant:s,variants:o,context:c,groupName:b,encoding:g,source:O,namespace:m}){let w=Object.fromEntries(Object.entries(o).map(([A,q])=>{if(Kd(q)){let D=Pjn(q,!1,c,[q.$ref],g,O,m);return c.markReferencedByDiscriminatedUnion(q,s,1),[A,D]}else{let D=jjn(q,!1,c,[...i,A],g,O,m,new Set([s]));return[A,D]}})),E=Object.entries(n).filter(([A])=>A!==s).map(([A,q])=>{let D=l!=null&&l.includes(A),C=Pb(q,!D,c,[...i,A],O,m);return{key:A,schema:C}});return $3p({nameOverride:e,generatedName:t,title:r,wrapAsNullable:d,properties:E,description:a,availability:u,discriminant:s,subtypes:w,groupName:b,source:O})}function $3p({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,properties:n,description:a,availability:u,discriminant:l,subtypes:d,groupName:s,source:o}){return i?El.nullable({nameOverride:e,generatedName:t,title:r,value:El.oneOf(PY.discriminated({description:a,availability:u,discriminantProperty:l,nameOverride:e,generatedName:t,title:r,schemas:d,commonProperties:n,groupName:s,encoding:void 0,source:o,inline:void 0})),groupName:s,description:a,availability:u,inline:void 0}):El.oneOf(PY.discriminated({description:a,availability:u,discriminantProperty:l,nameOverride:e,generatedName:t,title:r,schemas:d,commonProperties:n,groupName:s,encoding:void 0,source:o,inline:void 0}))}function G3p(e){if(e.proto!=null)return Xmn.protobuf({typeName:e.proto.type})}function SYt({nameOverride:e,generatedName:t,title:r,fernEnum:i,enumVarNames:n,enumValues:a,_default:u,description:l,availability:d,wrapAsNullable:s,groupName:o,context:c,source:b,inline:g}){let O=cDD(n??[]),m=new Set(a),w=Array.from(m).map((A,q)=>{let D=i?.[A],C=O[q],R=SPn.test(A),$=D?.name??C,I=R?A:DPn(A);return $!=null&&!SPn.test($)&&(c?.logger.warn(`Enum name override ${$} is not a valid name. Falling back on ${I}.`),$=void 0),{nameOverride:$,generatedName:I,value:A,description:D?.description,availability:d,casing:{snake:D?.casing?.snake??void 0,pascal:D?.casing?.pascal??void 0,screamingSnake:D?.casing?.screamingSnake??void 0,camel:D?.casing?.camel??void 0}}}),E=u!=null?w.find(A=>A.value===u):void 0;return sDD({wrapAsNullable:s,nameOverride:e,generatedName:t,title:r,values:w,_default:E,description:l,availability:d,groupName:o,source:b,inline:g})}function sDD({wrapAsNullable:e,nameOverride:t,generatedName:r,title:i,values:n,_default:a,description:u,availability:l,groupName:d,source:s,inline:o}){return e?El.nullable({nameOverride:t,generatedName:r,title:i,value:El.enum({nameOverride:t,generatedName:r,title:i,values:n,description:u,default:a,availability:l,example:void 0,groupName:d,source:s,inline:o}),description:u,availability:l,groupName:d,inline:o}):El.enum({nameOverride:t,generatedName:r,title:i,values:n,description:u,availability:l,default:a,example:void 0,groupName:d,source:s,inline:o})}function cDD(e){if(e.length<=1||e[0]==null)return e;let t=e[0],r=0;for(;t[r]!=null&&e.every(i=>i[r]===t[r]);)r++;return e.map(i=>i.substring(r))}function Q3p({nameOverride:e,generatedName:t,title:r,format:i,_default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,description:o,availability:c,wrapAsNullable:b,example:g,groupName:O}){return i==="int64"?n5({nameOverride:e,generatedName:t,title:r,primitive:Jd.int64({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="uint32"?n5({nameOverride:e,generatedName:t,title:r,primitive:Jd.uint({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="uint64"?n5({nameOverride:e,generatedName:t,title:r,primitive:Jd.uint64({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):n5({nameOverride:e,generatedName:t,title:r,primitive:Jd.int({default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O})}function J3p(e){return typeof e=="string"?YB.string(e):typeof e=="boolean"?YB.boolean(e):YB.string(`${e}`)}function K3p({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,value:n,description:a,availability:u,groupName:l}){return i?El.nullable({nameOverride:e,generatedName:t,title:r,value:El.literal({nameOverride:e,generatedName:t,title:r,value:J3p(n),description:a,availability:u,groupName:l}),description:a,availability:u,groupName:l,inline:void 0}):El.literal({nameOverride:e,generatedName:t,title:r,value:J3p(n),description:a,availability:u,groupName:l})}function s9s({nameOverride:e,generatedName:t,title:r,format:i,_default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,description:o,availability:c,wrapAsNullable:b,example:g,groupName:O}){return i==null||i==="double"?n5({nameOverride:e,generatedName:t,title:r,primitive:Jd.double({default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="float"?n5({nameOverride:e,generatedName:t,title:r,primitive:Jd.float({example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="int32"?n5({nameOverride:e,generatedName:t,title:r,primitive:Jd.int({default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="int64"?n5({nameOverride:e,generatedName:t,title:r,primitive:Jd.int64({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="uint32"?n5({nameOverride:e,generatedName:t,title:r,primitive:Jd.uint({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="uint64"?n5({nameOverride:e,generatedName:t,title:r,primitive:Jd.uint64({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="time-delta"?n5({nameOverride:e,generatedName:t,title:r,primitive:Jd.float({example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):n5({nameOverride:e,generatedName:t,title:r,primitive:Jd.float({example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O})}var lDD={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="schemas",applyStrategy:e=>{let t=[e[3]??""];return{refUnderProcessing:e.slice(4),newBreadcrumbs:t}}},fDD={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="responses",applyStrategy:e=>{let t=[e[3]??""];return e=e.slice(4),{refUnderProcessing:e.slice(4),newBreadcrumbs:t}}},dDD={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="parameters",applyStrategy:e=>{let t=[e[3]??""];return e=e.slice(4),e[0]==="schema"&&(e=e.slice(1)),{refUnderProcessing:e,newBreadcrumbs:t}}},pDD={isApplicable:e=>e[0]==="properties",applyStrategy:e=>{let t=[e[1]??""];return{refUnderProcessing:e.slice(2),newBreadcrumbs:t}}},_DD={isApplicable:e=>e[0]==="items",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},hDD={isApplicable:e=>e[0]==="allOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},yDD={isApplicable:e=>e[0]==="anyOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},vDD={isApplicable:e=>e[0]==="oneOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})};function xqo(e){let t=e.split("/").map(a=>a.replace(/~1/g,"/")),r=[],i=[lDD,fDD,dDD,pDD,_DD,hDD,yDD,vDD],n;do{n=t;for(let a of i)if(a.isApplicable(t)){let{refUnderProcessing:u,newBreadcrumbs:l}=a.applyStrategy(t);t=u,r=[...r,...l]}}while(t.join("")!==n.join(""));return r}function s2(e,t){let i=e.map(n=>/^[^a-zA-Z0-9]+$/.test(n)?n:q3(vg(n))).join("");return/^\d/.test(i)?Ela(i)??i:i}function c9s(e){let t=e.join("_");return vg(t)}function kD(e){switch(e.type){case"object":return py.object({allOf:e.allOf,properties:e.properties.map(t=>gDD(t)),allOfPropertyConflicts:e.allOfPropertyConflicts,description:e.description,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName,additionalProperties:e.additionalProperties,availability:e.availability,source:e.source,inline:e.inline});case"array":return py.array({description:e.description,availability:e.availability,value:kD(e.value),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName,inline:e.inline});case"enum":return py.enum({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,values:e.values,default:e.default,groupName:e.groupName,source:e.source,inline:e.inline});case"literal":return py.literal({description:e.description,availability:e.availability,value:e.value,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName});case"nullable":return py.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:kD(e.value),groupName:e.groupName,inline:e.inline});case"optional":return py.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:kD(e.value),groupName:e.groupName,inline:e.inline});case"primitive":return py.primitive({description:e.description,availability:e.availability,schema:Y3p(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName});case"map":return py.map({description:e.description,availability:e.availability,key:py.primitive({description:e.key.description,availability:e.key.availability,schema:Y3p(e.key.schema),generatedName:e.key.generatedName,title:e.key.title,nameOverride:e.key.nameOverride,groupName:e.groupName}),value:kD(e.value),generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,groupName:e.groupName,encoding:e.encoding,inline:e.inline});case"reference":return py.reference({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schema:e.schema,groupName:e.groupName,source:e.source});case"oneOf":return py.oneOf(bDD(e.value));case"unknown":return py.unknown({nameOverride:e.nameOverride,generatedName:e.generatedName});default:Ko(e)}}function bDD(e){switch(e.type){case"discriminated":return QGr.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:kD(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,kD(r)])),groupName:e.groupName,encoding:e.encoding,source:e.source,inline:e.inline});case"undiscriminated":return QGr.undiscriminated({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schemas:e.schemas.map(t=>kD(t)),groupName:e.groupName,encoding:e.encoding,source:e.source,inline:e.inline});default:Ko(e)}}function Y3p(e){switch(e.type){case"string":return sj.string(e);case"base64":return sj.base64();case"boolean":return sj.boolean(e);case"date":return sj.date();case"datetime":return sj.datetime();case"double":return sj.double(e);case"float":return sj.float();case"int":return sj.int(e);case"int64":return sj.int64(e);case"uint":return sj.uint();case"uint64":return sj.uint64();default:Ko(e)}}function gDD(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:kD(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly,writeonly:e.writeonly}}function Iqo(e,t){return Zre(kD(e),kD(t))}function X3p({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,required:u,wrapAsNullable:l,allOf:d,context:s,propertiesToExclude:o,groupName:c,fullExamples:b,additionalProperties:g,availability:O,encoding:m,source:w,namespace:E}){let A=[...u??[]],q={...n},D=[],C=[];for(let U of d)if(Kd(U)){let H=s.resolveSchemaReference(U);if(H.discriminator!=null&&H.discriminator.mapping!=null)continue;if(H.oneOf!=null){for(let K of H.oneOf){let te=Kd(K)?s.resolveSchemaReference(K):K,fe=Pb(te,!1,s.DUMMY,i,w,E);fe.type==="object"&&D.push(...fe.properties.map(me=>me.schema.type!=="optional"&&me.schema.type!=="nullable"?{...me,schema:El.optional({nameOverride:void 0,generatedName:"",title:void 0,value:me.schema,description:void 0,availability:me.availability,groupName:void 0,inline:void 0})}:me))}continue}let k=Nli(U);if(k==null)continue;C.push({schemaId:k,convertedSchema:l9s(U,[k],w,s.options.preserveSchemaIds),properties:Z3p({schema:U,context:s,breadcrumbs:i,source:w,namespace:E})}),s.markSchemaAsReferencedByNonRequest(k)}else{let H=Pb(U,!1,s,i,w,E);H.type==="object"&&D.push(...H.properties)}let R={};for(let U of C)for(let[H,k]of Object.entries(U.properties)){let K=R[H];K!=null?(K.schemaIds.push(U.schemaId),K.schemas.some(fe=>Iqo(fe,k))||K.schemas.push(k)):R[H]={schemaIds:[U.schemaId],schemas:[k]}}let $=[];for(let[U,H]of Object.entries(R))H.schemaIds.length>1&&$.push({propertyKey:U,allOfSchemaIds:H.schemaIds,conflictingTypeSignatures:H.schemas.length>1});let I=Object.entries(q).map(([U,H])=>{let k=A.includes(U),K=bf(H,fd.AUDIENCES)??[],te=nie(H),fe=Kd(H)?!1:H.readOnly,me=Kd(H)?!1:H.writeOnly,be=bf(H,fd.FERN_PROPERTY_NAME),we=[...i,U],Ze=c9s(we),Mt=k?Pb(H,!1,s,we,w,E):El.optional({nameOverride:e,generatedName:Ze,title:r,description:void 0,availability:te,value:Pb(H,!1,s,we,w,E),groupName:c,inline:void 0}),De={};for(let Te of C){let xt=Te.properties[U];xt!=null&&!Iqo(Mt,xt)?De[Te.schemaId]={differentSchema:!0}:xt!=null&&(De[Te.schemaId]={differentSchema:!1})}return{key:U,schema:Mt,nameOverride:be,audiences:K,conflict:De,generatedName:c9s([...i,U]),availability:te,readonly:fe,writeonly:me}});return I.push(...D.map(U=>{let H=U.conflict;for(let k of C){let K=k.properties[U.key];K!=null&&!Iqo(U.schema,K)?H[k.schemaId]={differentSchema:!0}:K!=null&&(H[k.schemaId]={differentSchema:!1})}return{...U,conflict:H}})),ODD({nameOverride:e,generatedName:t,title:r,wrapAsNullable:l,properties:I.filter(U=>!o.has(U.key)),description:a,allOf:C.map(U=>U.convertedSchema),allOfPropertyConflicts:$,groupName:c,fullExamples:b,additionalProperties:g,availability:O,source:w})}function ODD({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,properties:n,description:a,allOf:u,allOfPropertyConflicts:l,groupName:d,fullExamples:s,additionalProperties:o,availability:c,source:b}){return i?El.nullable({nameOverride:e,generatedName:t,title:r,value:El.object({description:a,properties:n,nameOverride:e,generatedName:t,title:r,allOf:u,allOfPropertyConflicts:l,groupName:d,fullExamples:s,additionalProperties:mjn(o),availability:void 0,source:b,inline:void 0}),description:a,availability:c,groupName:d,inline:void 0}):El.object({description:a,properties:n,nameOverride:e,generatedName:t,title:r,allOf:u,allOfPropertyConflicts:l,groupName:d,fullExamples:s,additionalProperties:mjn(o),availability:c,source:b,inline:void 0})}function Z3p({schema:e,context:t,breadcrumbs:r,source:i,namespace:n}){let a={},[u,l]=Kd(e)?[t.resolveSchemaReference(e),xqo(e.$ref)]:[e,r];for(let d of u.allOf??[])a={...a,...Z3p({schema:d,context:t,breadcrumbs:l,source:i,namespace:n})};for(let[d,s]of Object.entries(u.properties??{})){let o=Pb(s,!1,t,[...l,d],i,n);a[d]=o}return a}function k3p({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,description:n,availability:a,wrapAsNullable:u,context:l,subtypes:d,groupName:s,encoding:o,source:c,subtypePrefixOverrides:b,namespace:g}){let O=e7p(d);return t7p({uniqueSubtypes:O,nameOverride:e,generatedName:t,title:r,wrapAsNullable:u,description:n,availability:a,groupName:s,context:l,encoding:o,source:c})}function wjn({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,description:n,availability:a,wrapAsNullable:u,context:l,subtypes:d,groupName:s,encoding:o,source:c,subtypePrefixOverrides:b,namespace:g}){let O=mDD({schemas:d}),m=d.flatMap((E,A)=>{if(!Kd(E)&&E.enum!=null&&l.options.coerceEnumsToLiterals&&E.type==="string")return E.enum.map(D=>El.literal({nameOverride:void 0,generatedName:s2([t,D],l.options.preserveSchemaIds),title:void 0,value:YB.string(String(D)),groupName:void 0,description:void 0,availability:D.availability}));let q=O[A];if(b!=null){let D=b[A];D!=null&&"name"in D&&(q=D.name)}return[Pb(E,!1,l,[...i,q??`${A}`],c,g)]}),w=e7p(m);return t7p({uniqueSubtypes:w,nameOverride:e,generatedName:t,title:r,wrapAsNullable:u,description:n,availability:a,groupName:s,context:l,encoding:o,source:c})}function e7p(e){let t=[];for(let r=0;r<e.length;++r){let i=e[r],n=!1;for(let a=r+1;a<e.length;++a){let u=e[a];if(i!=null&&u!=null&&Zre(i,u)){n=!0;break}}i!=null&&!n&&t.push(i)}return t}function t7p({uniqueSubtypes:e,nameOverride:t,generatedName:r,title:i,wrapAsNullable:n,description:a,availability:u,groupName:l,context:d,encoding:s,source:o}){if(Object.entries(e).every(([b,g])=>g.type==="literal")){let b={},g=[];return Object.entries(e).forEach(([O,m])=>{m.type==="literal"&&m.value.type==="string"&&(g.push(m.value.value),m.description!=null&&(b[m.value.value]={description:m.description}))}),SYt({nameOverride:t,generatedName:r,title:i,wrapAsNullable:n,description:a,availability:u,fernEnum:b,enumVarNames:void 0,enumValues:g,_default:void 0,groupName:l,context:d,source:o,inline:void 0})}return e.length===1&&e[0]!=null?e[0]:r7p({nameOverride:t,generatedName:r,title:i,wrapAsNullable:n,description:a,availability:u,subtypes:e,groupName:l,encoding:s,source:o})}function f9s({nameOverride:e,generatedName:t,title:r,description:i,availability:n,wrapAsNullable:a,context:u,groupName:l,discriminator:d,encoding:s,source:o,namespace:c}){let b=Object.entries(d.mapping??{}).map(([m,w],E)=>{let A={$ref:w},q=Pjn(A,!1,u,[w],s,o,c);return u.markSchemaWithDiscriminantValue(A,d.propertyName,m),q.type==="object"&&(q.properties={[d.propertyName]:El.literal({nameOverride:void 0,generatedName:s2([t,m],u.options.preserveSchemaIds),title:void 0,value:YB.string(m),groupName:void 0,description:void 0,availability:void 0}),...q.properties.filter(D=>D.key!==d.propertyName)}),q}),g=[];for(let m=0;m<b.length;++m){let w=b[m],E=!1;for(let A=m+1;A<b.length;++A){let q=b[A];if(w!=null&&q!=null&&Zre(w,q)){E=!0;break}}w!=null&&!E&&g.push(w)}if(Object.entries(g).every(([m,w])=>w.type==="literal")){let m={},w=[];return Object.entries(g).forEach(([E,A])=>{A.type==="literal"&&A.value.type==="string"&&(w.push(A.value.value),A.description!=null&&(m[A.value.value]={description:A.description}))}),SYt({nameOverride:e,generatedName:t,title:r,wrapAsNullable:a,description:i,availability:n,fernEnum:m,enumVarNames:void 0,enumValues:w,_default:void 0,groupName:l,context:u,source:o,inline:void 0})}return g.length===1&&g[0]!=null?g[0]:r7p({nameOverride:e,generatedName:t,title:r,wrapAsNullable:a,description:i,availability:n,subtypes:g,groupName:l,encoding:s,source:o})}function mDD({schemas:e}){let t={},r=0;for(let a of e){if(!Kd(a)){if(a.properties!=null&&Object.entries(a.properties).length>0){let u=Object.keys(a.properties),l={},d=u;for(let[s,o]of Object.entries(t)){let c=bGa(o,u);d=bGa(d,o),l[s]=c}l[r]=d,t=l}}r++}let i=[],n=0;for(let a of e){let u=t[n];if(u!=null&&u.length>0){let l=u.sort();if(l[0]!=null){i.push(l[0]),++n;continue}}Kd(a)?i.push(lli(n)??`${n}`):a.type==="array"||a.type==="boolean"||a.type==="integer"||a.type==="number"||a.type==="string"?i.push(""):i.push(lli(n)??`${n}`),++n}return i}function r7p({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,description:n,availability:a,subtypes:u,groupName:l,encoding:d,source:s}){return i?El.nullable({nameOverride:e,generatedName:t,title:r,value:El.oneOf(PY.undiscriminated({description:n,availability:a,nameOverride:e,generatedName:t,title:r,schemas:u,groupName:l,encoding:d,source:s,inline:void 0})),description:n,availability:a,groupName:l,inline:void 0}):El.oneOf(PY.undiscriminated({description:n,availability:a,nameOverride:e,generatedName:t,title:r,schemas:u,groupName:l,encoding:d,source:s,inline:void 0}))}function Sjn(e){if(e.default!=null&&typeof e.default=="string")return e.default}function zqo({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="number")return e.example;let i=MIi(e);for(let n of i??[])if(typeof n=="number")return n;if(r&&typeof r=="number")return r}function i7p({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="boolean")return e.example;let i=MIi(e);for(let n of i??[])if(typeof n=="boolean")return n;if(r&&typeof r=="boolean")return r}function oQr({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="string")return e.example;let i=MIi(e);for(let n of i??[])if(typeof n=="string")return n;if(r&&typeof r=="string")return r}function n7p({schema:e,logger:t,fallback:r}){if(e.example!=null&&Array.isArray(e.example))return e.example;let i=MIi(e);for(let n of i??[])if(Array.isArray(n))return n;if(r&&Array.isArray(r))return r}var qIi="#/components/schemas/";function Pb(e,t,r,i,n,a,u=!1,l=new Set,d){let s=U3p(e)??n,o=ADD({schema:e,logger:r.logger});if(Kd(e)){let c=Nli(e);return c!=null?(u?r.markSchemaAsReferencedByRequest(c):r.markSchemaAsReferencedByNonRequest(c),Pjn(e,t,r,i,o,s,a)):jjn(r.resolveSchemaReference(e),t,r,xqo(e.$ref),o,s,a,l,u,d)}return jjn(e,t,r,i,o,s,a,l,u,d)}function Pjn(e,t,r,i,n,a,u){let l=e.$ref.includes("properties")?jjn(r.resolveSchemaReference(e),t,r,i,n,a,u,new Set):El.reference(l9s(e,i,a,r.options.preserveSchemaIds));return t?El.nullable({title:void 0,nameOverride:void 0,generatedName:s2(i,r.options.preserveSchemaIds),value:l,description:void 0,availability:void 0,groupName:void 0,inline:void 0}):l}function PDD(e){if(e!=null&&!e.includes(" ")&&/^[a-zA-Z]+$/.test(e))return e}function jjn(e,t,r,i,n,a,u,l=new Set,d=!1,s){typeof e=="string"&&(e={type:e});let o=bf(e,fd.TYPE_NAME)??(r.options.useTitlesAsName?PDD(e.title):void 0),c=bf(e,fd.SDK_GROUP_NAME)??bf(e,kU.TAGS)?.[0],b=(typeof c=="string"?[c]:c)??[];b=r.resolveGroupName(b);let g=s2(i,r.options.preserveSchemaIds),O=e.title,m=e.description,w=nie(e),E=[];e.example!=null&&E.push({name:void 0,value:e.example,description:void 0});let A=bf(e,kU.EXAMPLES);A!=null&&Object.keys(A).length>0&&E.push(...Object.entries(A).map(([C,R])=>({name:R?.summary??C,value:R.value,description:R.description})));let q=MIi(e);q!=null&&Object.keys(q).length>0&&E.push(...q.map(C=>({name:void 0,value:C,description:void 0})));let D=L3p({schema:e,description:m,title:O,nameOverride:o,generatedName:g,availability:w});if(D!=null)return D;if(Array.isArray(e.type)){let C=e.type.indexOf("null"),R=C!==-1;e.type.length===1?e.type=e.type[0]:e.type.length===2&&R?(e.type.splice(C,1),e.type=e.type[0],e.nullable=!0):(R&&(e.type.splice(C,1),e.nullable=!0),e.oneOf==null?e.oneOf=e.type:e.oneOf.push(...e.type))}if(!t&&e.nullable===!0)return jjn(e,!0,r,i,n,a,u,l,d,s);if(e.enum!=null&&(e.type==="string"||e.type==null)){if(!Fqo(e.enum))return n5({nameOverride:o,generatedName:g,title:O,primitive:Jd.string({default:Sjn(e),minLength:e.minLength,maxLength:e.maxLength,pattern:e.pattern,format:e.format,example:oQr({schema:e,logger:r.logger,fallback:s})}),groupName:b,wrapAsNullable:t,description:m,availability:w});let C=F3p(e);return e.enum.length===1&&e.enum[0]!=null&&C==null?K3p({nameOverride:o,generatedName:g,title:O,wrapAsNullable:t,value:e.enum[0],description:m,availability:w,groupName:b}):SYt({nameOverride:o,generatedName:g,title:O,fernEnum:C,enumVarNames:bf(e,[kU.ENUM_VAR_NAMES]),enumValues:e.enum,_default:e.default,description:m,availability:w,wrapAsNullable:t,groupName:b,context:r,source:a,inline:void 0})}if(Fqo(e.type)&&e.type.length>1){let C=e.type.includes("null"),R=e.type.filter($=>$!=="null").map($=>({type:$,nullable:C}));return wjn({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,wrapAsNullable:t,context:r,subtypes:R,groupName:b,encoding:n,source:a,namespace:u})}if(e.type==="boolean"){let C=bf(e,fd.BOOLEAN_LITERAL);return C!=null?a7p({nameOverride:o,generatedName:g,title:O,literal:YB.boolean(C),wrapAsNullable:t,description:m,availability:w,groupName:b}):n5({nameOverride:o,generatedName:g,title:O,primitive:Jd.boolean({default:jDD(e.default),example:i7p({schema:e,logger:r.logger,fallback:s})}),wrapAsNullable:t,description:m,availability:w,groupName:b})}if(e.type==="number")return s9s({nameOverride:o,generatedName:g,title:O,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:AIi(e.exclusiveMinimum),exclusiveMaximum:AIi(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:w,wrapAsNullable:t,example:zqo({schema:e,logger:r.logger,fallback:s}),groupName:b});if(e.type==="integer")return Q3p({nameOverride:o,generatedName:g,title:O,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:AIi(e.exclusiveMinimum),exclusiveMaximum:AIi(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:w,wrapAsNullable:t,example:zqo({schema:e,logger:r.logger,fallback:s}),groupName:b});if(e.type==="float")return s9s({nameOverride:o,generatedName:g,title:O,format:"float",_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:AIi(e.exclusiveMinimum),exclusiveMaximum:AIi(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:w,wrapAsNullable:t,example:zqo({schema:e,logger:r.logger,fallback:s}),groupName:b});if(e.type==="string"){if(e.format==="date-time")return n5({nameOverride:o,generatedName:g,title:O,primitive:Jd.datetime({example:oQr({schema:e,logger:r.logger,fallback:s})}),wrapAsNullable:t,description:m,availability:w,groupName:b});if(e.format==="json-string")return El.unknown({nameOverride:o,generatedName:g,title:O,description:m,availability:w,groupName:b,example:void 0});let C=s7p(e,"const");return C!=null?a7p({nameOverride:o,generatedName:g,title:O,literal:YB.string(C),wrapAsNullable:t,description:m,availability:w,groupName:b}):n5({nameOverride:o,generatedName:g,title:O,primitive:Jd.string({default:Sjn(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:oQr({schema:e,logger:r.logger,fallback:s})}),groupName:b,wrapAsNullable:t,description:m,availability:w})}if(e.type==="array")return H3p({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,item:e.items,description:m,availability:w,wrapAsNullable:t,context:r,groupName:b,example:n7p({schema:e,logger:r.logger,fallback:s}),source:a,namespace:u});if(e.additionalProperties!=null&&e.additionalProperties!==!1&&Rqo(e))return V3p({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,additionalProperties:e.additionalProperties,description:m,availability:w,wrapAsNullable:t,context:r,groupName:b,encoding:n,example:e.example,source:a,namespace:u});if(e.type==="object"&&e.discriminator!=null&&e.discriminator.mapping!=null)return r.options.discriminatedUnionV2?f9s({nameOverride:o,generatedName:g,title:O,description:m,availability:w,wrapAsNullable:t,context:r,groupName:b,discriminator:e.discriminator,encoding:n,source:a,namespace:u}):o9s({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,discriminator:e.discriminator,properties:e.properties??{},required:e.required,wrapAsNullable:t,context:r,groupName:b,encoding:n,source:a,namespace:u});if(e.oneOf!=null&&e.oneOf.length>0){let C=bf(e,fd.IS_UNDISCRIMINATED);if(e.discriminator!=null&&e.discriminator.mapping!=null&&Object.keys(e.discriminator.mapping).length>0)return r.options.discriminatedUnionV2||C?f9s({nameOverride:o,generatedName:g,title:O,description:m,availability:w,wrapAsNullable:t,context:r,groupName:b,discriminator:e.discriminator,encoding:n,source:a,namespace:u}):o9s({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,discriminator:e.discriminator,properties:e.properties??{},required:e.required,wrapAsNullable:t,context:r,groupName:b,encoding:n,source:a,namespace:u});if(e.oneOf.length===1&&e.oneOf[0]!=null){let R=Pb(e.oneOf[0],t,r,i,a,u,d);return Djn(R,m,b)}else if(e.oneOf.length>1){if(e.oneOf.length===2&&e.oneOf[0]!=null&&e.oneOf[1]!=null){let U=e.oneOf[0],H=e.oneOf[1];if(!Kd(U)&&U.type==="null")return Pb(H,!0,r,i,a,u);if(!Kd(H)&&H.type==="null")return Pb(U,!0,r,i,a,u)}let R=DDD({schemas:e.oneOf});if(R!=null)return SYt({nameOverride:o,generatedName:g,title:O,fernEnum:void 0,enumVarNames:void 0,enumValues:R,_default:e.default,description:m,availability:w,wrapAsNullable:t,groupName:b,context:r,source:a,inline:void 0});let $=o7p({schemas:e.oneOf,context:r});if($!=null&&!r.options.discriminatedUnionV2&&!C)return u9s({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},required:e.required,description:m,availability:w,wrapAsNullable:t,discriminant:$.discriminant,variants:$.schemas,context:r,groupName:b,encoding:n,source:a,namespace:u});let I=e.oneOf.filter(U=>!Kd(U)&&U.type==="null").length>0;return wjn({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,wrapAsNullable:t||I,context:r,subtypes:e.oneOf.filter(U=>Kd(U)||U.type!=="null"),encoding:n,groupName:b,source:a,namespace:u})}}if(e.anyOf!=null&&e.anyOf.length>0){if(e.anyOf.length===1&&e.anyOf[0]!=null){let $=Pb(e.anyOf[0],t,r,i,a,u,d);return Djn($,m,b)}if(e.anyOf.length===2){let[$,I]=e.anyOf;if($!=null&&I!=null){if(!Kd($)&&$.type==="null"){let U=Pb(I,!0,r,i,a,u);return Djn(U,m,b)}else if(!Kd(I)&&I.type==="null"){let U=Pb($,!0,r,i,a,u);return Djn(U,m,b)}}}let C=o7p({schemas:e.anyOf,context:r});if(C!=null&&!r.options.discriminatedUnionV2)return u9s({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},required:e.required,description:m,availability:w,wrapAsNullable:t,discriminant:C.discriminant,variants:C.schemas,context:r,groupName:b,encoding:n,source:a,namespace:u});let R=e.anyOf.filter($=>!Kd($)&&$.type==="null").length>0;return wjn({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,wrapAsNullable:t||R,context:r,subtypes:e.anyOf.filter($=>Kd($)||$.type!=="null"),encoding:n,groupName:b,source:a,namespace:u})}if(e.allOf!=null||e.properties!=null){let C=[];for(let $ of e.allOf??[])(Kd($)||Object.keys($).length>0)&&C.push($);if((e.properties==null||Rqo(e))&&C.length===1&&C[0]!=null){let $=Pb(C[0],t,r,i,a,u,d);return Djn($,m,b)}let R=C.filter($=>{let I=Nqo($);return I||r.logger.warn(`Skipping non-object allOf element: ${JSON.stringify($)}`),I});if((e.properties==null||Rqo(e))&&R.length===1&&R[0]!=null){let $=Pb(R[0],t,r,i,a,u,d);return Djn($,m,b)}return X3p({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},description:m,required:e.required,wrapAsNullable:t,allOf:R,context:r,propertiesToExclude:l,groupName:b,fullExamples:E,additionalProperties:e.additionalProperties,availability:w,encoding:n,source:a,namespace:u})}if(e.type==="object"&&wDD(e)&&SDD(e)&&Rqo(e))return Bqo({nameOverride:o,generatedName:g,title:O,description:m,availability:w,wrapAsNullable:t,keySchema:{nameOverride:void 0,generatedName:`${g}Key`,title:void 0,description:void 0,availability:void 0,schema:Jd.string({default:Sjn(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:oQr({schema:e,logger:r.logger,fallback:s})}),groupName:b},valueSchema:El.unknown({nameOverride:void 0,generatedName:`${g}Value`,title:void 0,description:void 0,availability:void 0,example:void 0,groupName:b}),groupName:b,encoding:n,example:e.example});if(e.type==null){let C=e.example??e.default;return El.unknown({nameOverride:o,generatedName:g,title:O,description:m,availability:w,groupName:b,example:C})}throw new Error(`Failed to convert schema breadcrumbs=${JSON.stringify(i)} value=${JSON.stringify(e)}`)}function jDD(e){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.toLowerCase();if(t==="true")return!0;if(t==="false")return!1}}}function Nli(e){if(e.$ref.startsWith(qIi))return e.$ref.replace(qIi,"")}function l9s(e,t,r,i){let n=bf(e,fd.TYPE_NAME),a=s2(t,i),u=e.description,l=nie(e),d=Nli(e);if(d==null)throw new Error(`Invalid schema reference ${JSON.stringify(e)}`);return py.reference({generatedName:a,nameOverride:n,title:void 0,schema:d,description:u??void 0,availability:l,groupName:void 0,source:r})}function wDD(e){return e.oneOf==null||e.oneOf.length===0}function SDD(e){return e.allOf==null||e.allOf.length===0}function Rqo(e){return e.properties==null||CK(e.properties)===0}function Fqo(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function Djn(e,t,r){return e.type==="reference"?El.reference({...e,description:t,availability:e.availability,groupName:r}):e.type==="optional"?El.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:t,availability:e.availability,groupName:r,inline:void 0}):e.type==="nullable"?El.nullable({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:t,availability:e.availability,groupName:r,inline:void 0}):e}function Nqo(e){return Kd(e)||e.type==="object"||e.properties!=null?!0:e.allOf!=null?e.allOf.every(t=>Nqo(t)):e.oneOf!=null?e.oneOf.every(t=>Nqo(t)):e.anyOf!=null?e.anyOf.every(t=>Nqo(t)):!1}function a7p({literal:e,wrapAsNullable:t,groupName:r,description:i,availability:n,nameOverride:a,generatedName:u,title:l}){return t?El.nullable({nameOverride:a,generatedName:u,title:l,value:El.literal({nameOverride:a,generatedName:u,title:l,value:e,description:i,availability:n,groupName:r}),groupName:r,description:i,availability:n,inline:void 0}):El.literal({nameOverride:a,generatedName:u,title:l,value:e,groupName:r,description:i,availability:n})}function n5({primitive:e,wrapAsNullable:t,groupName:r,description:i,availability:n,generatedName:a,nameOverride:u,title:l}){return r=typeof r=="string"?[r]:r,t?El.nullable({nameOverride:u,generatedName:a,title:l,value:El.primitive({nameOverride:u,generatedName:a,title:l,schema:e,description:i,availability:n,groupName:r}),groupName:r,description:i,availability:n,inline:void 0}):El.primitive({nameOverride:u,generatedName:a,title:l,schema:e,description:i,availability:n,groupName:r})}function DDD({schemas:e}){let t=new Set;for(let r of e){if(Kd(r))return;if(r.enum!=null&&Fqo(r.enum))r.enum.forEach(i=>t.add(i));else return}return Array.from(t)}function o7p({schemas:e,context:t}){let r={};for(let i of e){let n=u7p({schema:i,context:t});for(let[a,u]of Object.entries(n)){let l=r[a];l!=null?l[u]=i:r[a]={[u]:i}}}for(let[i,n]of Object.entries(r))if(Object.keys(n).length===e.length)return{discriminant:i,schemas:n}}function u7p({schema:e,context:t}){let r=Kd(e)?t.resolveSchemaReference(e):e;return EDD({schema:r,context:t})}function EDD({schema:e,context:t}){let r={};if(e.anyOf!=null){for(let i of e.anyOf){let n=u7p({schema:i,context:t});for(let[a,u]of Object.entries(n??{}))r[a]=u}return r}for(let[i,n]of Object.entries(e.properties??{})){let a=Kd(n)?t.resolveSchemaReference(n):n;a.type==="string"&&a.enum!=null&&Fqo(a.enum)&&MDD(a.enum).length===1&&a.enum[0]!=null&&(r[i]=a.enum[0]);let u=s7p(a,"const");a.type==="string"&&u!=null&&(r[i]=u),i==="type"&&a.example!=null&&(r[i]=a.example)}return r}function MDD(e){if(!e)return[];let t=new Set;return e.forEach(r=>{typeof r=="string"?t.add(r.toLowerCase()):t.add(r)}),Array.from(t)}function s7p(e,t){let r=e[t];if(r!=null)return r}function ADD({schema:e,logger:t}){let r=N3p({schema:e,logger:t});if(r!=null)return G3p(r)}var Ejn=class{document;taskContext;logger;DUMMY;options;namespace;static MESSAGE_REFERENCE_PREFIX="#/components/messages/";constructor({document:t,taskContext:r,options:i,namespace:n}){this.document=t,this.taskContext=r,this.logger=r.logger,this.DUMMY=this,this.options=i,this.namespace=n}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveTags(t,r){if(this.namespace==null&&t==null&&r!=null)return[r];let i=[];if(this.namespace!=null){let n={type:"namespace",name:this.namespace};i.push(n)}return i.concat(t??[])}resolveSchemaReference(t){if(!t.$ref.startsWith(qIi))throw new Error(`Failed to resolve schema reference: ${t.$ref}`);let i=t.$ref.substring(qIi.length).split("/"),n=this.document.components;if(n==null||n.schemas==null)throw new Error("Document does not have components.schemas.");let[a,u,l]=i;if(a==null||a==="")throw new Error(`${t.$ref} cannot be resolved. No schema key provided.`);let d=n.schemas[a];if(d==null)throw new Error(`Schema "${a}" is undefined in document.components.schemas.`);if(Kd(d)&&(d=this.resolveSchemaReference(d)),u==="properties"&&l!=null){let s=d.properties?.[l];if(s==null)throw new Error(`Property "${l}" not found on "${a}". Full ref: ${t.$ref}`);Kd(s)?d=this.resolveSchemaReference(s):d=s}return d}referenceExists(t){let r=t.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return!1;i=i[n]}return!0}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}markReferencedByDiscriminatedUnion(t,r,i){}markSchemaWithDiscriminantValue(t,r,i){}};var Lqo=class extends Ejn{getExampleMessageReference(t){return`#/components/messages/${t.messageId}`}resolveMessageReference(t){let r="#/components/messages/",i=this.document.components;if(i==null||i.messages==null||!t.$ref.startsWith(r))throw new Error(`Failed to resolve message reference: ${t.$ref} in v2 components`);let n=t.$ref.substring(r.length),a=i.messages[n];if(a==null)throw new Error(`${t.$ref} is undefined`);return a}};function Mjn(e,t){let r={},i={};return e==null?r=t:i={[e]:t},{rootSchemas:r,namespacedSchemas:i}}function Fli(e){if(typeof e=="string")return Q0.primitive(i_.string(e));if(typeof e=="number")return Number.isInteger(e)?Q0.primitive(i_.int(e)):Q0.primitive(i_.double(e));if(typeof e=="boolean")return Q0.primitive(i_.boolean(e));if(Array.isArray(e)){let t=e.map(r=>Fli(r));return t.length===0?void 0:Q0.array(t.filter(r=>r!=null))}else if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string")){let t=[];for(let[r,i]of Object.entries(e)){let n=Fli(i);n!=null&&t.push({key:i_.string(r),value:n})}return Q0.map(t)}}function Ifa(e){if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string"))return e}function c7p(e){if(e!=null&&Array.isArray(e))return e}var Lli=class{schemas;nonRequestReferencedSchemas;context;constructor(t,r,i){this.schemas=t,this.nonRequestReferencedSchemas=r,this.context=i}buildExample({schema:t,exampleId:r,example:i,options:n,skipReadonly:a}){return this.buildExampleHelper({schema:t,visitedSchemaIds:new Set,exampleId:r,example:i,options:{...n,maxCheckerDepth:n.maxCheckerDepth??5},depth:0,skipReadonly:a??!1})}buildExampleHelper({exampleId:t,example:r,schema:i,depth:n,visitedSchemaIds:a,options:u,skipReadonly:l}){switch(i.type){case"enum":return typeof r=="string"&&l7p({schema:i,value:r})?Q0.enum(r):i.values[0]!=null?Q0.enum(i.values[0]?.value):void 0;case"literal":return Q0.literal(i.value);case"nullable":{if(r==null&&!this.hasExample(i.value,0,a,u)&&(u.ignoreOptionals||this.exceedsMaxDepth(n,u)))return;let d=this.buildExampleHelper({schema:i.value,visitedSchemaIds:a,exampleId:t,example:r,depth:n,options:u,skipReadonly:l});return d!=null&&d.type==="array"&&d.value.length===0||d!=null&&d.type==="map"&&d.value.length===0||d!=null&&d.type==="object"&&Object.keys(d.properties).length===0?void 0:d}case"optional":{if(r==null&&!this.hasExample(i.value,0,a,u)&&(u.ignoreOptionals||this.exceedsMaxDepth(n,u))||Object.is(r,null))return;let d=this.buildExampleHelper({schema:i.value,visitedSchemaIds:a,exampleId:t,example:r,depth:n,options:u,skipReadonly:l});return d!=null&&d.type==="array"&&d.value.length===0||d!=null&&d.type==="map"&&d.value.length===0||d!=null&&d.type==="object"&&Object.keys(d.properties).length===0?void 0:d}case"primitive":{let d=this.buildExampleFromPrimitive({schema:i.schema,example:r,options:u});return Q0.primitive(d)}case"reference":{let d=this.schemas[i.schema];if(d!=null&&!a.has(i.schema)){a.add(i.schema);let s=d?.type==="object"&&!this.nonRequestReferencedSchemas.has(i.schema),o=this.buildExampleHelper({example:r,schema:d,exampleId:t,visitedSchemaIds:a,depth:n,options:u,skipReadonly:s||this.context.options.respectReadonlySchemas?l:!1});return a.delete(i.schema),o}return}case"oneOf":switch(i.value.type){case"discriminated":{let d={},s={},o={},c=Ifa(r),b=c?.[i.value.discriminantProperty],g=i.value.schemas[b],O=[],m=this.getDiscriminatedUnionVariantSchema(i.value,c);m!=null&&O.push(m),O.push(...Object.entries(i.value.schemas));for(let w of O)if(b!=null&&g!=null&&g.type==="object"){s=this.getAllProperties(g),o=this.getAllRequiredProperties(g),d[i.value.discriminantProperty]=Q0.primitive(i_.string(b));break}else{let E=this.buildExampleHelper({exampleId:t,schema:w[1],example:void 0,visitedSchemaIds:a,depth:n,options:u,skipReadonly:l});if(E!=null){this.mergeExampleWith(E,d),d[i.value.discriminantProperty]=Q0.primitive(i_.string(w[0]));break}}for(let w of i.value.commonProperties){s[w.key]={schema:w.schema,readonly:!1};let E=this.getResolvedSchema(w.schema);E.type!=="optional"&&E.type!=="nullable"&&(o[w.key]=w.schema)}for(let[w,E]of Object.entries(s)){let A=w in o;if(A&&c?.[w]!=null){let q=this.buildExampleHelper({schema:E.schema,exampleId:t,example:c[w],visitedSchemaIds:a,depth:n+1,options:u,skipReadonly:l});if(q!=null)d[w]=q;else return}else{let q=this.buildExampleHelper({exampleId:t,schema:E.schema,example:c?.[w],visitedSchemaIds:a,depth:n+1,options:u,skipReadonly:l});if(q!=null)d[w]=q;else if(A)return}}return Q0.oneOf(eli.discriminated(d))}case"undiscriminated":{let d=this.getUnDiscriminatedUnionVariantSchema(i.value,r);if(d!=null)return this.buildExampleHelper({exampleId:t,example:r,schema:d,visitedSchemaIds:a,depth:n,options:u,skipReadonly:l});break}}return;case"unknown":if(r!=null){let d=Fli(r);if(d!=null)return Q0.unknown(d)}return u.ignoreOptionals||this.exceedsMaxDepth(n,u)?void 0:u.isParameter?Q0.primitive(i_.string(u.name??"string")):Q0.map([{key:i_.string("key"),value:Q0.primitive(i_.string("value"))}]);case"array":{let d=c7p(r),s=[];if(d!=null&&d.length>0)for(let o of d){let c=this.buildExampleHelper({exampleId:t,example:o,schema:i.value,depth:n+1,visitedSchemaIds:a,options:u,skipReadonly:l});c!=null&&s.push(c)}else if(i.example!=null&&i.example.length>0)for(let o of i.example){let c=this.buildExampleHelper({exampleId:t,example:o,schema:i.value,depth:n+1,visitedSchemaIds:a,options:u,skipReadonly:l});c!=null&&s.push(c)}else{let o=this.buildExampleHelper({exampleId:t,example:void 0,schema:i.value,depth:n+1,visitedSchemaIds:a,options:u,skipReadonly:l});o!=null&&s.push(o)}return Q0.array(s)}case"map":{let d=Ifa(r??i.example);if(d!=null&&Object.entries(d).length>0){let c=[];for(let[b,g]of Object.entries(d)){let O=this.buildExampleFromPrimitive({schema:i.key.schema,example:b,options:u}),m=this.buildExampleHelper({exampleId:t,example:g,schema:i.value,visitedSchemaIds:a,depth:n+1,options:u,skipReadonly:l});m!=null&&c.push({key:O,value:m})}return Q0.map(c)}if(i.key.schema.type==="string"&&i.value.type==="unknown")return Q0.map([{key:i_.string("key"),value:Q0.unknown(Q0.primitive(i_.string("value")))}]);let s=this.buildExampleFromPrimitive({schema:i.key.schema,example:void 0,options:{...u,name:"key"}}),o=this.buildExampleHelper({exampleId:t,example:void 0,schema:i.value,visitedSchemaIds:a,depth:n+1,options:{...u,name:"value"},skipReadonly:l});return o!=null?Q0.map([{key:s,value:o}]):Q0.map([])}case"object":{let d={},s=i.fullExamples?.find(g=>g.name===t)??i.fullExamples?.find(g=>g.name==null)??i.fullExamples?.[0],o=Ifa(r)??(s!=null?Ifa(s.value):{})??{},c=this.getAllProperties(i),b=this.getAllRequiredProperties(i);for(let[g,O]of Object.entries(c)){if(l&&O.readonly)continue;let m=g in b,w=Object.keys(o).includes(g),E=this.buildExampleHelper({schema:O.schema,exampleId:t,example:o[g],visitedSchemaIds:a,depth:n+1,options:{...u,name:g},skipReadonly:l});if(m&&E!=null)d[g]=E;else{if(m)return;(w&&E!=null||!u.ignoreOptionals&&E!=null)&&(d[g]=E)}}if(i.additionalProperties){for(let[g,O]of Object.entries(o))if(!(g in d)){let m=this.buildExampleHelper({schema:El.unknown({example:O,title:void 0,availability:void 0,description:void 0,generatedName:"",nameOverride:void 0,groupName:void 0}),exampleId:t,example:O,visitedSchemaIds:a,depth:n+1,options:{...u,name:g},skipReadonly:l});m!=null&&(d[g]=m)}}return Q0.object({properties:d})}default:Ko(i)}}mergeExampleWith(t,r){t._visit({array:Qo,enum:Qo,literal:Qo,map:i=>{for(let n of i){let a=n.key;a.type==="string"&&(r[a.value]=n.value)}},object:i=>{for(let[n,a]of Object.entries(i.properties))r[n]=a},oneOf:i=>{if(i.type==="discriminated")for(let[n,a]of Object.entries(i.value))r[n]=a;else this.mergeExampleWith(i.value,r)},primitive:Qo,unknown:Qo,_other:Qo})}getObjectSchema(t){if(t.type==="object")return t;if(t.type==="reference"){let r=this.schemas[t.schema];if(r!=null)return this.getObjectSchema(r)}}getDiscriminatedUnionVariantSchema(t,r){let i=r?.[t.discriminantProperty];if(i==null||typeof i!="string")return Object.entries(t.schemas)[0];let n=t.schemas[i];return n==null?Object.entries(t.schemas)[0]:[i,n]}getUnDiscriminatedUnionVariantSchema(t,r){return r==null?t.schemas[0]:t.schemas.map(a=>({schema:a,heuristic:this.calcExampleHeuristic(a,r)})).sort((a,u)=>u.heuristic-a.heuristic)[0]?.schema}calcExampleHeuristic(t,r){switch(t.type){case"literal":return t.value.value===r?5:0;case"enum":return l7p({schema:t,value:r})?5:0;case"object":{if(!Hj(r))return 0;let i=this.getAllProperties(t),n=0;for(let[a,u]of Object.entries(i))r[a]!=null?(n++,n+=this.calcExampleHeuristic(u.schema,r[a])):n--;return n}case"array":{if(!Array.isArray(r))return 0;let i=0;for(let n of r)i+=this.calcExampleHeuristic(t.value,n);return i}case"map":{if(!Hj(r))return 0;let i=0;for(let[,n]of Object.entries(r))i+=this.calcExampleHeuristic(t.value,n);return i}case"nullable":case"optional":return this.calcExampleHeuristic(t.value,r);case"reference":{let i=this.getResolvedSchema(t);return i==null?0:this.calcExampleHeuristic(i,r)}case"oneOf":return Object.values(t.value.schemas).map(n=>this.calcExampleHeuristic(n,r)).sort((n,a)=>a-n)[0]??0;case"primitive":return r==null?0:t.schema._visit({int:()=>typeof r=="number",int64:()=>typeof r=="number",uint:()=>typeof r=="number",uint64:()=>typeof r=="number",float:()=>typeof r=="number",double:()=>typeof r=="number",string:()=>typeof r=="string",datetime:()=>typeof r=="string",date:()=>typeof r=="string",base64:()=>typeof r=="string",boolean:()=>typeof r=="boolean",_other:()=>!0})?1:-1;default:return 0}}hasExample(t,r,i=new Set,n){if(this.exceedsMaxCheckerDepth(r,n))return!1;switch(t.type){case"array":return this.hasExample(t.value,r+1,i,n);case"enum":return t.example!=null;case"literal":return!1;case"map":return t.example!=null||t.key.schema.example!=null&&this.hasExample(t.value,r+1,i,n);case"object":{if(t.fullExamples!=null&&t.fullExamples.length>0)return!0;for(let u of t.properties)if(this.hasExample(u.schema,r+1,i,n))return!0;return!1}case"primitive":return t.schema.example!=null;case"reference":{let a=this.schemas[t.schema];if(a!=null&&!i.has(t.schema)){i.add(t.schema);let u=this.hasExample(a,r,i,n);return i.delete(t.schema),u}return!1}case"unknown":return t.example!=null;case"oneOf":return Object.values(t.value.schemas).some(a=>this.hasExample(a,r,i,n));default:return!1}}exceedsMaxCheckerDepth(t,r){return t>(r.maxCheckerDepth??0)}exceedsMaxDepth(t,r){return t>(r.maxDepth??0)}getAllProperties(t){let r={};for(let i of t.properties)r[i.key]={schema:i.schema,readonly:i.readonly??!1};for(let i of t.allOf){let n=this.schemas[i.schema];if(n==null)continue;let a=this.getResolvedSchema(n);a.type==="object"&&(r={...this.getAllProperties(a),...r})}return r}getAllRequiredProperties(t){let r={};for(let i of t.properties){let n=this.getResolvedSchema(i.schema);n.type!=="optional"&&n.type!=="nullable"&&(r[i.key]=i.schema)}for(let i of t.allOf){let n=this.schemas[i.schema];if(n==null)continue;let a=this.getResolvedSchema(n);a.type==="object"&&(r={...this.getAllRequiredProperties(a),...r})}return r}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}buildExampleFromPrimitive({example:t,schema:r,options:i}){switch(r.type){case"string":return t!=null&&typeof t=="string"?i_.string(t):r.example!=null?i_.string(r.example):i_.string(i.name??yg.STRING);case"base64":return t!=null&&typeof t=="string"?i_.base64(t):r.example!=null?i_.base64(r.example):i_.base64(yg.BASE64);case"boolean":return t!=null&&typeof t=="boolean"?i_.boolean(t):r.example!=null?i_.boolean(r.example):i_.boolean(yg.BOOLEAN);case"date":return t!=null&&typeof t=="string"?i_.date(t):r.example!=null?i_.date(r.example):i_.date(yg.DATE);case"datetime":return t!=null&&typeof t=="string"?i_.datetime(t):r.example!=null?i_.datetime(r.example):i_.datetime(yg.DATE_TIME);case"double":return t!=null&&typeof t=="number"?i_.double(t):r.example!=null?i_.double(r.example):i_.double(yg.DOUBLE);case"float":return t!=null&&typeof t=="number"?i_.float(t):r.example!=null?i_.float(r.example):i_.float(yg.FLOAT);case"int":return t!=null&&typeof t=="number"?i_.int(t):r.example!=null?i_.int(r.example):i_.int(yg.INT);case"int64":return t!=null&&typeof t=="number"?i_.int64(t):r.example!=null?i_.int64(r.example):i_.int64(yg.INT64);case"uint":return t!=null&&typeof t=="number"?i_.uint(t):r.example!=null?i_.uint(r.example):i_.uint(yg.UINT);case"uint64":return t!=null&&typeof t=="number"?i_.uint64(t):r.example!=null?i_.uint64(r.example):i_.uint64(yg.UINT64);default:Ko(r)}}};function l7p({schema:e,value:t}){return e.values.map(r=>r.value).includes(t)}function DYt(e){switch(e.type){case"object":return El.object({allOf:e.allOf,properties:e.properties.map(t=>TDD(t)),allOfPropertyConflicts:e.allOfPropertyConflicts,description:e.description,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,groupName:e.groupName,fullExamples:void 0,additionalProperties:e.additionalProperties,availability:e.availability,source:e.source,inline:void 0});case"array":return El.array({description:e.description,availability:e.availability,value:DYt(e.value),generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,groupName:e.groupName,example:void 0,inline:void 0});case"enum":return El.enum({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,values:e.values,default:e.default,groupName:e.groupName,example:void 0,source:e.source,inline:void 0});case"literal":return El.literal({description:e.description,availability:e.availability,value:e.value,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,groupName:e.groupName});case"nullable":return El.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:DYt(e.value),groupName:e.groupName,inline:void 0});case"optional":return El.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:DYt(e.value),groupName:e.groupName,inline:void 0});case"primitive":return El.primitive({description:e.description,availability:e.availability,schema:f7p(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName});case"map":return El.map({description:e.description,availability:e.availability,key:El.primitive({description:e.key.description,availability:e.key.availability,schema:f7p(e.key.schema),generatedName:e.key.generatedName,nameOverride:e.key.nameOverride,title:e.key.title,groupName:e.groupName}),value:DYt(e.value),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName,encoding:e.encoding,example:void 0,inline:void 0});case"reference":return El.reference({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schema:e.schema,groupName:e.groupName,source:e.source});case"oneOf":return El.oneOf(qDD(e.value));case"unknown":return El.unknown({nameOverride:e.nameOverride,generatedName:e.generatedName,title:void 0,example:void 0,groupName:void 0,description:void 0,availability:void 0});default:Ko(e)}}function qDD(e){switch(e.type){case"discriminated":return PY.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:DYt(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,DYt(r)])),groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});case"undiscriminated":return PY.undiscriminated({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:e.schemas.map(t=>DYt(t)),groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});default:Ko(e)}}function f7p(e){switch(e.type){case"string":return Jd.string({default:e.default,pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:void 0});case"base64":return Jd.base64({example:void 0});case"boolean":return Jd.boolean({default:e.default,example:void 0});case"date":return Jd.date({example:void 0});case"datetime":return Jd.datetime({example:void 0});case"double":return Jd.double({default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:e.exclusiveMinimum,exclusiveMaximum:e.exclusiveMaximum,multipleOf:e.multipleOf,example:void 0});case"float":return Jd.float({example:void 0});case"int":return Jd.int({default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:e.exclusiveMinimum,exclusiveMaximum:e.exclusiveMaximum,multipleOf:e.multipleOf,example:void 0});case"int64":return Jd.int64({default:e.default,example:void 0});case"uint":return Jd.uint({default:void 0,example:void 0});case"uint64":return Jd.uint64({default:void 0,example:void 0});default:Ko(e)}}function TDD(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:DYt(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly,writeonly:e.writeonly}}function Uqo(e){return e.type!=="optional"&&e.type!=="nullable"}function d9s(e){return e==="POST"||e==="PUT"||e==="PATCH"}function zfa(e){if(e.type==="full")return e.request==null&&e.response==null&&e.queryParameters==null&&e.pathParameters==null&&e.headers==null;{let t=e.value;return t.request==null&&t.response==null&&t["query-parameters"]==null&&t["path-parameters"]==null&&t.headers==null}}var Vqo=class{schemas;context;exampleTypeFactory;logger;constructor(t,r){this.schemas=t,this.context=r,this.schemas=t,this.exampleTypeFactory=new Lli(t,r.nonRequestReferencedSchemas,r),this.logger=r.logger}buildEndpointExample(t){this.logger.debug(`Building endpoint example for ${t.method.toUpperCase()} ${t.path}`);let r=BDD(t.request),i=xDD(t.response);if(r?.type==="unsupported"||i?.type==="unsupported")return[];let n=[];if(r!=null&&r.type==="present"){let c=this.isSchemaRequired(r.schema);if(r.examples.length===0){let b=this.exampleTypeFactory.buildExample({skipReadonly:d9s(t.method),schema:r.schema,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});b!=null&&n.push([void 0,b])}else for(let{name:b,value:g}of r.examples){let O=this.exampleTypeFactory.buildExample({skipReadonly:d9s(t.method),schema:r.schema,exampleId:b,example:g,options:{isParameter:!1,ignoreOptionals:!0}});O!=null&&n.push([b,O])}if(c&&n.length===0)return this.logger.trace(`Failed to generate required request example for ${t.method.toUpperCase()} ${t.path}`),[]}let a=[];if(i!=null&&i.type==="present"){let c=this.isSchemaRequired(i.schema);if(t.response?.type==="json"&&t.response.statusCode===204)a.push([void 0,TIe.withoutStreaming(Q0.object({properties:{}}))]);else if(i.examples.length===0){let b=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:i.schema,exampleId:void 0,example:void 0,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});b!=null&&(t.response?.type==="json"?a.push([void 0,TIe.withoutStreaming(b)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&a.push([void 0,TIe.withStreaming({sse:t.response?.type==="streamingSse",events:[b]})]))}else for(let{name:b,value:g}of i.examples){let O=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:i.schema,exampleId:b,example:g,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});O!=null&&(t.response?.type==="json"?a.push([b,TIe.withoutStreaming(O)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&a.push([void 0,TIe.withStreaming({sse:t.response?.type==="streamingSse",events:[O]})]))}if(c&&a.length===0)return this.logger.trace(`Failed to generate required response example for ${t.method.toUpperCase()} ${t.path}`),[]}let u=[];for(let c of t.pathParameters){let b=this.isSchemaRequired(c.schema),g=this.exampleTypeFactory.buildExample({schema:c.schema,exampleId:void 0,example:void 0,options:{name:c.name,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!EYt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for path parameter ${c.name} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),b&&g==null)return[];g!=null&&u.push({name:c.name,parameterNameOverride:c.parameterNameOverride,value:g})}let l=[];for(let c of t.queryParameters){let b=this.isSchemaRequired(c.schema),g=this.exampleTypeFactory.buildExample({schema:c.schema,exampleId:void 0,example:void 0,options:{name:c.name,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!EYt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for query parameter ${c.name} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),b&&g==null)return[];g!=null&&l.push({name:c.name,value:g})}let d=[];for(let c of t.headers){let b=this.isSchemaRequired(c.schema),g=this.exampleTypeFactory.buildExample({schema:c.schema,exampleId:void 0,example:void 0,options:{name:c.name,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!EYt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for header ${c.name} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),b&&g==null)return[];g!=null&&d.push({name:c.name,value:g})}let s=[];t.request!=null&&t.response!=null?s=CDD(n,a):t.request!=null?s=n.map(([c,b])=>({id:c,request:b,response:void 0})):t.response!=null&&(s=a.map(([c,b])=>({id:c,request:void 0,response:b})));let o=t.examples.filter(c=>zfa(c)).flatMap(c=>{if(c.type==="unknown"){if(c.value!=null){let b=c.value["code-samples"];if(b!=null)return this.convertCodeSamples(b)}return}else return c.codeSamples}).filter(c=>u0(c));return s.length===0?[L8t.full({name:void 0,description:void 0,pathParameters:u,queryParameters:l,headers:d,request:void 0,response:void 0,codeSamples:o})]:s.map(({id:c,request:b,response:g})=>L8t.full({name:c,description:void 0,pathParameters:u,queryParameters:l,headers:d,request:b,response:g,codeSamples:o}))}convertCodeSamples(t){return t.map(r=>"language"in r?GGr.language({name:r.name??void 0,description:r.docs??void 0,language:r.language,code:r.code,install:r.install??void 0}):GGr.sdk({name:r.name??void 0,description:r.docs??void 0,sdk:r.sdk==="c#"?GU.Csharp:r.sdk,code:r.code})).filter(u0)}isSchemaRequired(t){return Uqo(this.getResolvedSchema(t))}getResolvedSchema(t){return t}};function CDD(e,t){let r=[];if(e.length<=1){let[n,a]=e[0]??[];if(t.length===0)return r.push({id:n,request:a,response:void 0}),r;for(let[u,l]of t)r.push({id:u??n,request:a,response:l});return r}if(t.length<=1){let[n,a]=t[0]??[];if(t.length===0)return r.push({id:n,request:void 0,response:a}),r;for(let[u,l]of e)r.push({id:u??n,request:l,response:a});return r}let i=new Set;for(let[n,a]of e){let u=t.find(([d])=>d==null)?.[1]??t[0]?.[1];if(n==null){if(u==null)continue;r.push({id:void 0,request:a,response:u});continue}let l=!1;for(let d=0;d<t.length;d++){let[s,o]=t[d];s==null||i.has(d)||n===s&&(r.push({id:n,request:a,response:o}),s!=null&&i.add(d),l=!0)}!l&&u!=null&&r.push({id:n,request:a,response:u})}for(let n=0;n<t.length;n++){if(i.has(n))continue;let[a,u]=t[n],l=e.find(([d])=>d==null)?.[1]??e[0]?.[1];l!=null&&r.push({id:a,request:l,response:u})}return r}function BDD(e){if(e!=null)return e.type==="multipart"?{type:"present",schema:IDD(e),examples:[]}:e.type==="json"?{type:"present",schema:e.schema,examples:e.fullExamples??[]}:{type:"unsupported"}}function xDD(e){if(e!=null)return e.type!=="json"&&e.type!=="streamingJson"&&e.type!=="streamingSse"?{type:"unsupported"}:{type:"present",schema:e.schema,examples:e.fullExamples??[]}}function EYt(e){switch(e.type){case"primitive":case"enum":case"literal":return!0;case"unknown":return EYt(e);case"array":case"object":case"map":return!1;case"oneOf":switch(e.value.type){case"discriminated":return!1;case"undiscriminated":return EYt(e.value.value);default:return!1}default:Ko(e)}}function IDD(e){return El.object({properties:e.properties.map(t=>t.schema.type==="file"?null:{key:t.key,schema:DYt(t.schema.value),audiences:[],conflict:{},generatedName:t.key,nameOverride:void 0,availability:void 0,readonly:void 0,writeonly:void 0,inline:void 0}).filter(u0),allOf:[],allOfPropertyConflicts:[],fullExamples:void 0,description:e.description,nameOverride:void 0,generatedName:"",title:void 0,groupName:void 0,additionalProperties:!1,availability:void 0,source:e.source,inline:void 0})}var Ajn=class{exampleTypeFactory;schemas;constructor(t,r){this.exampleTypeFactory=new Lli(t,new Set,r),this.schemas=t}buildWebsocketSessionExamplesForExtension({context:t,extensionExamples:r,publish:i,subscribe:n,handshake:a,source:u,namespace:l}){let d=[];for(let s of r){let o=[];for(let g of a.queryParameters){let O=this.isSchemaRequired(g.schema),m=this.exampleTypeFactory.buildExample({schema:g.schema,exampleId:void 0,example:s.queryParameters?.[g.name],options:{name:g.name,isParameter:!0,ignoreOptionals:!0}});m!=null&&!EYt(m)&&(m=void 0),!(O&&m==null)&&m!=null&&o.push({name:g.name,value:m})}let c=[];for(let g of a.headers){let O=this.isSchemaRequired(g.schema),m=this.exampleTypeFactory.buildExample({schema:g.schema,exampleId:void 0,example:s.headers?.[g.name],options:{name:g.name,isParameter:!0,ignoreOptionals:!0}});m!=null&&!EYt(m)&&(m=void 0),!(O&&m==null)&&m!=null&&c.push({name:g.name,value:m})}let b=[];for(let g of s.messages){let O=t.getExampleMessageReference(g),m=t.resolveMessageReference({$ref:O}),w=Kd(m.payload)?t.resolveSchemaReference(m.payload):m.payload,E=this.exampleTypeFactory.buildExample({schema:Pb(w,!1,t,[g.messageId],u,l),exampleId:void 0,example:g.value,options:{isParameter:!1,ignoreOptionals:!0}});E!=null&&b.push({messageType:g.type,payload:E,description:void 0})}d.push({name:s.summary,queryParameters:o,headers:c,description:s.description,messages:b})}return d}buildWebsocketSessionExample({publish:t,subscribe:r,handshake:i}){let n={name:void 0,queryParameters:[],headers:[],description:void 0,messages:[]},a=[];for(let l of i.queryParameters){let d=this.isSchemaRequired(l.schema),s=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(s!=null&&!EYt(s)&&(s=void 0),d&&s==null)return;s!=null&&a.push({name:l.name,value:s})}let u=[];for(let l of i.headers){let d=this.isSchemaRequired(l.schema),s=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(s!=null&&!EYt(s)&&(s=void 0),d&&s==null)return;s!=null&&u.push({name:l.name,value:s})}if(t!=null){let l=this.exampleTypeFactory.buildExample({schema:t,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});l!=null&&n.messages.push({messageType:"publish",payload:l,description:void 0})}if(r!=null){let l=this.exampleTypeFactory.buildExample({schema:r,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});l!=null&&n.messages.push({messageType:"subscribe",payload:l,description:void 0})}return n}isSchemaRequired(t){return Uqo(this.getResolvedSchema(t))}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}};var RY={FERN_PARAMETER_OPTIONAL:"x-fern-optional",FERN_DISPLAY_NAME:"x-fern-display-name",FERN_SDK_GROUP_NAME:"x-fern-sdk-group-name",FERN_EXAMPLES:"x-fern-examples",BASE_PATH:"x-fern-base-path",FERN_ENUM:"x-fern-enum",IGNORE:"x-fern-ignore"};function Wqo(e){return bf(e,RY.FERN_EXAMPLES)??[]}function Hqo(e,t){return t.includes("://")?t:`${e}://${t}`}function $qo(e){return e.startsWith("/")?e:"/"+e}function _7p({context:e,breadcrumbs:t,source:r,asyncApiOptions:i,document:n}){let a={},u={};for(let[s,o]of Object.entries(n.components?.schemas??{})){let c=Pb(o,!1,e,[s],r,e.namespace);a[s]=c}let l=new Ajn(a,e),d={};for(let[s,o]of Object.entries(n.servers??{}))d[s]={name:s,url:Hqo(o.protocol,o.url)};for(let[s,o]of Object.entries(n.channels??{})){let c=bf(o,RY.IGNORE);if(c!=null&&c){e.logger.debug(`Channel ${s} is marked with x-fern-ignore. Skipping.`);continue}let b=[];if(o.parameters!=null)for(let[E,A]of Object.entries(o.parameters??{}))b.push({name:E,description:A.description,parameterNameOverride:void 0,schema:A.schema!=null?Pb(A.schema,!1,e,t,r,e.namespace):El.primitive({schema:Jd.string({default:void 0,pattern:void 0,format:void 0,maxLength:void 0,minLength:void 0,example:void 0}),description:void 0,availability:void 0,generatedName:"",title:void 0,groupName:void 0,nameOverride:void 0}),variableReference:void 0,availability:nie(A),source:r});let g=[],O=[];if(o.bindings?.ws!=null){if(o.bindings.ws.headers!=null){let E=o.bindings.ws.headers.required??[];for(let[A,q]of Object.entries(o.bindings.ws.headers.properties??{})){let D=Kd(q)?e.resolveSchemaReference(q):q;g.push({name:A,schema:Pb(D,!E.includes(A),e,[...t,A],r,e.namespace),description:D.description,parameterNameOverride:void 0,env:void 0,availability:nie(D),source:r})}}if(o.bindings.ws.query!=null){let E=o.bindings.ws.query.required??[];for(let[A,q]of Object.entries(o.bindings.ws.query.properties??{})){let D=Kd(q)?e.resolveSchemaReference(q):q;O.push({name:A,schema:Pb(D,!E.includes(A),e,[...t,A],r,e.namespace),description:D.description,parameterNameOverride:void 0,availability:nie(D),source:r})}}}let m;o.publish!=null&&("oneOf"in o.publish.message?m=d7p({generatedName:o.publish.operationId??"PublishEvent",event:o.publish,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:i}):m=p7p({action:"Publish",channelPath:s,message:o.publish.message,context:e,source:r}));let w;if(o.subscribe!=null&&("oneOf"in o.subscribe.message?w=d7p({generatedName:o.subscribe.operationId??"SubscribeEvent",event:o.subscribe,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:i}):w=p7p({action:"Subscribe",channelPath:s,message:o.subscribe.message,context:e,source:r})),g.length>0||O.length>0||m!=null||w!=null){let E=Wqo(o),A=[];if(E.length>0)A=l.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:E,handshake:{headers:g,queryParameters:O},publish:m,subscribe:w,source:r,namespace:e.namespace});else{let q=l.buildWebsocketSessionExample({handshake:{headers:g,queryParameters:O},publish:m,subscribe:w});q!=null&&A.push(q)}u[s]={audiences:bf(o,fd.AUDIENCES)??[],handshake:{headers:g.map(q=>({...q,schema:kD(q.schema),env:q.env})),queryParameters:O.map(q=>({...q,schema:kD(q.schema)})),pathParameters:b.map(q=>({...q,parameterNameOverride:void 0,schema:kD(q.schema)}))},groupName:[bf(o,RY.FERN_SDK_GROUP_NAME)??s],publish:m!=null?kD(m):m,subscribe:w!=null?kD(w):w,servers:(o.servers?.map(q=>d[q])??Object.values(d)).filter(q=>q!=null),summary:bf(o,RY.FERN_DISPLAY_NAME),path:$qo(s),description:void 0,examples:A,source:r}}}return{groupedSchemas:Mjn(e.namespace,a),channels:u??void 0,servers:Object.values(d),basePath:bf(n,RY.BASE_PATH)}}function d7p({generatedName:e,event:t,context:r,breadcrumbs:i,source:n,options:a,asyncApiOptions:u}){if("oneOf"in t.message&&t.message.oneOf!=null){let l=[],d=[];for(let s of t.message.oneOf){let o,c={type:"notFound"};if(Kd(s)){let b=r.resolveMessageReference(s);!Kd(b.payload)&&u.naming==="v2"?(c=b.name?{type:"name",name:b.name}:c,o={...b.payload,title:b.name??b.payload.title,description:b.name??b.payload.description}):o=b.payload}else o=s;d.push(c),l.push(o)}return wjn({description:t.description??t.message.description,availability:nie(t.message),subtypes:l,nameOverride:t.operationId,generatedName:e,title:t.message.title,groupName:void 0,wrapAsNullable:!1,breadcrumbs:i,context:r,encoding:void 0,source:n,namespace:r.namespace,subtypePrefixOverrides:u.naming==="v2"?d:[]})}}function p7p({action:e,channelPath:t,message:r,context:i,source:n}){if(r.payload!=null){let a=r.payload;return Kd(r.payload)&&(a=i.resolveSchemaReference(r.payload)),Kd(a)?Pb(a,!1,i,[t,e],n,i.namespace):Pb(a,!1,i,[t,e],n,i.namespace)}}var Gqo=class extends Ejn{getExampleMessageReference(t){return`#/channels/${t.channelId}/messages/${t.messageId}`}resolveMessageReference(t){let r="#/channels/",i="#/components/messages/";if(t.$ref.startsWith(r)){let l=t.$ref.split("/"),d=l[2],s=l[4];if(d==null||s==null||!this.document.channels?.[d])throw new Error(`Failed to resolve message reference ${t.$ref} in channel ${d}`);let c=this.document.channels[d].messages?.[s];if(c==null)throw new Error(`${t.$ref} is undefined`);return{name:s,...c}}let n=this.document.components;if(!t.$ref.startsWith(i)||!n?.messages)throw new Error(`Failed to resolve message reference: ${t.$ref} in v3 components`);let a=t.$ref.substring(i.length),u=n.messages[a];if(u==null)throw new Error(`${t.$ref} is undefined`);return{name:a,...u}}};var h7p="#/channels/",y7p="#/servers/",p9s="$message.";function b7p({context:e,breadcrumbs:t,source:r,asyncApiOptions:i,document:n}){let a={},u={},l={},d=[],s={};for(let[m,w]of Object.entries(n.components?.schemas??{}))a[m]=Pb(w,!1,e,[m],r,e.namespace);for(let[m,w]of Object.entries(n.channels??{}))if(u[m]||(u[m]={}),w.messages)for(let[E,A]of Object.entries(w.messages))A&&A.payload!=null&&(l[E]||(l[E]=[]),l[E].push({channelId:m,payload:A.payload}));for(let[m,w]of Object.entries(l))if(w.length===1){let E=w[0],A=E.channelId;u[A]=u[A]||{},u[A][m]=Pb(E.payload,!1,e,[m],r,e.namespace)}else{d.push(m);for(let{channelId:E,payload:A}of w){let q=`${E}_${m}`;u[E]||(u[E]={}),u[E][q]=Pb(A,!1,e,[q],r,e.namespace)}}let o=Object.values(u).reduce((m,w)=>({...m,...w}),{}),c=new Ajn(o,e),b={};for(let[m,w]of Object.entries(n.servers??{}))b[m]={name:m,url:Hqo(w.protocol,w.host)};let g={};for(let[m,w]of Object.entries(n.operations??{})){if(bf(w,RY.IGNORE))continue;let E=zDD(w);if(g[E]||(g[E]={subscribe:[],publish:[]}),w.action==="receive")g[E].subscribe.push(...w.messages);else if(w.action==="send")g[E].publish.push(...w.messages);else throw new Error(`Operation ${m} has an invalid action: ${w.action}`)}let O={};for(let[m,w]of Object.entries(g)){O[m]={subscribe:void 0,publish:void 0};let E=m.split("/").pop()??m,A=E.charAt(0).toUpperCase()+E.slice(1);w.subscribe.length>0&&u[m]!=null&&(O[m].subscribe=v7p({generatedName:A+"SubscribeEvent",channelPath:m,messages:w.subscribe,breadcrumbs:t,context:e,source:r,messageSchemas:u[m],duplicatedMessageIds:d})),w.publish.length>0&&u[m]!=null&&(O[m].publish=v7p({generatedName:A+"PublishEvent",channelPath:m,messages:w.publish,breadcrumbs:t,context:e,source:r,messageSchemas:u[m],duplicatedMessageIds:d}))}for(let[m,w]of Object.entries(n.channels??{})){if(bf(w,RY.IGNORE))continue;let E=[],A=[],q=[];if(w.parameters!=null)for(let[D,C]of Object.entries(w.parameters)){let{type:R,parameterKey:$}=RDD(C.location),I=bf(C,RY.FERN_PARAMETER_OPTIONAL),U=q3(vg(m))+q3(vg(D)),H=bf(C,RY.FERN_ENUM),k=C.enum!=null&&Array.isArray(C.enum)?FDD({parameterName:U,fernEnum:H,parameterDescription:C.description,enumValues:C.enum,defaultValue:C.default,context:e,source:r}):El.primitive({schema:Jd.string({default:C.default,pattern:void 0,format:void 0,maxLength:void 0,minLength:void 0,example:C.examples?.[0]}),description:void 0,availability:void 0,generatedName:"",title:U,groupName:void 0,nameOverride:void 0});I&&(k=El.optional({value:k,description:void 0,availability:void 0,generatedName:"",title:U,groupName:void 0,nameOverride:void 0,inline:void 0}));let K={name:$,description:C.description,parameterNameOverride:void 0,schema:k,variableReference:void 0,availability:nie(C),source:r};R==="header"?E.push({...K,env:void 0}):R==="path"?A.push(K):R==="payload"&&q.push(K)}if(E.length>0||q.length>0||O[m]!=null&&(O[m].publish!=null||O[m].subscribe!=null)){let D=Wqo(w),C=[];if(D.length>0)C=c.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:D,handshake:{headers:E,queryParameters:q},publish:O[m]?.publish,subscribe:O[m]?.subscribe,source:r,namespace:e.namespace});else{let R=c.buildWebsocketSessionExample({handshake:{headers:E,queryParameters:q},publish:O[m]?.publish,subscribe:O[m]?.subscribe});R!=null&&C.push(R)}s[m]={audiences:bf(w,fd.AUDIENCES)??[],handshake:{headers:E.map(R=>({...R,schema:kD(R.schema),env:R.env})),queryParameters:q.map(R=>({...R,schema:kD(R.schema)})),pathParameters:A.map(R=>({...R,parameterNameOverride:void 0,schema:kD(R.schema)}))},groupName:[bf(w,RY.FERN_SDK_GROUP_NAME)??m],publish:O[m]?.publish!=null?kD(O[m].publish):void 0,subscribe:O[m]?.subscribe!=null?kD(O[m].subscribe):void 0,summary:bf(w,RY.FERN_DISPLAY_NAME),servers:w.servers?.map(R=>NDD(b,R))??Object.values(b),path:w.address??$qo(m),description:void 0,examples:C,source:r}}}return{groupedSchemas:Mjn(e.namespace,a),channels:s,servers:Object.values(b),basePath:bf(n,RY.BASE_PATH)}}function zDD(e){if(!e.channel.$ref.startsWith(h7p))throw new Error(`Failed to resolve channel path from operation ${e.channel.$ref}`);return e.channel.$ref.substring(h7p.length)}function RDD(e){try{let[t,r]=e.split("#/");if(t==null||r==null)throw new Error(`Invalid location format: ${e}; unable to parse message type and parameter key`);if(!t.startsWith(p9s))throw new Error(`Invalid location format: ${e}; expected ${p9s} prefix`);let i=t.substring(p9s.length);if(i!=="header"&&i!=="path"&&i!=="payload")throw new Error(`Invalid message type: ${i}. Must be one of: header, path, payload`);return{type:i,parameterKey:r}}catch{throw new Error(`Invalid location format: ${e}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`)}}function NDD(e,t){if(!t.$ref.startsWith(y7p))throw new Error(`Failed to resolve server name from server ref ${t.$ref}`);let r=t.$ref.substring(y7p.length),i=e[r];if(i==null)throw new Error(`Failed to find server with name ${r}`);return i}function FDD({parameterName:e,fernEnum:t,parameterDescription:r,enumValues:i,defaultValue:n,context:a,source:u}){return SYt({nameOverride:void 0,generatedName:e,title:void 0,wrapAsNullable:!1,description:r??void 0,availability:void 0,fernEnum:t??{},enumVarNames:void 0,enumValues:i,_default:n,groupName:void 0,context:a,source:u,inline:void 0})}function v7p({generatedName:e,channelPath:t,messages:r,context:i,breadcrumbs:n,source:a,messageSchemas:u,duplicatedMessageIds:l}){if(r.length>0){let d=[];for(let s of r){let o=i.resolveMessageReference(s),c;l.some(g=>g===o.name)?c=`${t}_${o.name}`:c=o.name;let b=u[c];b!=null&&d.push(b)}return k3p({description:void 0,availability:void 0,subtypes:d,nameOverride:void 0,generatedName:e,title:void 0,groupName:void 0,wrapAsNullable:!1,breadcrumbs:n,context:i,encoding:void 0,source:a,namespace:i.namespace,subtypePrefixOverrides:[]})}}function g7p({document:e,taskContext:t,options:r,source:i,asyncApiOptions:n,namespace:a}){let u=[];if(a!=null&&u.push(a),parseFloat(e.asyncapi)<3){let l=e;l.tags?.[0]!=null?u.push(l.tags[0].name):n.naming!=="v2"&&u.push("websocket");let d=new Lqo({document:l,taskContext:t,options:r,namespace:a});return _7p({context:d,breadcrumbs:u,source:i,asyncApiOptions:n,document:l})}else{let l=e,d=new Gqo({document:l,taskContext:t,options:r,namespace:a});return b7p({context:d,breadcrumbs:u,source:i,asyncApiOptions:n,document:l})}}function O7p(e){let t=LDD(e),r={};return _9s({obj:t,occurrences:r,breadcrumbs:[]}),r}function _9s({obj:e,occurrences:t,breadcrumbs:r}){if(e!=null){if(Array.isArray(e)){for(let i of e)_9s({obj:i,occurrences:t,breadcrumbs:r});return}if(typeof e=="object"){if(e.$ref!=null&&typeof e.$ref=="string"){let i=e.$ref;t[i]==null?t[i]=1:t[i]+=1;return}for(let i in e)_9s({obj:e[i],occurrences:t,breadcrumbs:[...r,i]})}}}function LDD(e){return{...e,paths:Object.fromEntries(Object.entries(e.paths??{}).map(([t,r])=>[t,{...r,get:r?.get!=null?Rfa(r.get):void 0,put:r?.put!=null?Rfa(r.put):void 0,post:r?.post!=null?Rfa(r.post):void 0,patch:r?.patch!=null?Rfa(r.patch):void 0,delete:r?.delete!=null?Rfa(r.delete):void 0}]))}}function Rfa(e){return{...e,requestBody:e.requestBody!=null?Kd(e.requestBody)?e.requestBody:UDD(e.requestBody):void 0}}function UDD(e){let t,r;for(let i in e.content){let n=zB.parse(i);n!=null&&(n.isJSON()?t=e.content[i]:n.isMultipart()&&(r=e.content[i]))}return r!=null&&t!=null?{...e,content:{[zB.MULTIPART_FORM_DATA]:r}}:e}var Qqo=class{endpoints;parser=new fTi;constructor({context:t,options:r}){this.endpoints=r.filter?.endpoints?new Set(this.validateAndFilterEndpoints({context:t,endpoints:r.filter.endpoints})):void 0}skipEndpoint({method:t,path:r}){return this.endpoints!=null&&!this.endpoints.has(`${t} ${r}`)}hasEndpoints(){return this.endpoints!=null}validateAndFilterEndpoints({context:t,endpoints:r}){let i=[];for(let n of r){let a=this.parser.tryParse(n);if(a==null){t.logger.debug(`Ignoring configured filter endpoint "${n}"; expected format "POST /users/get"`);continue}i.push(`${a.method} ${a.path}`)}return i}};var m7p="#/components/parameters/",P7p="#/components/responses/",j7p="#/components/examples/",w7p="#/components/requestBodies/",qjn=class{logger;document;taskContext;authHeaders;refOccurrences;DUMMY;options;source;filter;namespace;constructor({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:u}){this.document=t,this.logger=r.logger,this.taskContext=r,this.authHeaders=i,this.refOccurrences=O7p(t),this.options=n,this.source=a,this.filter=new Qqo({context:r,options:n}),this.DUMMY=this.getDummy(),this.namespace=u}getNumberOfOccurrencesForRef(t){return this.refOccurrences[t.$ref]??0}resolveTagsToTagIds(t){let r=[];return this.namespace!=null&&r.push(this.namespace),r.concat(t??[])}resolveTags(t){let r=[];if(this.namespace!=null){let i={type:"namespace",name:this.namespace};r.push(i)}return r.concat(t??[])}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveSchemaReference(t){let r=t.$ref.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return{"x-fern-type":"unknown"};i=i[n]}return i==null?(this.logger.warn(`Encountered undefined reference: ${t.$ref}`),{"x-fern-type":"unknown"}):(Kd(i)&&(i=this.resolveSchemaReference(i)),i)}resolveParameterReference(t){if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(m7p))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(m7p.length),i=this.document.components.parameters[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Kd(i)?this.resolveParameterReference(i):i}resolveRequestBodyReference(t){if(this.document.components==null||this.document.components.requestBodies==null||!t.$ref.startsWith(w7p))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(w7p.length),i=this.document.components.requestBodies[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Kd(i)?this.resolveRequestBodyReference(i):i}resolveResponseReference(t){if(this.document.components==null||this.document.components.responses==null||!t.$ref.startsWith(P7p))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(P7p.length),i=this.document.components.responses[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Kd(i)?this.resolveResponseReference(i):i}resolveExampleReference(t){if(this.document.components==null||this.document.components.examples==null||!t.$ref.startsWith(j7p))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(j7p.length),i=this.document.components.examples[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Kd(i)?this.resolveExampleReference(i):i}referenceExists(t){let r=t.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return!1;i=i[n]}return!0}};var Tjn=class extends qjn{constructor({document:t,taskContext:r,options:i,source:n,namespace:a}){super({document:t,taskContext:r,authHeaders:new Set,options:i,source:n,namespace:a})}getDummy(){return this}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}getReferencedSchemas(){return new Set}markReferencedByDiscriminatedUnion(t,r,i){}getReferencesFromDiscriminatedUnion(t){}excludeSchema(t){}isSchemaExcluded(t){return!1}markSchemaWithDiscriminantValue(t,r,i){}getDiscriminatedUnionMetadata(t){}};var Jqo=class extends qjn{nonRequestReferencedSchemas=new Set;twoOrMoreRequestsReferencedSchemas=new Set;singleRequestReferencedSchemas=new Set;discriminatedUnionReferences={};discriminatedUnionMetadata={};schemasToExclude=new Set;constructor({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:u}){super({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:u})}getDummy(){return new Tjn({document:this.document,taskContext:this.taskContext,options:this.options,source:this.source,namespace:this.namespace})}markSchemaAsReferencedByNonRequest(t){this.nonRequestReferencedSchemas.add(t)}markSchemaAsReferencedByRequest(t){this.singleRequestReferencedSchemas.has(t)?this.twoOrMoreRequestsReferencedSchemas.add(t):this.singleRequestReferencedSchemas.add(t)}getReferencedSchemas(){return new Set([...this.nonRequestReferencedSchemas,...this.twoOrMoreRequestsReferencedSchemas])}markReferencedByDiscriminatedUnion(t,r,i){let n=this.discriminatedUnionReferences[t.$ref];n!=null?(n.discriminants.add(r),n.numReferences+=i):this.discriminatedUnionReferences[t.$ref]={discriminants:new Set([r]),numReferences:i}}getReferencesFromDiscriminatedUnion(t){return this.discriminatedUnionReferences[t.$ref]}markSchemaWithDiscriminantValue(t,r,i){let n=this.discriminatedUnionMetadata[t.$ref];n!=null?n.discriminants.set(r,i):this.discriminatedUnionMetadata[t.$ref]={discriminants:new Map([[r,i]])}}getDiscriminatedUnionMetadata(t){return this.discriminatedUnionMetadata[t.$ref]}excludeSchema(t){this.schemasToExclude.add(t)}isSchemaExcluded(t){return this.schemasToExclude.has(t)}};function S7p(e){return bf(e,fd.ASYNC_CONFIG)}var D7p="$request.";function E7p(e){let t=bf(e,fd.STREAMING);if(t!=null)return typeof t=="boolean"?t?{type:"stream",format:"json"}:void 0:t["stream-condition"]==null&&t.format!=null?{type:"stream",format:t.format}:{type:"streamCondition",format:t.format??"json",streamDescription:t["stream-description"],streamConditionProperty:VDD(t["stream-condition"]),responseStream:t["response-stream"],response:t.response}}function VDD(e){return e.startsWith(D7p)?e.slice(D7p.length):e}function M7p(e){let t=e;if(t.cursor!=null)return qIe.cursor({cursor:t.cursor,nextCursor:t.next_cursor,results:t.results});if("offset"in e){let r=e;return qIe.offset({offset:r.offset,results:r.results,step:r.step,hasNextPage:r["has-next-page"]})}if("type"in e&&e.type==="custom"){let r=e;return qIe.custom({results:r.results})}throw new Error("Invalid pagination extension")}function A7p(e,t){let r=bf(t,fd.PAGINATION);if(r!=null){if(typeof r=="boolean"){let i=bf(e,fd.PAGINATION);if(typeof i=="boolean")throw new Error("Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.");return i==null?void 0:M7p(i)}return M7p(r)}}var WDD=Yu.object({lang:Yu.string(),label:Yu.optional(Yu.string()),source:Yu.string()}),h9s=Yu.array(WDD);var q7p={README_EXT:"x-readme"};function HDD(e){if(!Array.isArray(e))return!1;for(let t of e)if(!Hj(t)||typeof t.language!="string"||typeof t.code!="string")return!1;return!0}function T7p(e){let t=bf(e,q7p.README_EXT);if(!Hj(t))return[];let r=t["code-samples"];if(!HDD(r))return[];let i=[];for(let n of r)i.push({name:n.name,language:n.language,code:n.code,install:n.install,docs:void 0});return i}function C7p(e,t,r){let n=(bf(t,fd.EXAMPLES)??[]).filter(s=>{let o=G6.serialization.ExampleEndpointCallSchema.parse(s);return o.ok||r.logger.error(`Failed to parse x-fern-example in ${e.path}/${e.method}`),o.ok}),a=Bfa(t,kU.REDOCLY_CODE_SAMPLES_KEBAB,h9s,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],l=[...Bfa(t,kU.REDOCLY_CODE_SAMPLES_CAMEL,h9s,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],...a];l.length>0&&n.push({"code-samples":l.map(s=>({name:s.label??s.lang,language:s.lang,code:s.source,install:void 0,docs:void 0}))});let d=T7p(t);return d.length>0&&n.push({"code-samples":d}),n.map(L8t.unknown)}function B7p(e){let t=bf(e,fd.AVAILABILITY);if(t==="ga"||t==="generally-available")return $U.GenerallyAvailable;if(t==="beta"||t==="pre-release")return $U.Beta;if(t==="deprecated")return $U.Deprecated;if(e.deprecated)return $U.Deprecated}function Kqo(e){return{url:$DD({url:e.url,variables:e.variables??{}}),description:e.description,name:GDD(e),audiences:bf(e,fd.AUDIENCES)}}function $DD({url:e,variables:t}){let r=Object.fromEntries(Object.entries(t).map(([i,n])=>[i,n.default]));for(let[i,n]of Object.entries(r))e=e.replace(`{${i}}`,n);return e}function GDD(e){let t=bf(e,[fd.SERVER_NAME_V1,fd.SERVER_NAME_V2]);if(t!=null)return t;if(e.description?.toLowerCase()==="production")return"Production";if(e.description?.toLowerCase()==="sandbox")return"Sandbox"}function x7p(e){return bf(e,fd.PARAMETER_NAME)}function I7p(e){return bf(e,fd.SDK_VARIABLE)}function Yqo({path:e,httpMethod:t,parameters:r,context:i,requestBreadcrumbs:n,source:a}){let u={pathParameters:[],queryParameters:[],headers:[]};for(let l of r){let d=bf(l,fd.IGNORE);if(d!=null&&d){i.logger.debug(`${t.toUpperCase()} ${e} has a parameter marked with x-fern-ignore. Skipping.`);continue}let s=Kd(l)?i.resolveParameterReference(l):l,o=s.required??!1,c=nie(s),b=[...n,s.name],g=s2(b,i.options.preserveSchemaIds),O=s.schema!=null?Pb(s.schema,!o,i,b,a,i.namespace,!1,new Set,oQr({schema:s,logger:i.logger})):o?El.primitive({nameOverride:void 0,generatedName:g,title:void 0,schema:Jd.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:oQr({schema:s,logger:i.logger})}),description:void 0,availability:c,groupName:void 0}):El.optional({nameOverride:void 0,generatedName:g,title:void 0,value:El.primitive({nameOverride:void 0,generatedName:g,title:void 0,schema:Jd.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:oQr({schema:s,logger:i.logger})}),description:void 0,availability:void 0,groupName:void 0}),description:void 0,availability:c,groupName:void 0,inline:void 0});if(s.in==="header"&&s.schema!=null&&!Kd(s.schema)&&s.schema.default!=null){let w=s.schema.default;typeof w=="string"&&w.length>0&&(O=El.literal({nameOverride:void 0,generatedName:g,title:void 0,value:YB.string(w),description:void 0,availability:c,groupName:void 0}))}let m={name:s.name,schema:O,description:s.description,parameterNameOverride:x7p(s),availability:c,source:a};s.in==="query"?u.queryParameters.push(m):s.in==="path"?u.pathParameters.push({...m,variableReference:I7p(s)}):s.in==="header"?!QDD.has(s.name.toLowerCase())&&!i.authHeaders.has(s.name)?u.headers.push({...m,env:void 0}):i.logger.debug(`Ignoring ${s.name} header, in ${t.toUpperCase()} ${e}`):i.logger.warn(`Skipping ${s.in} parameter, ${s.name}, in ${t.toUpperCase()} ${e}`)}return u}var QDD=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]);function z7p(e,t){for(let r of Object.keys(e))if(r.includes("text/event-stream")){let i=e[r];if(i==null)continue;let n=i.schema;return{contentType:r,schema:n??{},examples:Nfa(i,t)}}}function Cjn(e,t){for(let r of Object.keys(e))if(r.includes("json")||r==="*/*"){let i=e[r];if(i==null)continue;let n=i.schema;return{contentType:r.includes("*")?void 0:r,schema:n??{},examples:Nfa(i,t)}}}function R7p(e,t){for(let r of Object.keys(e)){let i=e[r];if(i==null)continue;return{schema:i.schema??{},examples:Nfa(i,t)}}}function Nfa(e,t){let r=[];e.example!=null&&r.push({name:void 0,value:e.example,description:void 0});let i=bf(e,kU.EXAMPLES);return i!=null&&Object.keys(i).length>0&&r.push(...Object.entries(i).map(([n,a])=>({name:a.summary??n,value:a.value,description:a.description}))),e.examples!=null&&Object.keys(e.examples).length>0&&r.push(...Object.entries(e.examples).map(([n,a])=>{let u=Kd(a)?t.resolveExampleReference(a):a;return{name:u.summary??n,value:u.value,description:u.description}})),r}function JDD(e,t){for(let[r,i]of Object.entries(e.content))if(zB.parse(r)?.isURLEncoded())return{schema:i.schema,contentType:r,examples:Nfa(i,t)}}function KDD(e){for(let[t,r]of Object.entries(e.content))if(zB.parse(t)?.isMultipart())return{schema:r.schema,encoding:r.encoding}}function YDD(e){for(let t in e.content)if(zB.parse(t)?.isOctetStream())return!0;return!1}function XDD(e,t){let r=Kd(e)?y9s(e,t):{id:void 0,schema:e};return Object.entries(r.schema.properties??{}).find(([i,n])=>!Kd(n)&&n.type==="string"&&n.format==="binary")!=null}function Bjn({requestBody:e,document:t,context:r,requestBreadcrumbs:i,source:n,namespace:a}){let u=Kd(e)?r.resolveRequestBodyReference(e):e,l=KDD(u),d=l?.schema,s=l?.encoding,o=JDD(u,r),c=Cjn(u.content,r);if(YDD(u))return lSe.octetStream({description:u.description,source:n});if(d!=null&&c==null||d!=null&&XDD(d,t)){let b=Kd(d)?y9s(d,t):{id:void 0,schema:d},g=Pb(b.schema,!1,r,i,n,a),O=[];if(g.type==="object")for(let m of g.properties){if(m.schema.type==="primitive"&&m.schema.schema.type==="string"&&m.schema.schema.format==="binary"){O.push({key:m.key,schema:CIe.file({isOptional:!1,isArray:!1}),description:m.schema.description,contentType:s?.[m.key]?.contentType,exploded:!1,encoding:void 0});continue}if(m.schema.type==="optional"&&m.schema.value.type==="primitive"&&m.schema.value.schema.type==="string"&&m.schema.value.schema.format==="binary"){O.push({key:m.key,schema:CIe.file({isOptional:!0,isArray:!1}),description:m.schema.description,contentType:s?.[m.key]?.contentType,exploded:!1,encoding:void 0});continue}if(m.schema.type==="array"&&m.schema.value.type==="primitive"&&m.schema.value.schema.type==="string"&&m.schema.value.schema.format==="binary"){O.push({key:m.key,schema:CIe.file({isOptional:!1,isArray:!0}),description:m.schema.description,contentType:s?.[m.key]?.contentType,exploded:!1,encoding:void 0});continue}if(m.schema.type==="optional"&&m.schema.value.type==="array"&&m.schema.value.value.type==="primitive"&&m.schema.value.value.schema.type==="string"&&m.schema.value.value.schema.format==="binary"){O.push({key:m.key,schema:CIe.file({isOptional:!0,isArray:!0}),description:m.schema.description,contentType:s?.[m.key]?.contentType,exploded:!1,encoding:void 0});continue}let w=s?.[m.key]?.contentType;O.push({key:m.key,schema:CIe.json(m.schema),description:void 0,contentType:s?.[m.key]?.contentType,exploded:s?.[m.key]?.explode,encoding:w==null?r.options.defaultFormParameterEncoding:void 0})}return lSe.multipart({name:Kd(d)&&r.getNumberOfOccurrencesForRef(d)===1?b.id:void 0,description:b.schema.description,properties:O,source:n})}if(c!=null){let b=Pb(c.schema,!1,r,i,n,a,!0);return lSe.json({description:void 0,schema:b,contentType:c.contentType,fullExamples:c.examples,additionalProperties:!Kd(c.schema)&&mjn(c.schema.additionalProperties),source:n})}if(o!=null&&o.schema!=null){let b=Pb(o.schema,!1,r,i,n,a);return lSe.json({schema:b,description:u.description,contentType:o.contentType,source:n,fullExamples:o.examples,additionalProperties:!1})}}function y9s(e,t){if(!e.$ref.startsWith(qIi))throw new Error(`Failed to resolve schema reference because of unsupported prefix: ${e.$ref}`);let r=Nli(e);if(r==null)throw new Error(`Failed to resolve schema reference because missing schema id: ${e.$ref}`);let i=t.components?.schemas?.[r];if(i==null)throw new Error(`Failed to resolve schema reference because missing: ${e.$ref}`);return Kd(i)?y9s(i,t):{id:r,schema:i}}var v9s={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"},N7p=new Set(Object.values(v9s));var ZDD=["200","201","202","204"];function L7p({operationContext:e,responses:t,context:r,responseBreadcrumbs:i,responseStatusCode:n,streamFormat:a,source:u}){if(t==null)return{value:void 0,errors:{}};let l=kDD({responses:t,context:r,source:u,namespace:r.namespace}),d=!1,s;for(let o of n!=null?[n]:ZDD){let c=t[o];c!=null&&(d=!0,s==null&&(s=F7p({operationContext:e,response:c,context:r,responseBreadcrumbs:i,streamFormat:a,source:u,namespace:r.namespace,statusCode:typeof o=="string"?parseInt(o):o})))}if(s==null&&!d&&t.default!=null&&(s=F7p({operationContext:e,response:t.default,context:r,responseBreadcrumbs:i,streamFormat:a,source:u,namespace:r.namespace})),s!=null)switch(s.type){case"json":return{value:s,errors:l};case"streamingJson":case"streamingSse":return{value:s,errors:l};case"file":case"text":case"streamingText":return{value:s,errors:l};default:Ko(s)}return{value:void 0,errors:l}}function F7p({operationContext:e,streamFormat:t,response:r,context:i,responseBreadcrumbs:n,source:a,namespace:u,statusCode:l}){let d=Kd(r)?i.resolveResponseReference(r):r;if(d.content!=null&&Object.entries(d.content).find(([b,g])=>{if(g.schema==null)return!1;let O=Kd(g.schema)?i.resolveSchemaReference(g.schema):g.schema;return O.type==="string"&&O.format==="binary"}))return XB.file({description:d.description,source:a,statusCode:l});let s=z7p(d.content??{},i);if(s!=null&&t!=null)switch(t){case"json":return XB.streamingJson({statusCode:l,description:d.description,responseProperty:bf(e.operation,fd.RESPONSE_PROPERTY),fullExamples:s.examples,schema:Pb(s.schema,!1,i,n,a,u),source:a});case"sse":return XB.streamingSse({description:d.description,responseProperty:void 0,fullExamples:s.examples,schema:Pb(s.schema,!1,i,n,a,u),source:a,statusCode:l})}let o=Cjn(d.content??{},i);if(o!=null){if(t!=null)switch(t){case"json":return XB.streamingJson({description:d.description,responseProperty:void 0,fullExamples:o.examples,schema:Pb(o.schema,!1,i,n,a,u),source:a,statusCode:l});case"sse":return XB.streamingSse({description:d.description,responseProperty:void 0,fullExamples:o.examples,schema:Pb(o.schema,!1,i,n,a,u),source:a,statusCode:l})}return XB.json({description:d.description,schema:Pb(o.schema,!1,i,n,a,u),responseProperty:bf(e.operation,fd.RESPONSE_PROPERTY),fullExamples:o.examples,source:a,statusCode:l})}for(let[c,b]of Object.entries(d.content??{})){let g=zB.parse(c);if(g!=null){if(g.isOctetStream()||g.isPDF()||g.isAudio()||g.isImage()||g.isVideo())return XB.file({description:d.description,source:a,statusCode:l});if(g.isPlainText()){let O=b.schema;if(O==null)return XB.text({description:d.description,source:a,statusCode:l});let m=Kd(O)?i.resolveSchemaReference(O):O;return m.type==="string"&&m.format==="byte"?XB.file({description:d.description,source:a,statusCode:l}):XB.text({description:d.description,source:a,statusCode:l})}}}}function kDD({responses:e,context:t,source:r,namespace:i}){let n={};for(let[a,u]of Object.entries(e)){if(a==="default")continue;let l=parseInt(a);if(l<400||l>600)continue;let d=Kd(u)?t.resolveResponseReference(u):u,s=R7p(d.content??{},t),o=v9s[l];if(o==null){t.logger.warn(`No error name found for status code ${a}`);continue}n[l]={statusCode:l,nameOverride:void 0,generatedName:o,description:d.description,schema:Pb(s?.schema??{},!1,t,[o,"Body"],r,i),fullExamples:s?.examples,source:r}}return n}function uQr({operationContext:e,context:t,responseStatusCode:r,suffix:i,streamFormat:n,source:a}){let{document:u,operation:l,path:d,method:s,baseBreadcrumbs:o,sdkMethodName:c}=e,b=bf(l,fd.IDEMPOTENT),g=bf(l,[fd.REQUEST_NAME_V1,fd.REQUEST_NAME_V2]),O=[...o,"Request"],m=Yqo({parameters:[...e.pathItemParameters,...e.operationParameters],context:t,requestBreadcrumbs:O,path:d,httpMethod:s,source:a}),w=/{([^}]+)}/g,A=[...d.matchAll(w)].map(U=>U[1]).filter(U=>!m.pathParameters.some(H=>H.name===U));if(A.length>0)for(let U of A)m.pathParameters.push({name:U??"",variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:a,schema:El.primitive({schema:Jd.string({default:void 0,example:void 0,format:void 0,maxLength:void 0,minLength:void 0,pattern:void 0}),description:void 0,generatedName:"",nameOverride:void 0,groupName:void 0,availability:void 0,title:void 0}),description:void 0});let q=l.requestBody!=null?Bjn({requestBody:l.requestBody,document:u,context:new Tjn({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:O,source:a,namespace:t.namespace}):void 0;tED({context:t,convertedParameters:m})&&q!=null&&q.type==="json"&&q.schema.type!=="object"&&l.requestBody!=null?q=Bjn({requestBody:l.requestBody,document:u,context:t,requestBreadcrumbs:[...O,"Body"],source:a,namespace:t.namespace}):l.requestBody!=null&&(q=Bjn({requestBody:l.requestBody,document:u,context:t,requestBreadcrumbs:[...O],source:a,namespace:t.namespace}));let D=[...o,"Response"],C=L7p({operationContext:e,streamFormat:n,responses:l.responses,context:t,responseBreadcrumbs:D,responseStatusCode:r,source:a});e.method==="GET"&&(q=void 0);let R=B7p(l),$=C7p(e,l,t),I=bf(l,fd.SERVER_NAME_V2);return{summary:l.summary,internal:bf(l,kU.INTERNAL),idempotent:b,audiences:bf(l,fd.AUDIENCES)??[],operationId:l.operationId!=null&&i!=null?l.operationId+"_"+i:l.operationId,tags:t.resolveTagsToTagIds(l.tags),namespace:t.namespace,sdkName:c,pathParameters:m.pathParameters,queryParameters:m.queryParameters,headers:m.headers,requestNameOverride:g??void 0,generatedRequestName:s2(O,t.options.preserveSchemaIds),request:q,response:C.value,errors:C.errors,servers:I!=null?[{name:I,url:void 0,audiences:void 0}]:(l.servers??[]).map(U=>Kqo(U)),description:l.description,authed:eED(l,u),availability:R,method:s,path:d,examples:$,pagination:e.pagination,source:a}}function eED(e,t){return e.security!=null?Object.keys(e.security).length>0:t.security!=null?Object.keys(t.security).length>0:!1}function tED({context:e,convertedParameters:t}){return e.options.inlinePathParameters&&t.pathParameters.length>0||t.queryParameters.length>0||t.headers.length>0}function V7p({operationContext:e,context:t,asyncExtension:r,source:i}){let{operation:n,pathItemParameters:a,operationParameters:u}=e,l=r.discriminant.name,d=r.discriminant.value,s=r["response-status-code"],o=U7p({context:t,headerToIgnore:l,parameters:a}),c=U7p({context:t,headerToIgnore:l,parameters:u}),b=uQr({operationContext:{...e,pathItemParameters:o,operationParameters:c,operation:{...n,responses:Object.fromEntries(Object.entries(n.responses).filter(([O])=>parseInt(O)!==s))}},context:t,streamFormat:void 0,source:i}),g=uQr({operationContext:{...e,pathItemParameters:o,operationParameters:c,baseBreadcrumbs:[...e.baseBreadcrumbs,"async"]},context:t,suffix:"async",responseStatusCode:s,streamFormat:void 0,source:i});return g.headers.push({name:l,schema:El.literal({nameOverride:void 0,generatedName:s2([l],t.options.preserveSchemaIds),title:void 0,description:void 0,availability:void 0,value:YB.string(d),groupName:void 0}),description:void 0,parameterNameOverride:void 0,env:void 0,availability:void 0,source:i}),{sync:b,async:g}}function U7p({context:e,headerToIgnore:t,parameters:r}){return r.filter(i=>{let n=Kd(i)?e.resolveParameterReference(i):i;return!(n.in==="header"&&n.name===t)})}var b9s="stream";function G7p({operationContext:e,context:t,streamingExtension:r}){switch(r.type){case"stream":return{streaming:uQr({operationContext:e,context:t,streamFormat:r.format,source:t.source}),nonStreaming:void 0};case"streamCondition":{let i=W7p({context:t,operation:e.operation,streamingExtension:r,isStreaming:!0});if(i?.schemaReference!=null){let s=Nli(i.schemaReference);s!=null&&t.excludeSchema(s)}let n=H7p({operation:e.operation,response:r.responseStream}),a=uQr({operationContext:{...e,sdkMethodName:e.sdkMethodName!=null?{groupName:e.sdkMethodName.groupName,methodName:e.sdkMethodName.methodName+"_"+b9s}:void 0,operation:{...e.operation,description:r.streamDescription??e.operation.description,requestBody:i?.requestBody,responses:n},baseBreadcrumbs:[...e.baseBreadcrumbs,b9s]},context:t,streamFormat:r.format,suffix:b9s,source:t.source});a.examples=a.examples.filter(s=>$7p(s,t)!==!1);let u=W7p({context:t,operation:e.operation,streamingExtension:r,isStreaming:!1}),l=H7p({operation:e.operation,response:r.response}),d=uQr({streamFormat:void 0,operationContext:{...e,operation:{...e.operation,requestBody:u?.requestBody,responses:l}},context:t,source:t.source});return d.examples=d.examples.filter(s=>$7p(s,t)!==!0),{streaming:a,nonStreaming:d}}default:Ko(r)}}function W7p({context:e,operation:t,streamingExtension:r,isStreaming:i}){if(t.requestBody==null)return;let n=Kd(t.requestBody)?e.resolveRequestBodyReference(t.requestBody):t.requestBody,a=Cjn(n.content,e);if(a==null)return;let u=Kd(a.schema)?e.resolveSchemaReference(a.schema):a.schema;if(u.allOf==null&&u.properties==null)return;let l=u.properties?.[r.streamConditionProperty];l!=null&&Kd(l)&&(l=void 0);let d={...u,properties:{...u.properties,[r.streamConditionProperty]:{type:"boolean","x-fern-boolean-literal":i,...l??{}}},title:void 0,required:[...u.required??[],r.streamConditionProperty]};return{requestBody:{content:{[zB.APPLICATION_JSON]:{schema:d}}},schemaReference:Kd(a.schema)?a.schema:void 0}}function H7p({operation:e,response:t}){return{...e.responses,200:{description:"",content:{[zB.APPLICATION_JSON]:{schema:t}}}}}function $7p(e,t){return e._visit({unknown:r=>{let i=G6.serialization.ExampleEndpointCallSchema.parse(r);if(i.ok&&i.value.response!=null)return i.value.response.stream!=null},full:()=>{},_other:()=>{}})}function Q7p({context:e,operationContext:t,source:r}){let{document:i,operation:n,path:a,method:u,baseBreadcrumbs:l,sdkMethodName:d}=t,s=[...l,"Payload"],o=Yqo({parameters:[...t.pathItemParameters,...t.operationParameters],context:e,requestBreadcrumbs:s,path:a,httpMethod:u,source:r});if(n.requestBody==null){e.logger.error(`Skipping webhook ${u.toUpperCase()} ${a}: Missing a request body`);return}if(u!=="POST"&&u!=="GET"){e.logger.error(`Skipping webhook ${u.toUpperCase()} ${a}: Not POST or GET`);return}let c=Bjn({requestBody:n.requestBody,document:i,context:e,requestBreadcrumbs:[...l,"Payload"],source:r,namespace:e.namespace});if(c==null||c.type!=="json"){e.logger.error(`Skipping webhook ${a} because non-json request body`);return}if(n.operationId==null){e.logger.error(`Skipping webhook ${a} because no operation id present`);return}return{summary:n.summary,sdkName:d,namespace:e.namespace,method:u,operationId:n.operationId,tags:e.resolveTagsToTagIds(n.tags),headers:o.headers,generatedPayloadName:s2(s,e.options.preserveSchemaIds),payload:c.schema,description:n.description,examples:rED(c.fullExamples),source:r}}function rED(e){if(e==null)return[];let t=[];for(let r of e){let i=Fli(r.value);i!=null&&t.push({description:r.description,name:r.name,payload:i})}return t}function g9s({context:e,pathItemContext:t,operation:r,convertToWebhook:i}){let n=bf(r,fd.IGNORE);if(n!=null&&n){e.logger.debug(`${t.method.toUpperCase()} ${t.path} is marked with x-fern-ignore. Skipping.`);return}let a=iED(r,e),u=A7p(e.document,r),l={...t,sdkMethodName:a,baseBreadcrumbs:nED({operation:r,sdkMethodName:a,httpMethod:t.method,path:t.path,shouldUseIdiomaticRequestNames:e.options.shouldUseIdiomaticRequestNames}),operation:r,operationParameters:r.parameters??[],pagination:u};if(i){let c=Q7p({context:e,operationContext:l,source:e.source});return c!=null?{type:"webhook",value:c}:void 0}let d=E7p(r);if(d!=null){let c=G7p({context:e,operationContext:l,streamingExtension:d});return c!=null?{type:"streaming",streaming:c.streaming,nonStreaming:c.nonStreaming}:void 0}let s=S7p(r);if(s!=null){let c=V7p({context:e,operationContext:l,asyncExtension:s,source:e.source});return{type:"async",async:c.async,sync:c.sync}}return{type:"http",value:uQr({context:e,operationContext:l,streamFormat:void 0,source:e.source})}}function iED(e,t){let r=bf(e,fd.SDK_METHOD_NAME),i=bf(e,fd.SDK_GROUP_NAME)??[];if(r!=null){let n=typeof i=="string"?[i]:i;return n=t.resolveGroupName(n),{groupName:n,methodName:r}}}function nED({sdkMethodName:e,operation:t,httpMethod:r,path:i,shouldUseIdiomaticRequestNames:n}){let a=[];if(e!=null){if(n&&a.push(e.methodName),e.groupName.length>0){let u=e.groupName[e.groupName.length-1];u!=null&&a.push(typeof u=="string"?u:u.name)}n||a.push(e.methodName)}else t.operationId!=null?a.push(t.operationId):a.push(vg(`${r}_${i.split("/").join("_")}`));return a}function J7p(e,t,r,i){let n=[],a=Y7p(t),u={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let l of a){if(i.filter.skipEndpoint({method:l.method,path:e})){i.logger.debug(`Skipping endpoint "${l.method} ${e}"`);continue}let d=aED({operation:l.operation}),s=g9s({context:i,pathItemContext:{...u,method:l.method},operation:l.operation,convertToWebhook:d});s!=null&&n.push(s)}return n}function K7p(e,t,r,i){let n=[],a=Y7p(t),u={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let l of a){if(i.filter.skipEndpoint({method:l.method,path:e})){i.logger.debug(`Skipping endpoint "${l.method} ${e}"`);continue}let d=g9s({context:i,pathItemContext:{...u,method:l.method},operation:l.operation,convertToWebhook:!0});d!=null&&n.push(d)}return n}function Y7p(e){let t=[];return e.get!=null&&t.push({method:W$.Get,operation:e.get}),e.post!=null&&t.push({method:W$.Post,operation:e.post}),e.put!=null&&t.push({method:W$.Put,operation:e.put}),e.delete!=null&&t.push({method:W$.Delete,operation:e.delete}),e.patch!=null&&t.push({method:W$.Patch,operation:e.patch}),t}function aED({operation:e}){return bf(e,[fd.WEBHOOK])??!1}function X7p(e){let t=bf(e,fd.BASIC_AUTH_USERNAME_VARIABLE_NAME),r=bf(e,fd.BASIC_AUTH_PASSWORD_VARIABLE_NAME);return{usernameVariable:t,passwordVariable:r}}function Z7p(e){return bf(e,fd.FERN_BASIC_AUTH)}function O9s(e,t){if(Kd(e))throw new Error(`Converting referenced security schemes is unsupported: ${JSON.stringify(e)}`);return oED(e,t)}function oED(e,t){if(e.type==="apiKey"&&e.in==="header"){let r=bf(e,kU.BEARER_FORMAT),i=bf(e,fd.FERN_HEADER_AUTH);return k8.header({headerName:e.name,prefix:r!=null?"Bearer":i?.prefix,headerVariableName:i?.name??bf(e,fd.HEADER_VARIABLE_NAME),headerEnvVar:i?.env})}else if(e.type==="http"&&e.scheme==="bearer"){let r=bf(e,fd.FERN_BEARER_TOKEN);return k8.bearer({tokenVariableName:r?.name??bf(e,fd.BEARER_TOKEN_VARIABLE_NAME),tokenEnvVar:r?.env})}else if(e.type==="http"&&e.scheme==="basic"){let r=Z7p(e),i=X7p(e);return k8.basic({usernameVariableName:r?.username?.name??i.usernameVariable,usernameEnvVar:r?.username?.env,passwordVariableName:r?.password?.name??i.passwordVariable,passwordEnvVar:r?.password?.env})}else{if(e.type==="openIdConnect")return k8.bearer({tokenVariableName:void 0,tokenEnvVar:void 0});if(e.type==="oauth2")return k8.oauth({scopesEnum:uED(e,t)})}throw new Error(`Failed to convert security scheme ${JSON.stringify(e)}`)}function uED(e,t){let r=e.flows.authorizationCode?.scopes??e.flows.clientCredentials?.scopes??e.flows.implicit?.scopes??e.flows.password?.scopes;if(r!=null){let i=SYt({nameOverride:void 0,generatedName:"OauthScope",title:void 0,enumValues:Object.keys(r),fernEnum:Object.fromEntries(Object.entries(r).map(([a,u])=>[a,{description:u}])),_default:void 0,description:void 0,availability:void 0,enumVarNames:void 0,wrapAsNullable:!1,groupName:void 0,context:void 0,source:t,inline:void 0}),n=kD(i);if(n.type==="enum")return n}}function k7p(e){return bf(e,fd.BASE_PATH)}var sED=Yu.record(Yu.string(),Yu.object({summary:Yu.string().optional(),description:Yu.string().optional()}));function e6p({document:e,context:t}){return Bfa(e,fd.GROUPS,sED,t.logger)}function t6p({context:e,document:t}){return bf(t,fd.FERN_VERSION)??void 0}function r6p(e){let t=bf(e,fd.FERN_GLOBAL_HEADERS),r=[];for(let i of t??[])r.push({...i,schema:i.type!=null?xfa({fernType:i.type,description:void 0,availability:void 0,generatedName:i.name??i.header,title:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function i6p(e){let t=bf(e,fd.FERN_IDEMPOTENCY_HEADERS),r=[];for(let i of t??[])r.push({...i,schema:i.type!=null?xfa({fernType:i.type,description:void 0,availability:void 0,generatedName:i.name??i.header,title:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function n6p(e,t){let r=bf(e,fd.SDK_VARIABLES);return r==null?{}:Object.fromEntries(Object.entries(r).map(([i,n])=>{if(n.type==="string")return[i,{nameOverride:void 0,generatedName:s2([i],t),title:n.title,schema:sj.string({default:Sjn(n),pattern:n.pattern,format:n.format,minLength:n.minLength,maxLength:n.maxLength}),description:n.description,availability:void 0,groupName:void 0}];throw new Error(`Variable ${i} has unsupported schema ${JSON.stringify(n)}`)}))}var cED="webhooks";function a6p(e){return bf(e,cED)??{}}function o6p(e){return bf(e,fd.RESOLUTIONS)}function u6p({openapi:e}){let t=o6p(e);if(t==null)return e;let r={};for(let i of t){let n=`#/components/schemas/${i.name}`;for(let a of i.resolutions)e=lED({openapi:e,schemaReference:a,schemaName:i.name}),e=s6p({openapi:e,replaceReference:a,schemaReference:n,replacedReferences:r}),r={...r,...Object.fromEntries(i.resolutions.map(u=>[n,u]))}}return e}function lED({openapi:e,schemaReference:t,schemaName:r}){let i=t.replace("#/","").split("/").map(a=>a.replaceAll("~1","/")),n=e;for(let a of i){let u=n[a];if(u==null)return e;n=u}return e.components==null&&(e.components={}),e.components.schemas==null&&(e.components.schemas={}),e.components.schemas[r]=n,e}function s6p({openapi:e,replaceReference:t,schemaReference:r,replacedReferences:i}){let n=Object.keys(i).filter(d=>t.startsWith(d)).sort((d,s)=>s.length-d.length)[0];if(n!=null){let d=i[n];if(d!=null){let s=r.replace(n,d);return s6p({openapi:e,replaceReference:t,schemaReference:s,replacedReferences:{}})}}let a=t.replace("#/","").split("/").map(d=>d.replaceAll("~1","/")),u=e;for(let d of a.slice(0,-1)){let s=u[d];if(s==null)return e;u=s}let l=a[a.length-1];return l==null||(u[l]={$ref:r}),e}function l6p({openApi:e,taskContext:t,options:r,source:i,namespace:n}){e=u6p({openapi:e});let a=Object.fromEntries(Object.entries(e.components?.securitySchemes??{}).map(([I,U])=>O9s(U,i)==null?[]:[I,O9s(U,i)])),u=new Set(...Object.entries(a).map(([I,U])=>U.type==="basic"||U.type==="bearer"?"Authorization":U.type==="header"?U.headerName:null)),l=n6p(e,r.preserveSchemaIds),d=r6p(e),s=i6p(e),o=r.audiences??[],c=[],b=[],g=new Jqo({document:e,taskContext:t,authHeaders:u,options:r,source:i,namespace:n});g.filter.hasEndpoints()&&t.logger.debug("Endpoint filter applied..."),Object.entries(e.paths??{}).forEach(([I,U])=>{if(U==null)return;t.logger.debug(`Converting path ${I}`);let H=J7p(I,U,e,g);for(let k of H){let K=c6p({operation:k});if(!(o.length>0&&!o.some(te=>K.includes(te))))switch(k.type){case"async":c.push(k.sync),c.push(k.async);break;case"http":c.push(k.value);break;case"streaming":c.push(k.streaming),k.nonStreaming&&c.push(k.nonStreaming);break;case"webhook":b.push(k.value);break;default:Ko(k)}}}),Object.entries(a6p(e)).forEach(([I,U])=>{if(U==null)return;t.logger.debug(`Converting path ${I}`);let H=K7p(I,U,e,g);for(let k of H){let K=c6p({operation:k});o.length>0&&!o.some(te=>K.includes(te))||b.push(k.value)}});let O=Object.fromEntries(Object.entries(e.components?.schemas??{}).map(([I,U])=>{if(!Kd(U)){let H=bf(U,fd.IGNORE);if(H!=null&&H)return[];if(N7p.has(I))return[I,Pb({...U,"x-fern-type-name":`${I}Body`},!1,g,[I],i,n)]}return[I,Pb(U,!1,g,[I],i,n)]}).filter(I=>I.length>0)),m=fED(O,g,i),w=dED(m,g),E={};for(let[I,U]of Object.entries(w)){let H=kD(U);g.isSchemaExcluded(I)||(E[I]=H,t.logger.debug(`Converted schema ${I}`))}let A=new Lli(w,g.nonRequestReferencedSchemas,g),q=b.map(I=>{let H=I.examples;if(!r.disableExamples&&H.length===0){let k=A.buildExample({schema:I.payload,exampleId:void 0,example:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});k!=null&&(H=[{name:void 0,description:void 0,payload:k}])}return{...I,payload:kD(I.payload),examples:H}}),D=new Vqo(w,g),C=c.map(I=>{let U=I.examples,H=U;if(!r.disableExamples&&(U.length===0||U.every(zfa))){let te=D.buildEndpointExample(I);te.length>0&&(H=[...te,...U.filter(fe=>!zfa(fe))])}let k=I.request,K=I.response;return{...I,request:k?.type==="json"?{...k,schema:kD(k.schema)}:k,response:K?.type==="json"?{...K,schema:kD(K.schema)}:K,queryParameters:I.queryParameters.map(te=>({description:te.description,name:te.name,schema:kD(te.schema),parameterNameOverride:te.parameterNameOverride,availability:te.availability,source:te.source})),pathParameters:I.pathParameters.map(te=>({description:te.description,name:te.name,schema:kD(te.schema),parameterNameOverride:te.parameterNameOverride,variableReference:te.variableReference,availability:te.availability,source:te.source})),headers:I.headers.map(te=>({description:te.description,name:te.name,schema:kD(te.schema),parameterNameOverride:te.parameterNameOverride,env:te.env,availability:te.availability,source:te.source})),examples:H,errors:od(I.errors,te=>{let fe=te.fullExamples?.map(me=>{let be=Fli(me.value);if(be!=null)return{name:me.name,description:me.description,example:be}}).filter(u0);if(fe?.length===0){let me=A.buildExample({schema:te.schema,example:void 0,exampleId:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});me!=null&&fe.push({name:void 0,description:void 0,example:me})}return{generatedName:te.generatedName,nameOverride:te.nameOverride,schema:kD(te.schema),description:te.description,source:te.source,examples:fe}})}}),R=e6p({document:e,context:g});return{apiVersion:t6p({context:g,document:e}),basePath:k7p(e),title:e.info.title,description:e.info.description,groups:Object.fromEntries(Object.entries(R??{}).map(([I,U])=>[I,{summary:U.summary??void 0,description:U.description??void 0}])),servers:(e.servers??[]).map(I=>Kqo(I)),websocketServers:[],tags:{tagsById:Object.fromEntries((e.tags??[]).map(I=>[I.name,{id:I.name,description:I.description}])),orderedTagIds:e.tags?.map(I=>I.name)},endpoints:C,webhooks:q,channels:{},groupedSchemas:Mjn(n,E),securitySchemes:a,hasEndpointsMarkedInternal:C.some(I=>I.internal),nonRequestReferencedSchemas:g.getReferencedSchemas(),variables:l,globalHeaders:d,idempotencyHeaders:s}}function fED(e,t,r){let i={};for(let[n,a]of Object.entries(e)){if(a.type!=="object"){i[n]=a;continue}let u={$ref:`#/components/schemas/${n}`},l=t.getReferencesFromDiscriminatedUnion(u);if(l==null){i[n]=a;continue}let d={...a,type:"object",properties:a.properties.filter(o=>!l.discriminants.has(o.key)),allOfPropertyConflicts:a.allOfPropertyConflicts.filter(o=>!l.discriminants.has(o.propertyKey)),source:r};i[n]=d;let s=f6p({schema:a,schemas:e});for(let o of[...new Set(s)]){let c=i[o]??e[o];c==null||c.type!=="object"||(i[o]={...c,type:"object",properties:c.properties.filter(b=>!l.discriminants.has(b.key)),allOfPropertyConflicts:c.allOfPropertyConflicts.filter(b=>!l.discriminants.has(b.propertyKey))})}}return i}function dED(e,t){let r={};for(let[i,n]of Object.entries(e)){if(n.type!=="object"){r[i]=n;continue}let a={$ref:`#/components/schemas/${i}`},u=t.getDiscriminatedUnionMetadata(a);if(u==null){r[i]=n;continue}let l=[];for(let s of n.properties)if(u.discriminants.has(s.key)){let o=u.discriminants.get(s.key);o!=null&&l.push({...s,schema:El.literal({nameOverride:void 0,generatedName:s2([n.generatedName,o],t.options.preserveSchemaIds),title:void 0,value:YB.string(o),groupName:void 0,description:void 0,availability:n.availability})})}else l.push(s);let d={...n,type:"object",properties:l};r[i]=d}return r}function f6p({schema:e,schemas:t}){let r=[];for(let i of e.allOf){r.push(i.schema);let n=t[i.schema];n!=null&&n.type==="object"&&r.push(...f6p({schema:n,schemas:t}))}return r}function c6p({operation:e}){let t=[];switch(e.type){case"async":t=e.async.audiences;break;case"http":t=e.value.audiences;break;case"streaming":t=e.streaming.audiences;break;case"webhook":break;default:Ko(e)}return t}function TIi({context:e,documents:t,options:r}){let i={apiVersion:void 0,title:void 0,description:void 0,basePath:void 0,servers:[],websocketServers:[],tags:{tagsById:{},orderedTagIds:void 0},hasEndpointsMarkedInternal:!1,endpoints:[],webhooks:[],channels:{},groupedSchemas:{rootSchemas:{},namespacedSchemas:{}},variables:{},nonRequestReferencedSchemas:new Set,securitySchemes:{},globalHeaders:[],idempotencyHeaders:[],groups:{}};for(let n of t){let a=n.source!=null?n.source:Kre.openapi({file:"<memory>"});switch(n.type){case"openapi":{let u=l6p({taskContext:e,openApi:n.value,options:a9s({options:n.settings,overrides:r}),source:a,namespace:n.namespace});i=_ED(i,u);break}case"asyncapi":{let u=g7p({document:n.value,taskContext:e,options:a9s({options:n.settings,overrides:r}),source:a,asyncApiOptions:pED({options:n.settings}),namespace:n.namespace});u.servers!=null&&(i.websocketServers=[...i.websocketServers,...u.servers.map(l=>({...l,audiences:void 0,description:void 0}))]),u.channels!=null&&(i.channels={...i.channels,...u.channels}),u.groupedSchemas!=null&&(i.groupedSchemas=d6p(i.groupedSchemas,u.groupedSchemas)),u.basePath!=null&&(i.basePath=u.basePath);break}default:Ko(n)}}return i}function pED({options:e,overrides:t}){return{naming:t?.naming??e?.asyncApiNaming??R3p.naming}}function _ED(e,t){return{apiVersion:e.apiVersion??t.apiVersion,title:e.title??t.title,description:e.description??t.description,basePath:e.basePath??t.basePath,servers:[...e.servers,...t.servers],websocketServers:[...e.websocketServers,...t.websocketServers],tags:{tagsById:{...e.tags.tagsById,...t.tags.tagsById},orderedTagIds:e.tags.orderedTagIds==null&&t.tags.orderedTagIds==null?void 0:[...e.tags.orderedTagIds??[],...t.tags.orderedTagIds??[]]},hasEndpointsMarkedInternal:e.hasEndpointsMarkedInternal||t.hasEndpointsMarkedInternal,endpoints:[...e.endpoints,...t.endpoints],webhooks:[...e.webhooks,...t.webhooks],channels:{...e.channels,...t.channels},groupedSchemas:d6p(e.groupedSchemas,t.groupedSchemas),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},globalHeaders:e.globalHeaders!=null?[...e.globalHeaders,...t.globalHeaders??[]]:void 0,idempotencyHeaders:e.idempotencyHeaders!=null?[...e.idempotencyHeaders,...t.idempotencyHeaders??[]]:void 0,groups:{...e.groups,...t.groups}}}function d6p(e,t){e.rootSchemas={...e.rootSchemas,...t.rootSchemas};for(let[r,i]of Object.entries(t.namespacedSchemas))e.namespacedSchemas[r]!=null?e.namespacedSchemas[r]={...e.namespacedSchemas[r],...i}:e.namespacedSchemas[r]=i;return e}var Xqo={config:new p6p.Config({apis:{},styleguide:{plugins:[n9s],rules:{spec:"warn"}}},void 0),dereference:!1,removeUnusedComponents:!1,keepUrlRefs:!0};function Ffa(e){return e.swagger!=null}function m9s(e){return e.openapi!=null}function Uli(e,t={}){return{...Object.fromEntries(vN(e.namedDefinitionFiles).map(([r,i])=>[r,{...i,defaultUrl:t.defaultURL}])),...vN(e.importedDefinitions).reduce((r,[i,n])=>({...r,...Pkn(Uli(n.definition,{defaultURL:n.url}),(a,u)=>sR(i,ry.of(u)))}),{})}}function Lfa(e,t={}){return{...Object.fromEntries(vN(e.packageMarkers).map(([r,i])=>[r,{...i,defaultUrl:t.defaultURL}])),...vN(e.importedDefinitions).reduce((r,[i,n])=>({...r,...Pkn(Lfa(n.definition,{defaultURL:n.url}),(a,u)=>sR(i,ry.of(u)))}),{})}}function sQr(e){return{...Lfa(e),...Uli(e)}}function aie(e,t){return sQr(e.definition)[t]?.contents}function XN(e,t){for(let[r,i]of vN(sQr(e.definition)))t(r,i.contents,{isPackageMarker:XAi(r)===W1,defaultUrl:i.defaultUrl})}function CIi(e,t){for(let[r,i]of vN(Lfa(e.definition)))t(r,i.contents)}var P5p=vi(m5p(),1);async function Cda(e){return(await(0,P5p.convertObj)(e,{})).openapi}var w5p=require("fs/promises");var j5p=require("fs/promises");async function aCo({absoluteFilePathToOverrides:e,data:t,context:r,allowNullKeys:i}){let n=null;try{let a=(await(0,j5p.readFile)(e,"utf8")).toString();try{n=JSON.parse(a)}catch{n=rp.load(a,{json:!0})}}catch{return r.failAndThrow(`Failed to read overrides from file ${e}`)}return Hus({data:t,overrides:n,allowNullKeys:i})}async function S5p({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let i=(await(0,w5p.readFile)(t)).toString(),n=await rp.load(i);return r!=null?await aCo({absoluteFilePathToOverrides:r,context:e,data:n}):n}var xda=vi(Cqo(),1);var D5p=vi(Cqo(),1),wUs=vi(require("path"),1);var Bda=class extends D5p.BaseResolver{absolutePathToOpenAPIOverrides;constructor(t){super(),this.absolutePathToOpenAPIOverrides=t}resolveExternalRef(t,r){let i=super.resolveExternalRef(t,r);return wHr(Wl.of(i))?i:this.absolutePathToOpenAPIOverrides!=null?wUs.default.resolve(wUs.default.dirname(this.absolutePathToOpenAPIOverrides),r):i}};async function SUs({absolutePathToOpenAPI:e,absolutePathToOpenAPIOverrides:t,parsed:r}){return(r!=null?await(0,xda.bundle)({...Xqo,doc:{source:new xda.Source(e,"<openapi>"),parsed:r},externalRefResolver:new Bda(t)}):await(0,xda.bundle)({...Xqo,ref:e,externalRefResolver:new Bda(t)})).bundle.parsed}var DBD=["examples","example",fd.EXAMPLES,kU.REDOCLY_CODE_SAMPLES_CAMEL,kU.REDOCLY_CODE_SAMPLES_KEBAB];async function Ida({context:e,absolutePathToOpenAPI:t,absolutePathToOpenAPIOverrides:r}){let i=await SUs({absolutePathToOpenAPI:t}),n;if(r!=null?n=r:typeof i=="object"&&i[fd.OPENAPI_OVERIDES_FILEPATH]!=null&&(n=Xu(fp(t),Xa.of(i[fd.OPENAPI_OVERIDES_FILEPATH]))),n!=null){let a=await aCo({absoluteFilePathToOverrides:n,context:e,data:i,allowNullKeys:DBD});return await SUs({absolutePathToOpenAPI:t,absolutePathToOpenAPIOverrides:r,parsed:a})}return i}var e5t=class{absoluteFilePath;constructor(t){this.absoluteFilePath=t}async loadDocuments({context:t,specs:r}){let i=[];for(let n of r){let a=(await(0,E5p.readFile)(n.absoluteFilepath)).toString(),u=Qq(this.absoluteFilePath,n.source.file);n.source.relativePathToDependency!=null&&(u=Xu(n.source.relativePathToDependency,u));let l=n.source.type==="protobuf"?Kre.protobuf({file:u}):Kre.openapi({file:u});if(a.includes("openapi")||a.includes("swagger")){let d=await Ida({absolutePathToOpenAPI:n.absoluteFilepath,context:t,absolutePathToOpenAPIOverrides:n.absoluteFilepathToOverrides});if(m9s(d))i.push({type:"openapi",value:d,source:l,namespace:n.namespace,settings:n.settings});else if(Ffa(d)){let s=await Cda(d);i.push({type:"openapi",value:s,source:l,namespace:n.namespace,settings:n.settings})}}else if(a.includes("asyncapi")){let d=await S5p({context:t,absoluteFilePath:n.absoluteFilepath,absoluteFilePathToOverrides:n.absoluteFilepathToOverrides});i.push({type:"asyncapi",value:d,source:l,namespace:n.namespace,settings:n.settings})}else t.failAndThrow(`${n.absoluteFilepath} is not a valid OpenAPI or AsyncAPI file`)}return i}};var hCo=require("fs/promises"),rLp=vi(fte(),1);var tLp=vi(eLp(),1);async function eG(e,t,r=[],{doNotPipeOutput:i=!1,secrets:n=[],substitutions:a={},...u}={}){let l=n.reduce((o,c)=>({...o,[c]:"<redacted>"}),a),d=[t,...r].join(" ");for(let[o,c]of Object.entries(l))d=d.replaceAll(o,c);e?.debug(`+ ${d}`);let s=(0,tLp.default)(t,r,u);return i||(s.stdout?.pipe(process.stdout),s.stderr?.pipe(process.stderr)),s.then(o=>(o.stdout==null&&(o.stdout=""),o.stderr==null&&(o.stderr=""),o))}function pCo(e,{logger:t,...r}={}){return(i,n)=>eG(t,e,i,{...r,...n})}var gID="buf.gen.yaml",iLp="output",OID=`${iLp}/openapi.yaml`,_Co=class{context;constructor({context:t}){this.context=t}async generate({absoluteFilepathToProtobufRoot:t,absoluteFilepathToProtobufTarget:r,relativeFilepathToProtobufRoot:i,local:n}){return n?this.generateLocal({absoluteFilepathToProtobufRoot:t,absoluteFilepathToProtobufTarget:r,relativeFilepathToProtobufRoot:i}):this.generateRemote()}async generateLocal({absoluteFilepathToProtobufRoot:t,absoluteFilepathToProtobufTarget:r,relativeFilepathToProtobufRoot:i}){let n=await this.setupProtobufGeneratorConfig({absoluteFilepathToProtobufRoot:t,relativeFilepathToProtobufRoot:i}),a=Qq(t,r);return this.doGenerateLocal({cwd:n,target:a})}async setupProtobufGeneratorConfig({absoluteFilepathToProtobufRoot:t,relativeFilepathToProtobufRoot:r}){let i=Wl.of((await rLp.default.dir()).path);return await(0,hCo.cp)(t,i,{recursive:!0}),await(0,hCo.writeFile)(Xu(i,Xa.of(gID)),mID({relativeFilepathToProtobufRoot:r})),i}async doGenerateLocal({cwd:t,target:r}){let i=pCo("which",{cwd:t,logger:this.context.logger});try{await i(["buf"])}catch{this.context.failAndThrow("Missing required dependency; please install 'buf' to continue (e.g. 'brew install buf').")}try{await i(["protoc-gen-openapi"])}catch{this.context.failAndThrow("Missing required dependency; please install 'protoc-gen-openapi' to continue (e.g. 'brew install go && go install github.com/fern-api/protoc-gen-openapi/cmd/protoc-gen-openapi@latest').")}let n=pCo("buf",{cwd:t,logger:this.context.logger});return await n(["config","init"]),await n(["generate",r]),Xu(t,Xa.of(OID))}async generateRemote(){this.context.failAndThrow("Remote Protobuf generation is unimplemented.")}};function mID({relativeFilepathToProtobufRoot:e}){return`
|
|
1936
|
+
`)),{ok:!0,value:t}):i}}function jSo(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var kmn=class e extends Error{errors;constructor(t){super(t.map(jSo).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var ePn=class e extends Error{errors;constructor(t){super(t.map(jSo).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function CA(e){return{optional:()=>V7s(e),transform:t=>W7s(e,t),parseOrThrow:(t,r)=>{let i=e.parse(t,r);if(i.ok)return i.value;throw new ePn(i.errors)},jsonOrThrow:(t,r)=>{let i=e.json(t,r);if(i.ok)return i.value;throw new kmn(i.errors)}}}function V7s(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:()=>FP.OPTIONAL};return{...t,...CA(t)}}function W7s(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,...CA(r)}}function Zqp(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:yM(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:yM(t,"bigint")}]},getType:()=>FP.BIGINT};return{...e5(e),...CA(e)}}var eaD=/^([+-]?\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 kqp(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:yM(t,"string")}]}:eaD.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:yM(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:yM(t,"Date object")}]},getType:()=>FP.DATE};return{...e5(e),...CA(e)}}function H$(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...e5(r),...CA(r)}}}function wSo(e){let t=new Set(e);return H$(FP.ENUM,(i,{allowUnrecognizedEnumValues:n,breadcrumbsPrefix:a=[]}={})=>typeof i!="string"?{ok:!1,errors:[{path:a,message:yM(i,"string")}]}:!t.has(i)&&!n?{ok:!1,errors:[{path:a,message:yM(i,"enum")}]}:{ok:!0,value:i})()}function eTp(e){let t=H7s(e);return{...t,...CA(t)}}function H7s(e){return{parse:(t,r)=>tPn(e).parse(t,r),json:(t,r)=>tPn(e).json(t,r),getType:()=>tPn(e).getType()}}function tPn(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function jla(e){return Object.entries(e)}function wla(e,t){let r=new Set(t);return Object.entries(e).reduce((i,[n,a])=>(r.has(n)&&(i[n]=a),i),{})}function rli(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 Sla(e){return Object.keys(e)}function tTp(e,t){let r=[],i=[];for(let n of e)t(n)?r.push(n):i.push(n);return[r,i]}function U8t(e){return{withParsedProperties:t=>$7s(e,t)}}function $7s(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(!rli(i))return{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:yM(i,"object")}]};let a=new Set(Object.keys(t)),u=wla(i,Object.keys(i).filter(l=>!a.has(l)));return e.json(u,n)},getType:()=>e.getType()};return{...r,...CA(r),...U8t(r)}}function rTp(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function ili(e){return e.isProperty}function SSo(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,i])=>ili(i)?i.rawKey:r),_getParsedProperties:()=>Sla(e),parse:(r,i)=>{let n={},a=[];for(let[u,l]of jla(e)){let d=ili(l)?l.rawKey:u,s=ili(l)?l.valueSchema:l,o={rawKey:d,parsedKey:u,valueSchema:s};n[d]=o,aTp(s)&&a.push(d)}return iTp({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 jla(e)){let l=ili(u)?u.valueSchema:u;aTp(l)&&n.push(a)}return iTp({value:r,requiredKeys:n,getProperty:a=>{let u=e[a];if(u!=null)return ili(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:()=>FP.OBJECT};return{...e5(t),...CA(t),...U8t(t),...Xxi(t)}}function iTp({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:i="fail",skipValidation:n=!1,breadcrumbsPrefix:a=[]}){if(!rli(e))return{ok:!1,errors:[{path:a,message:yM(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 Xxi(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(i,n)=>nTp({extensionKeys:t._getRawProperties(),value:i,transformBase:a=>e.parse(a,n),transformExtension:a=>t.parse(a,n)}),json:(i,n)=>nTp({extensionKeys:t._getParsedProperties(),value:i,transformBase:a=>e.json(a,n),transformExtension:a=>t.json(a,n)}),getType:()=>FP.OBJECT};return{...r,...CA(r),...U8t(r),...Xxi(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:()=>FP.OBJECT};return{...t,...CA(t),...U8t(t),...Xxi(t)}}}}function nTp({extensionKeys:e,value:t,transformBase:r,transformExtension:i}){let n=new Set(e),[a,u]=tTp(Sla(t),s=>n.has(s)),l=r(wla(t,u)),d=i(wla(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 aTp(e){return!taD(e)}function taD(e){switch(e.getType()){case FP.ANY:case FP.UNKNOWN:case FP.OPTIONAL:return!0;default:return!1}}function oTp(e){return SSo(e)}function uTp(e){let t={...H7s(e),_getRawProperties:()=>tPn(e)._getRawProperties(),_getParsedProperties:()=>tPn(e)._getParsedProperties()};return{...t,...CA(t),...U8t(t),...Xxi(t)}}function DSo(e){let t={parse:(r,i)=>sTp(r,(n,a)=>e.parse(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,i)=>sTp(r,(n,a)=>e.json(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>FP.LIST};return{...e5(t),...CA(t)}}function sTp(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:yM(e,"list"),path:[]}]}}function cTp(e){return H$(FP.STRING_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:yM(r,`"${e}"`)}]})()}function lTp(e){return H$(FP.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:yM(r,`${e.toString()}`)}]})()}var fTp=H$(FP.ANY,e=>({ok:!0,value:e}));var dTp=H$(FP.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:yM(e,"boolean")}]});var pTp=H$(FP.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:yM(e,"number")}]});var _Tp=H$(FP.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:yM(e,"string")}]});var hTp=H$(FP.UNKNOWN,e=>({ok:!0,value:e}));function vTp(e,t){let r={parse:(i,n)=>yTp({value:i,isKeyNumeric:e.getType()===FP.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)=>yTp({value:i,isKeyNumeric:e.getType()===FP.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:()=>FP.RECORD};return{...e5(r),...CA(r)}}function yTp({value:e,isKeyNumeric:t,transformKey:r,transformValue:i,breadcrumbsPrefix:n=[]}){return rli(e)?jla(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:yM(e,"object")}]}}function bTp(e){let t=DSo(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:yM(i,"Set")}]},getType:()=>FP.SET};return{...e5(r),...CA(r)}}function OTp(e){let t={parse:(r,i)=>gTp((n,a)=>n.parse(r,a),e,i),json:(r,i)=>gTp((n,a)=>n.json(r,a),e,i),getType:()=>FP.UNDISCRIMINATED_UNION};return{...e5(t),...CA(t)}}function gTp(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 mTp(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function jTp(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,i=typeof e=="string"?e:e.parsedDiscriminant,n=wSo(Sla(t)),a={parse:(u,l)=>PTp({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)=>PTp({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:()=>FP.UNION};return{...e5(a),...CA(a),...U8t(a)}}function PTp({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:i,getAdditionalPropertiesSchema:n,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:u,breadcrumbsPrefix:l=[]}){if(!rli(e))return{ok:!1,errors:[{path:l,message:yM(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 SO=At.objectWithoutOptionalProperties({title:At.string().optional()});var ESo=At.objectWithoutOptionalProperties({file:At.string()});var MSo=At.objectWithoutOptionalProperties({file:At.string()});var ASo=At.union("type",{openapi:ESo,protobuf:MSo}).transform({transform:e=>{switch(e.type){case"openapi":return Kre.openapi(e);case"protobuf":return Kre.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var ny=At.objectWithoutOptionalProperties({source:ASo.optional()});var qSo=At.objectWithoutOptionalProperties({typeName:At.string()});var TSo=At.union("type",{protobuf:qSo}).transform({transform:e=>{switch(e.type){case"protobuf":return Xmn.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var Xre=At.objectWithoutOptionalProperties({encoding:TSo.optional()});var Of=At.objectWithoutOptionalProperties({description:At.string().optional()});var CSo=At.enum_(["GenerallyAvailable","Beta","Deprecated"]);var uh=At.objectWithoutOptionalProperties({availability:CSo.optional()});var sYt=At.number();var cYt=At.objectWithoutOptionalProperties({statusCode:sYt.optional()});var Xb=At.objectWithoutOptionalProperties({nameOverride:At.string().optional(),generatedName:At.string()});var XD=At.objectWithoutOptionalProperties({inline:At.boolean().optional()});var jY=At.string();var wY=At.string();var BSo=At.objectWithoutOptionalProperties({id:wY}).extend(Of);var xSo=At.string();var ISo=At.objectWithoutOptionalProperties({usernameVariableName:At.string().optional(),usernameEnvVar:At.string().optional(),passwordVariableName:At.string().optional(),passwordEnvVar:At.string().optional()});var zSo=At.objectWithoutOptionalProperties({tokenVariableName:At.string().optional(),tokenEnvVar:At.string().optional()});var RSo=At.objectWithoutOptionalProperties({headerName:At.string(),prefix:At.string().optional(),headerVariableName:At.string().optional(),headerEnvVar:At.string().optional()});var NSo=At.objectWithoutOptionalProperties({queryParameterName:At.string()});var FSo=At.objectWithoutOptionalProperties({snake:At.string().optional(),camel:At.string().optional(),screamingSnake:At.string().optional(),pascal:At.string().optional()});var nli=At.objectWithoutOptionalProperties({nameOverride:At.string().optional(),generatedName:At.string(),value:At.string(),casing:FSo.optional()}).extend(Of).extend(uh);var LSo=At.objectWithoutOptionalProperties({type:At.stringLiteral("namespace"),name:At.string()});var USo=At.undiscriminatedUnion([At.string(),LSo]);var ali=At.list(USo);var DO=At.objectWithoutOptionalProperties({groupName:ali.optional()});var rPn=At.objectWithoutOptionalProperties({default:nli.optional(),values:At.list(nli)}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(ny).extend(SO).extend(XD);var VSo=At.objectWithoutOptionalProperties({scopesEnum:rPn.optional()});var WSo=At.union("type",{basic:ISo,bearer:zSo,header:RSo,query:NSo,oauth:VSo}).transform({transform:e=>{switch(e.type){case"basic":return k8.basic(e);case"bearer":return k8.bearer(e);case"header":return k8.header(e);case"query":return k8.query(e);case"oauth":return k8.oauth(e);default:return e}},untransform:({_visit:e,...t})=>t});var Dla=At.objectWithoutOptionalProperties({name:At.string().optional(),url:At.string(),audiences:At.list(At.string()).optional()}).extend(Of);var HSo=At.string();var lYt=At.objectWithoutOptionalProperties({namespace:At.string().optional()});var Q7s={};Io(Q7s,{FullExample:()=>BA,FullObjectExample:()=>GSo,FullOneOfExample:()=>JSo,KeyValuePair:()=>QSo,LiteralExample:()=>$So,PrimitiveExample:()=>nPn,PropertyKey:()=>iPn});var iPn=At.string();var nPn=At.union("type",{int:At.object({value:At.number()}),int64:At.object({value:At.number()}),uint:At.object({value:At.number()}),uint64:At.object({value:At.number()}),float:At.object({value:At.number()}),double:At.object({value:At.number()}),string:At.object({value:At.string()}),datetime:At.object({value:At.string()}),date:At.object({value:At.string()}),base64:At.object({value:At.string()}),boolean:At.object({value:At.boolean()})}).transform({transform:e=>{switch(e.type){case"int":return i_.int(e.value);case"int64":return i_.int64(e.value);case"uint":return i_.uint(e.value);case"uint64":return i_.uint64(e.value);case"float":return i_.float(e.value);case"double":return i_.double(e.value);case"string":return i_.string(e.value);case"datetime":return i_.datetime(e.value);case"date":return i_.date(e.value);case"base64":return i_.base64(e.value);case"boolean":return i_.boolean(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var $So=At.union("type",{boolean:At.object({value:At.boolean()}),string:At.object({value:At.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return Zmn.boolean(e.value);case"string":return Zmn.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var BA=At.union("type",{primitive:At.object({value:nPn}),object:At.lazyObject(()=>GSo),array:At.object({value:At.list(At.lazy(()=>BA))}),map:At.object({value:At.list(At.lazyObject(()=>QSo))}),enum:At.object({value:At.string()}),literal:At.object({value:$So}),oneOf:At.object({value:At.lazy(()=>JSo)}),unknown:At.object({value:At.lazy(()=>BA)})}).transform({transform:e=>{switch(e.type){case"primitive":return Q0.primitive(e.value);case"object":return Q0.object(e);case"array":return Q0.array(e.value);case"map":return Q0.map(e.value);case"enum":return Q0.enum(e.value);case"literal":return Q0.literal(e.value);case"oneOf":return Q0.oneOf(e.value);case"unknown":return Q0.unknown(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var GSo=At.objectWithoutOptionalProperties({properties:At.record(iPn,At.lazy(()=>BA))});var QSo=At.objectWithoutOptionalProperties({key:nPn,value:At.lazy(()=>BA)});var JSo=At.union("type",{discriminated:At.object({value:At.record(iPn,At.lazy(()=>BA))}),undiscriminated:At.object({value:At.lazy(()=>BA)})}).transform({transform:e=>{switch(e.type){case"discriminated":return eli.discriminated(e.value);case"undiscriminated":return eli.undiscriminated(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var J7s={};Io(J7s,{AllOfPropertyConflict:()=>OPn,ArraySchema:()=>zDo,Availability:()=>CSo,BooleanSchema:()=>qDo,CasingOverrides:()=>FSo,CommonProperty:()=>HDo,CursorPagination:()=>hDo,CustomCodeSample:()=>pDo,CustomCodeSampleLanguage:()=>lDo,CustomCodeSampleSdk:()=>dDo,CustomPagination:()=>vDo,DiscriminatedOneOfSchema:()=>VDo,DoubleSchema:()=>MDo,Endpoint:()=>bDo,EndpointExample:()=>hPn,EndpointResponseExample:()=>cDo,EndpointSdkName:()=>fYt,EnumSchema:()=>rPn,EnumValue:()=>nli,ErrorExample:()=>nDo,FernExample:()=>oDo,FileResponse:()=>lPn,FileSchema:()=>XSo,FullEndpointExample:()=>_Do,GlobalHeader:()=>CDo,Header:()=>oli,HeaderExample:()=>_Pn,HttpEndpointServer:()=>dPn,HttpError:()=>aDo,HttpMethod:()=>aPn,IdempotencyHeader:()=>BDo,IntSchema:()=>DDo,JsonRequest:()=>tDo,JsonResponse:()=>fPn,LiteralSchema:()=>gPn,LiteralSchemaValue:()=>xDo,LongSchema:()=>EDo,MapSchema:()=>RDo,MultipartRequest:()=>cPn,MultipartRequestProperty:()=>eDo,MultipartRequestPropertyEncoding:()=>kSo,MultipartSchema:()=>ZSo,NullableSchema:()=>FDo,ObjectProperty:()=>UDo,ObjectPropertyConflictInfo:()=>mPn,ObjectSchema:()=>IDo,OctetStreamRequest:()=>sPn,OffsetPagination:()=>yDo,OneOfSchema:()=>LDo,OpenApiIntermediateRepresentation:()=>wTp,OptionalSchema:()=>NDo,Pagination:()=>yPn,PathParameter:()=>oPn,PathParameterExample:()=>uDo,PrimitiveSchema:()=>sli,PrimitiveSchemaValue:()=>TDo,QueryParameter:()=>uPn,QueryParameterExample:()=>pPn,ReferencedSchema:()=>dYt,Request:()=>rDo,Response:()=>iDo,Schema:()=>EO,Schemas:()=>SDo,SdkGroupInfo:()=>KSo,StreamingResponseExample:()=>sDo,StringSchema:()=>ADo,SupportedSdkLanguage:()=>fDo,Tags:()=>YSo,TextResponse:()=>uli,UnDiscriminatedOneOfSchema:()=>WDo,Webhook:()=>gDo,WebhookExampleCall:()=>bPn,WebhookHttpMethod:()=>vPn,WebsocketChannel:()=>wDo,WebsocketHandshake:()=>ODo,WebsocketMessageExample:()=>PDo,WebsocketServer:()=>mDo,WebsocketSessionExample:()=>jDo});var KSo=At.objectWithoutOptionalProperties({summary:At.string().optional(),description:At.string().optional()});var YSo=At.objectWithoutOptionalProperties({tagsById:At.record(wY,BSo),orderedTagIds:At.list(wY).optional()});var aPn=At.enum_(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS","TRACE"]);var oPn=At.objectWithoutOptionalProperties({name:At.string(),schema:At.lazy(()=>EO),variableReference:At.string().optional(),parameterNameOverride:At.string().optional()}).extend(Of).extend(uh).extend(ny);var uPn=At.objectWithoutOptionalProperties({name:At.string(),schema:At.lazy(()=>EO),parameterNameOverride:At.string().optional()}).extend(Of).extend(uh).extend(ny);var oli=At.objectWithoutOptionalProperties({name:At.string(),schema:At.lazy(()=>EO),env:At.string().optional(),parameterNameOverride:At.string().optional()}).extend(Of).extend(uh).extend(ny);var fYt=At.objectWithoutOptionalProperties({groupName:ali,methodName:At.string()});var sPn=At.objectWithoutOptionalProperties({}).extend(Of).extend(ny);var XSo=At.objectWithoutOptionalProperties({isOptional:At.boolean(),isArray:At.boolean()});var ZSo=At.union("type",{file:XSo,json:At.object({value:At.lazy(()=>EO)})}).transform({transform:e=>{switch(e.type){case"file":return CIe.file(e);case"json":return CIe.json(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var kSo=At.enum_(["json","form"]);var eDo=At.objectWithoutOptionalProperties({key:At.string(),schema:ZSo,contentType:At.string().optional(),exploded:At.boolean().optional(),encoding:kSo.optional()}).extend(Of);var cPn=At.objectWithoutOptionalProperties({name:At.string().optional(),properties:At.list(eDo)}).extend(Of).extend(ny);var tDo=At.objectWithoutOptionalProperties({schema:At.lazy(()=>EO),contentType:At.string().optional(),additionalProperties:At.boolean()}).extend(Of).extend(ny);var rDo=At.union("type",{octetStream:sPn,multipart:cPn,json:tDo}).transform({transform:e=>{switch(e.type){case"octetStream":return tli.octetStream(e);case"multipart":return tli.multipart(e);case"json":return tli.json(e);default:return e}},untransform:({_visit:e,...t})=>t});var lPn=At.objectWithoutOptionalProperties({}).extend(Of).extend(ny).extend(cYt);var fPn=At.objectWithoutOptionalProperties({schema:At.lazy(()=>EO),responseProperty:At.string().optional()}).extend(Of).extend(ny).extend(cYt);var uli=At.objectWithoutOptionalProperties({}).extend(Of).extend(ny).extend(cYt);var iDo=At.union("type",{file:lPn,json:fPn,text:uli,streamingSse:fPn,streamingText:uli,streamingJson:fPn}).transform({transform:e=>{switch(e.type){case"file":return Yre.file(e);case"json":return Yre.json(e);case"text":return Yre.text(e);case"streamingSse":return Yre.streamingSse(e);case"streamingText":return Yre.streamingText(e);case"streamingJson":return Yre.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var nDo=At.objectWithoutOptionalProperties({name:At.string().optional(),description:At.string().optional(),example:At.lazy(()=>BA)});var aDo=At.objectWithoutOptionalProperties({schema:At.lazy(()=>EO).optional(),examples:At.list(nDo).optional()}).extend(Of).extend(Xb).extend(ny);var dPn=At.objectWithoutOptionalProperties({name:At.string().optional(),url:At.string().optional(),audiences:At.list(At.string()).optional()});var oDo=At.unknown();var uDo=At.objectWithoutOptionalProperties({name:At.string(),parameterNameOverride:At.string().optional(),value:At.lazy(()=>BA)});var pPn=At.objectWithoutOptionalProperties({name:At.string(),value:At.lazy(()=>BA)});var _Pn=At.objectWithoutOptionalProperties({name:At.string(),value:At.lazy(()=>BA)});var sDo=At.objectWithoutOptionalProperties({sse:At.boolean(),events:At.list(At.lazy(()=>BA))});var cDo=At.union("type",{withStreaming:sDo,withoutStreaming:At.object({value:At.lazy(()=>BA)})}).transform({transform:e=>{switch(e.type){case"withStreaming":return TIe.withStreaming(e);case"withoutStreaming":return TIe.withoutStreaming(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var lDo=At.objectWithoutOptionalProperties({name:At.string().optional(),language:At.string(),code:At.string(),install:At.string().optional()}).extend(Of);var fDo=At.enum_(["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm"]);var dDo=At.objectWithoutOptionalProperties({name:At.string().optional(),sdk:fDo,code:At.string()}).extend(Of);var pDo=At.union("type",{language:lDo,sdk:dDo}).transform({transform:e=>{switch(e.type){case"language":return GGr.language(e);case"sdk":return GGr.sdk(e);default:return e}},untransform:({_visit:e,...t})=>t});var _Do=At.objectWithoutOptionalProperties({name:At.string().optional(),pathParameters:At.list(uDo).optional(),queryParameters:At.list(pPn).optional(),headers:At.list(_Pn).optional(),request:At.lazy(()=>BA).optional(),response:cDo.optional(),codeSamples:At.list(pDo)}).extend(Of);var hPn=At.union("type",{unknown:At.object({value:oDo}),full:_Do}).transform({transform:e=>{switch(e.type){case"unknown":return L8t.unknown(e.value);case"full":return L8t.full(e);default:return e}},untransform:({_visit:e,...t})=>t});var hDo=At.objectWithoutOptionalProperties({cursor:At.string(),nextCursor:At.property("next_cursor",At.string()),results:At.string()});var yDo=At.objectWithoutOptionalProperties({offset:At.string(),results:At.string(),step:At.string().optional(),hasNextPage:At.string().optional()});var vDo=At.objectWithoutOptionalProperties({results:At.string()});var yPn=At.union("type",{cursor:hDo,offset:yDo,custom:vDo}).transform({transform:e=>{switch(e.type){case"cursor":return qIe.cursor(e);case"offset":return qIe.offset(e);case"custom":return qIe.custom(e);default:return e}},untransform:({_visit:e,...t})=>t});var bDo=At.objectWithoutOptionalProperties({authed:At.boolean(),internal:At.boolean().optional(),idempotent:At.boolean().optional(),method:aPn,audiences:At.list(At.string()),path:At.string(),summary:At.string().optional(),operationId:At.string().optional(),tags:At.list(wY),pathParameters:At.list(oPn),queryParameters:At.list(uPn),headers:At.list(oli),sdkName:fYt.optional(),generatedRequestName:At.string(),requestNameOverride:At.string().optional(),request:rDo.optional(),response:iDo.optional(),errors:At.record(sYt,aDo),servers:At.list(dPn),examples:At.list(hPn),pagination:yPn.optional()}).extend(Of).extend(uh).extend(ny).extend(lYt);var vPn=At.enum_(["GET","POST"]);var bPn=At.objectWithoutOptionalProperties({name:At.string().optional(),payload:At.lazy(()=>BA)}).extend(Of);var gDo=At.objectWithoutOptionalProperties({sdkName:fYt.optional(),method:vPn,summary:At.string().optional(),operationId:At.string(),tags:At.list(wY),headers:At.list(oli),generatedPayloadName:At.string(),payload:At.lazy(()=>EO),examples:At.list(bPn)}).extend(Of).extend(ny).extend(lYt);var ODo=At.objectWithoutOptionalProperties({queryParameters:At.list(uPn),headers:At.list(oli),pathParameters:At.list(oPn)});var mDo=At.objectWithoutOptionalProperties({name:At.string(),url:At.string()});var PDo=At.objectWithoutOptionalProperties({messageType:At.string(),payload:At.lazy(()=>BA)}).extend(Of);var jDo=At.objectWithoutOptionalProperties({name:At.string().optional(),queryParameters:At.list(pPn).optional(),headers:At.list(_Pn).optional(),messages:At.list(PDo)}).extend(Of);var wDo=At.objectWithoutOptionalProperties({audiences:At.list(At.string()),path:At.string(),groupName:ali,summary:At.string().optional(),handshake:ODo,publish:At.lazy(()=>EO).optional(),subscribe:At.lazy(()=>EO).optional(),servers:At.list(mDo),examples:At.list(jDo)}).extend(Of).extend(ny);var SDo=At.objectWithoutOptionalProperties({rootSchemas:At.record(jY,At.lazy(()=>EO)),namespacedSchemas:At.record(HSo,At.record(jY,At.lazy(()=>EO)))});var DDo=At.objectWithoutOptionalProperties({default:At.number().optional(),minimum:At.number().optional(),maximum:At.number().optional(),exclusiveMinimum:At.boolean().optional(),exclusiveMaximum:At.boolean().optional(),multipleOf:At.number().optional()});var EDo=At.objectWithoutOptionalProperties({default:At.number().optional()});var MDo=At.objectWithoutOptionalProperties({default:At.number().optional(),minimum:At.number().optional(),maximum:At.number().optional(),exclusiveMinimum:At.boolean().optional(),exclusiveMaximum:At.boolean().optional(),multipleOf:At.number().optional()});var ADo=At.objectWithoutOptionalProperties({default:At.string().optional(),pattern:At.string().optional(),format:At.string().optional(),minLength:At.number().optional(),maxLength:At.number().optional()});var qDo=At.objectWithoutOptionalProperties({default:At.boolean().optional()});var TDo=At.union("type",{int:DDo,int64:EDo,uint:At.object({}),uint64:At.object({}),float:At.object({}),double:MDo,string:ADo,datetime:At.object({}),date:At.object({}),base64:At.object({}),boolean:qDo}).transform({transform:e=>{switch(e.type){case"int":return sj.int(e);case"int64":return sj.int64(e);case"uint":return sj.uint();case"uint64":return sj.uint64();case"float":return sj.float();case"double":return sj.double(e);case"string":return sj.string(e);case"datetime":return sj.datetime();case"date":return sj.date();case"base64":return sj.base64();case"boolean":return sj.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var sli=At.objectWithoutOptionalProperties({schema:TDo}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(SO);var CDo=At.objectWithoutOptionalProperties({header:At.string(),name:At.string().optional(),optional:At.boolean().optional(),env:At.string().optional(),schema:At.lazy(()=>EO).optional()});var BDo=At.objectWithoutOptionalProperties({header:At.string(),name:At.string().optional(),env:At.string().optional(),schema:At.lazy(()=>EO).optional()});var wTp=At.objectWithoutOptionalProperties({apiVersion:At.unknown().optional(),title:At.string().optional(),description:At.string().optional(),basePath:At.string().optional(),servers:At.list(Dla),websocketServers:At.list(Dla),groups:At.record(At.string(),KSo),tags:YSo,hasEndpointsMarkedInternal:At.boolean(),endpoints:At.list(bDo),webhooks:At.list(gDo),channels:At.record(At.string(),wDo),groupedSchemas:SDo,variables:At.record(At.string(),sli),nonRequestReferencedSchemas:At.set(jY),securitySchemes:At.record(xSo,WSo),globalHeaders:At.list(CDo).optional(),idempotencyHeaders:At.list(BDo).optional()});var dYt=At.objectWithoutOptionalProperties({schema:jY}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(ny).extend(SO);var xDo=At.union("type",{boolean:At.object({value:At.boolean()}),string:At.object({value:At.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return YB.boolean(e.value);case"string":return YB.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var gPn=At.objectWithoutOptionalProperties({value:xDo}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(SO);var EO=At.union("type",{primitive:sli,object:At.lazyObject(()=>IDo),array:At.lazyObject(()=>zDo),map:At.lazyObject(()=>RDo),optional:At.lazyObject(()=>NDo),enum:rPn,reference:dYt,literal:gPn,oneOf:At.object({value:At.lazy(()=>LDo)}),nullable:At.lazyObject(()=>FDo),unknown:Xb}).transform({transform:e=>{switch(e.type){case"primitive":return py.primitive(e);case"object":return py.object(e);case"array":return py.array(e);case"map":return py.map(e);case"optional":return py.optional(e);case"enum":return py.enum(e);case"reference":return py.reference(e);case"literal":return py.literal(e);case"oneOf":return py.oneOf(e.value);case"nullable":return py.nullable(e);case"unknown":return py.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var OPn=At.objectWithoutOptionalProperties({propertyKey:At.string(),allOfSchemaIds:At.list(jY),conflictingTypeSignatures:At.boolean()});var IDo=At.objectWithoutOptionalProperties({allOf:At.list(dYt),properties:At.list(At.lazyObject(()=>UDo)),allOfPropertyConflicts:At.list(OPn),additionalProperties:At.boolean()}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(ny).extend(SO).extend(XD);var mPn=At.objectWithoutOptionalProperties({differentSchema:At.boolean()});var UDo=At.objectWithoutOptionalProperties({key:At.string(),schema:At.lazy(()=>EO),readonly:At.boolean().optional(),writeonly:At.boolean().optional(),conflict:At.record(jY,mPn),generatedName:At.string(),nameOverride:At.string().optional(),audiences:At.list(At.string())}).extend(uh);var zDo=At.objectWithoutOptionalProperties({value:At.lazy(()=>EO)}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(SO).extend(XD);var RDo=At.objectWithoutOptionalProperties({key:sli,value:At.lazy(()=>EO)}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(Xre).extend(SO).extend(XD);var NDo=At.objectWithoutOptionalProperties({value:At.lazy(()=>EO)}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(SO).extend(XD);var FDo=At.objectWithoutOptionalProperties({value:At.lazy(()=>EO)}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(SO).extend(XD);var LDo=At.union("type",{discriminated:At.lazyObject(()=>VDo),undiscriminated:At.lazyObject(()=>WDo)}).transform({transform:e=>{switch(e.type){case"discriminated":return QGr.discriminated(e);case"undiscriminated":return QGr.undiscriminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var VDo=At.objectWithoutOptionalProperties({discriminantProperty:At.string(),commonProperties:At.list(At.lazyObject(()=>HDo)),schemas:At.record(At.string(),At.lazy(()=>EO))}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(Xre).extend(ny).extend(SO).extend(XD);var HDo=At.objectWithoutOptionalProperties({key:At.string(),schema:At.lazy(()=>EO)});var WDo=At.objectWithoutOptionalProperties({schemas:At.list(At.lazy(()=>EO))}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(Xre).extend(ny).extend(SO).extend(XD);var K7s={};Io(K7s,{ArraySchemaWithExample:()=>lEo,Base64WithExample:()=>aEo,BooleanWithExample:()=>oEo,CommonPropertyWithExample:()=>gEo,DateWithExample:()=>nEo,DatetimeWithExample:()=>iEo,DiscriminatedOneOfSchemaWithExample:()=>vEo,DoubleWithExample:()=>tEo,EndpointWithExample:()=>DTp,EnumSchemaWithExample:()=>sEo,FloatWithExample:()=>eEo,HeaderWithExample:()=>cli,HttpErrorWithExample:()=>KDo,Int64WithExample:()=>XDo,IntWithExample:()=>YDo,JsonRequestWithExample:()=>GDo,JsonResponseWithExample:()=>jPn,MapSchemaWithExample:()=>fEo,NamedFullExample:()=>pYt,NullableSchemaWithExample:()=>pEo,ObjectPropertyWithExample:()=>yEo,ObjectSchemaWithExample:()=>_Eo,OneOfSchemaWithExample:()=>hEo,OptionalSchemaWithExample:()=>dEo,PathParameterWithExample:()=>$Do,PrimitiveSchemaValueWithExample:()=>uEo,PrimitiveSchemaWithExample:()=>wPn,QueryParameterWithExample:()=>PPn,RequestWithExample:()=>QDo,ResponseWithExample:()=>JDo,SchemaWithExample:()=>vM,StringSchemaWithExample:()=>rEo,Uint64WithExample:()=>kDo,UintWithExample:()=>ZDo,UnDiscriminatedOneOfSchemaWithExample:()=>bEo,UnknownSchemaWithExample:()=>cEo,WebhookWithExample:()=>ETp,WebsocketHandshakeWithExample:()=>STp});var pYt=At.objectWithoutOptionalProperties({name:At.string().optional(),value:At.unknown()}).extend(Of);var PPn=At.objectWithoutOptionalProperties({name:At.string(),schema:At.lazy(()=>vM),parameterNameOverride:At.string().optional()}).extend(Of).extend(uh).extend(ny);var cli=At.objectWithoutOptionalProperties({name:At.string(),schema:At.lazy(()=>vM),env:At.string().optional(),parameterNameOverride:At.string().optional()}).extend(Of).extend(uh).extend(ny);var STp=At.objectWithoutOptionalProperties({queryParameters:At.list(PPn),headers:At.list(cli)});var $Do=At.objectWithoutOptionalProperties({name:At.string(),schema:At.lazy(()=>vM),variableReference:At.string().optional(),parameterNameOverride:At.string().optional()}).extend(Of).extend(uh).extend(ny);var GDo=At.objectWithoutOptionalProperties({schema:At.lazy(()=>vM),contentType:At.string().optional(),fullExamples:At.list(pYt).optional(),additionalProperties:At.boolean()}).extend(Of).extend(ny);var QDo=At.union("type",{octetStream:sPn,multipart:cPn,json:GDo}).transform({transform:e=>{switch(e.type){case"octetStream":return lSe.octetStream(e);case"multipart":return lSe.multipart(e);case"json":return lSe.json(e);default:return e}},untransform:({_visit:e,...t})=>t});var jPn=At.objectWithoutOptionalProperties({schema:At.lazy(()=>vM),responseProperty:At.string().optional(),fullExamples:At.list(pYt).optional()}).extend(Of).extend(ny).extend(cYt);var JDo=At.union("type",{file:lPn,json:jPn,text:uli,streamingSse:jPn,streamingText:uli,streamingJson:jPn}).transform({transform:e=>{switch(e.type){case"file":return XB.file(e);case"json":return XB.json(e);case"text":return XB.text(e);case"streamingSse":return XB.streamingSse(e);case"streamingText":return XB.streamingText(e);case"streamingJson":return XB.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var KDo=At.objectWithoutOptionalProperties({statusCode:sYt,schema:At.lazy(()=>vM),fullExamples:At.list(pYt).optional()}).extend(Of).extend(Xb).extend(ny);var DTp=At.objectWithoutOptionalProperties({authed:At.boolean(),internal:At.boolean().optional(),idempotent:At.boolean().optional(),method:aPn,audiences:At.list(At.string()),path:At.string(),summary:At.string().optional(),operationId:At.string().optional(),tags:At.list(wY),pathParameters:At.list($Do),queryParameters:At.list(PPn),headers:At.list(cli),sdkName:fYt.optional(),generatedRequestName:At.string(),requestNameOverride:At.string().optional(),request:QDo.optional(),response:JDo.optional(),errors:At.record(sYt,KDo),servers:At.list(dPn),examples:At.list(hPn),pagination:yPn.optional()}).extend(Of).extend(uh).extend(ny).extend(lYt);var ETp=At.objectWithoutOptionalProperties({sdkName:fYt.optional(),method:vPn,summary:At.string().optional(),operationId:At.string(),tags:At.list(wY),headers:At.list(cli),generatedPayloadName:At.string(),payload:At.lazy(()=>vM),examples:At.list(bPn)}).extend(Of).extend(ny).extend(lYt);var YDo=At.objectWithoutOptionalProperties({default:At.number().optional(),minimum:At.number().optional(),maximum:At.number().optional(),exclusiveMinimum:At.boolean().optional(),exclusiveMaximum:At.boolean().optional(),multipleOf:At.number().optional(),example:At.number().optional()});var XDo=At.objectWithoutOptionalProperties({default:At.number().optional(),example:At.number().optional()});var ZDo=At.objectWithoutOptionalProperties({default:At.number().optional(),example:At.number().optional()});var kDo=At.objectWithoutOptionalProperties({default:At.number().optional(),example:At.number().optional()});var eEo=At.objectWithoutOptionalProperties({example:At.number().optional()});var tEo=At.objectWithoutOptionalProperties({default:At.number().optional(),minimum:At.number().optional(),maximum:At.number().optional(),exclusiveMinimum:At.boolean().optional(),exclusiveMaximum:At.boolean().optional(),multipleOf:At.number().optional(),example:At.number().optional()});var rEo=At.objectWithoutOptionalProperties({default:At.string().optional(),pattern:At.string().optional(),format:At.string().optional(),minLength:At.number().optional(),maxLength:At.number().optional(),example:At.string().optional()});var iEo=At.objectWithoutOptionalProperties({example:At.string().optional()});var nEo=At.objectWithoutOptionalProperties({example:At.string().optional()});var aEo=At.objectWithoutOptionalProperties({example:At.string().optional()});var oEo=At.objectWithoutOptionalProperties({default:At.boolean().optional(),example:At.boolean().optional()});var uEo=At.union("type",{int:YDo,int64:XDo,uint:ZDo,uint64:kDo,float:eEo,double:tEo,string:rEo,datetime:iEo,date:nEo,base64:aEo,boolean:oEo}).transform({transform:e=>{switch(e.type){case"int":return Jd.int(e);case"int64":return Jd.int64(e);case"uint":return Jd.uint(e);case"uint64":return Jd.uint64(e);case"float":return Jd.float(e);case"double":return Jd.double(e);case"string":return Jd.string(e);case"datetime":return Jd.datetime(e);case"date":return Jd.date(e);case"base64":return Jd.base64(e);case"boolean":return Jd.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var wPn=At.objectWithoutOptionalProperties({schema:uEo}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(SO);var sEo=At.objectWithoutOptionalProperties({default:nli.optional(),values:At.list(nli),example:At.string().optional()}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(ny).extend(SO).extend(XD);var cEo=At.objectWithoutOptionalProperties({example:At.unknown()}).extend(DO).extend(Xb).extend(Of).extend(uh).extend(SO);var vM=At.union("type",{primitive:wPn,object:At.lazyObject(()=>_Eo),array:At.lazyObject(()=>lEo),map:At.lazyObject(()=>fEo),optional:At.lazyObject(()=>dEo),enum:sEo,reference:dYt,literal:gPn,oneOf:At.object({value:At.lazy(()=>hEo)}),nullable:At.lazyObject(()=>pEo),unknown:cEo}).transform({transform:e=>{switch(e.type){case"primitive":return El.primitive(e);case"object":return El.object(e);case"array":return El.array(e);case"map":return El.map(e);case"optional":return El.optional(e);case"enum":return El.enum(e);case"reference":return El.reference(e);case"literal":return El.literal(e);case"oneOf":return El.oneOf(e.value);case"nullable":return El.nullable(e);case"unknown":return El.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var lEo=At.objectWithoutOptionalProperties({value:At.lazy(()=>vM),example:At.list(At.unknown()).optional()}).extend(DO).extend(Xb).extend(Of).extend(uh).extend(SO).extend(XD);var fEo=At.objectWithoutOptionalProperties({key:wPn,value:At.lazy(()=>vM),example:At.unknown().optional()}).extend(DO).extend(Xb).extend(Of).extend(uh).extend(Xre).extend(SO).extend(XD);var dEo=At.objectWithoutOptionalProperties({value:At.lazy(()=>vM)}).extend(DO).extend(Xb).extend(Of).extend(uh).extend(SO).extend(XD);var pEo=At.objectWithoutOptionalProperties({value:At.lazy(()=>vM)}).extend(DO).extend(Xb).extend(Of).extend(uh).extend(SO).extend(XD);var _Eo=At.objectWithoutOptionalProperties({allOf:At.list(dYt),properties:At.list(At.lazyObject(()=>yEo)),allOfPropertyConflicts:At.list(OPn),fullExamples:At.list(pYt).optional(),additionalProperties:At.boolean()}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(ny).extend(SO).extend(XD);var yEo=At.objectWithoutOptionalProperties({key:At.string(),schema:At.lazy(()=>vM),readonly:At.boolean().optional(),writeonly:At.boolean().optional(),audiences:At.list(At.string()),conflict:At.record(jY,mPn),nameOverride:At.string().optional(),generatedName:At.string()}).extend(uh);var hEo=At.union("type",{discriminated:At.lazyObject(()=>vEo),undiscriminated:At.lazyObject(()=>bEo)}).transform({transform:e=>{switch(e.type){case"discriminated":return PY.discriminated(e);case"undiscriminated":return PY.undiscriminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var vEo=At.objectWithoutOptionalProperties({discriminantProperty:At.string(),commonProperties:At.list(At.lazyObject(()=>gEo)),schemas:At.record(At.string(),At.lazy(()=>vM))}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(Xre).extend(ny).extend(SO).extend(XD);var gEo=At.objectWithoutOptionalProperties({key:At.string(),schema:At.lazy(()=>vM)});var bEo=At.objectWithoutOptionalProperties({schemas:At.list(At.lazy(()=>vM))}).extend(Of).extend(Xb).extend(DO).extend(uh).extend(Xre).extend(ny).extend(SO).extend(XD);var MTp=/^(\d+)/,SPn=/^[a-zA-Z][a-zA-Z0-9_]*$/,ATp={"<":"LESS_THAN",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL_TO","<=":"LESS_THAN_OR_EQUAL_TO","!=":"NOT_EQUALS","=":"EQUAL_TO","==":"EQUAL_TO","*":"ALL","":"EMPTY",'""':"EMPTY_STRING","-":"HYPHEN","|":"PIPE",".":"DOT","/":"SLASH"};function lli(e){let t=["zero","one","two","three","four","five","six","seven","eight","nine"],r=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],i=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"];if(e<0||e>9999)return;if(e<10)return t[e];if(e<20)return r[e-10];if(e<100){let u=Math.floor(e/10),l=e%10;return l===0?i[u]:`${i[u]}_${t[l]}`}if(e<1e3){let u=Math.floor(e/100),l=e%100;return l===0?`${t[u]}_hundred`:`${t[u]}_hundred_${lli(l)}`}let n=Math.floor(e/1e3),a=e%1e3;return a===0?`${t[n]}_thousand`:`${t[n]}_thousand_${lli(a)}`}function Ela(e){let t=e.match(MTp);if(t&&t[0]!=null){let r=t[0],i=e.substring(r.length),n=parseFloat(r);if(!isNaN(n)&&isFinite(n)){let a=lli(n);return i.length>0?`${a}_${i}`:a}}}function DPn(e){let t=Ela(e),r=ATp[e];return t!=null?q3(vg(t)):r??(e.toLowerCase()==="n/a"?"NOT_APPLICABLE":q3(vg(e)))}function Zre(e,t){return e.type==="primitive"&&t.type==="primitive"?qTp(e.schema,t.schema):e.type==="enum"&&t.type==="enum"?raD(e.values,t.values):e.type==="array"&&t.type==="array"?Zre(e.value,t.value):e.type==="unknown"&&t.type==="unknown"?!0:e.type==="reference"&&t.type==="reference"?e.schema===t.schema:e.type==="optional"&&t.type==="optional"?Zre(e.value,t.value):e.type==="oneOf"&&t.type==="oneOf"?iaD(e.value,t.value):e.type==="object"&&t.type==="object"?naD(e,t):e.type==="map"&&t.type==="map"?qTp(e.key.schema,t.key.schema)&&Zre(e.value,t.value):e.type==="literal"&&t.type==="literal"?e.value===t.value:!1}function qTp(e,t){return e.type===t.type}function raD(e,t){let r=new Set(...e.map(n=>n.value)),i=new Set(...t.map(n=>n.value));return u1e(r,i)}function iaD(e,t){return e.type==="discriminated"&&t.type==="discriminated"?e.discriminantProperty===t.discriminantProperty&&Object.keys(e.schemas).length===Object.keys(t.schemas).length&&Object.entries(e.schemas).every(([r,i])=>{let n=t.schemas[r];return n==null?!1:Zre(i,n)}):e.type==="undiscriminated"&&t.type==="undiscriminated"?e.schemas.length===t.schemas.length&&e.schemas.every((r,i)=>{let n=t.schemas[i];return n==null?!1:Zre(r,n)}):!1}function naD(e,t){if(Object.keys(e.properties).length!==Object.keys(t.properties).length)return!1;let r=Object.fromEntries(e.properties.map(i=>[i.key,i.schema]));return Object.entries(t.properties).every(([i,n])=>{let a=r[i];return a==null?!1:Zre(a,n.schema)})}var a2;(function(e){e[e.Channel=0]="Channel",e[e.Endpoint=1]="Endpoint",e[e.Request=2]="Request",e[e.Webhook=3]="Webhook"})(a2||(a2={}));var OEo=class{logger;taskContext;ir;builder;environmentOverrides;authOverrides;globalHeaderOverrides;detectGlobalHeaders;objectQueryParameters;respectReadonlySchemas;respectNullableSchemas;onlyIncludeReferencedSchemas;inlinePathParameters;enableUniqueErrorsPerEndpoint;defaultServerName=void 0;unknownSchema=new Set;referencedSchemaIds;endpointMethod;state=new Set;constructor({taskContext:t,ir:r,options:i,environmentOverrides:n,globalHeaderOverrides:a,authOverrides:u}){this.logger=t.logger,this.taskContext=t,this.ir=r,this.environmentOverrides=n,this.authOverrides=u,this.globalHeaderOverrides=a,this.detectGlobalHeaders=i?.detectGlobalHeaders??!0,this.objectQueryParameters=i?.objectQueryParameters??!1,this.respectReadonlySchemas=i?.respectReadonlySchemas??!1,this.respectNullableSchemas=i?.respectNullableSchemas??!1,this.onlyIncludeReferencedSchemas=i?.onlyIncludeReferencedSchemas??!1,this.inlinePathParameters=i?.inlinePathParameters??!1,this.referencedSchemaIds=i?.onlyIncludeReferencedSchemas?new Set:void 0,this.enableUniqueErrorsPerEndpoint=i?.enableUniqueErrorsPerEndpoint??!1,this.builder=new Yxi(this.enableUniqueErrorsPerEndpoint),r.title!=null&&this.builder.setDisplayName({displayName:r.title});let l={};if(!this.enableUniqueErrorsPerEndpoint)for(let d of r.endpoints)for(let[s,o]of Object.entries(d.errors)){let c=parseInt(s),b=l[c];b==null&&o.schema!=null?l[c]=o.schema:b!=null&&o.schema!=null&&Zre(b,o.schema)||this.unknownSchema.add(c)}}getReferencedSchemaIds(){if(this.referencedSchemaIds!=null)return Array.from(this.referencedSchemaIds)}getSchema(t,r){return r==null?this.ir.groupedSchemas.rootSchemas[t]:this.ir.groupedSchemas.namespacedSchemas[r]?.[t]}getDefaultServerName(){return this.defaultServerName}setDefaultServerName(t){this.defaultServerName=t}isErrorUnknownSchema(t){return this.unknownSchema.has(t)}getEndpointMethod(){return this.endpointMethod}setEndpointMethod(t){this.endpointMethod=t}unsetEndpointMethod(){this.endpointMethod=void 0}isInState(t){return this.state.has(t)}setInState(t){this.state.add(t)}unsetInState(t){this.state.delete(t)}shouldMarkSchemaAsReferenced(){return this.onlyIncludeReferencedSchemas&&this.isInAnyState(a2.Channel,a2.Endpoint,a2.Webhook)}markSchemaAsReferenced(t,r){switch(t.type){case"primitive":return;case"object":this.markObjectSchemaAsReferenced(t,r);return;case"array":this.markSchemaAsReferenced(t.value,r);return;case"map":this.markSchemaAsReferenced(t.value,r);return;case"optional":this.markSchemaAsReferenced(t.value,r);return;case"reference":this.markSchemaIdAsReferenced(t.schema,r);return;case"oneOf":this.markOneofSchemaAsReferenced(t.value,r);return;case"nullable":this.markSchemaAsReferenced(t.value,r);return;case"enum":return;case"literal":return;case"unknown":return;default:Ko(t)}}markObjectSchemaAsReferenced(t,r){for(let i of t.allOf)this.markSchemaIdAsReferenced(i.schema,r);for(let i of t.properties)this.markSchemaAsReferenced(i.schema,r)}markOneofSchemaAsReferenced(t,r){switch(t.type){case"discriminated":for(let i of Object.values(t.schemas))this.markSchemaAsReferenced(i,r);return;case"undiscriminated":for(let i of t.schemas)this.markSchemaAsReferenced(i,r);return;default:Ko(t)}}markSchemaIdAsReferenced(t,r){if(this.referencedSchemaIds!=null&&!this.referencedSchemaIds.has(t)){this.referencedSchemaIds.add(t);let i=this.getSchema(t,r);i!=null&&this.markSchemaAsReferenced(i,r)}}isInAnyState(...t){return t.some(r=>this.isInState(r))}};function kx(e){switch(e){case $U.Deprecated:return"deprecated";case $U.Beta:return"pre-release";case $U.GenerallyAvailable:return"generally-available";default:return}}function aaD(e){let t=e.find(i=>typeof i=="object"&&i.type==="namespace"),r=e.filter(i=>typeof i=="string"||i.type!=="namespace");return t?[t,...r]:r}function TTp(e){let t=e?aaD(e):void 0;if(t==null||t.length===0)return TAi;let r=[];for(let[i,n]of t.entries())if(typeof n=="string")r.push(vg(n));else if(typeof n=="object")switch(n.type){case"namespace":{i<t.length-1?r.push(vg(n.name)):r.push(n.name,TAi);break}default:Ko(n.type)}else Ko(n);return r.join("/")}function EPn(e){return ry.of(`${TTp(e)}.yml`)}function Y7s({sdkName:e,namespaceOverride:t}){let r;return e==null||e.groupName.length===0&&t==null?TAi:(t!=null?r=[{type:"namespace",name:t},...e.groupName.filter(i=>typeof i=="string"||i.type!=="namespace")]:r=e.groupName,TTp(r))}function CTp({sdkName:e,namespaceOverride:t}){return ry.of(`${Y7s({sdkName:e,namespaceOverride:t})}.yml`)}function BTp({location:e,namespaceOverride:t}){return t!=null?sR(ry.of(t),e):e}function mEo(e){switch(e.type){case"protobuf":return{proto:{type:e.typeName}};default:Ko(e.type)}}function MPn(e){switch(e.type){case"object":case"enum":case"array":case"map":case"reference":case"literal":case"optional":case"nullable":case"primitive":return e.groupName??void 0;case"oneOf":return e.value.groupName??void 0;case"unknown":return;default:Ko(e)}}function bM(e){return typeof e=="string"?e:e.type}function APn(e){if(typeof e!="string")return e.docs}function Mla(e){if(typeof e!="string")return e.default}function X7s(e){if(typeof e!="string")return e.validation}var oaD=-2147483648,uaD=2147483647,saD=-17976931348623157e292,caD=17976931348623157e292;function I0({schema:e,fileContainingReference:t,declarationFile:r=t,context:i,namespace:n,declarationDepth:a}){switch(i.shouldMarkSchemaAsReferenced()&&i.markSchemaAsReferenced(e,n),e.type){case"primitive":return PEo(e);case"array":return e6s({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"map":return t6s({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"reference":return k7s({schema:e,fileContainingReference:t,context:i,namespace:n});case"unknown":return i6s();case"optional":return jEo({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"nullable":return r6s({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"enum":return baD({schema:e,fileContainingReference:t,context:i,declarationFile:r,declarationDepth:a});case"literal":return e.value,n6s(e);case"object":return gaD({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"oneOf":return OaD({schema:e.value,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});default:Ko(e)}}function PEo(e){switch(e.schema.type){case"string":return daD({description:e.description,schema:e.schema});case"int":return paD({description:e.description,schema:e.schema});case"float":return _aD({description:e.description,schema:e.schema});case"double":return haD({description:e.description,schema:e.schema});case"boolean":return laD({description:e.description,schema:e.schema});case"int64":return faD({description:e.description,schema:e.schema})}let t=e.schema._visit({int:()=>"integer",int64:()=>"long",uint:()=>"uint",uint64:()=>"uint64",float:()=>"double",double:()=>"double",string:()=>"string",datetime:()=>"datetime",date:()=>"date",base64:()=>"base64",boolean:()=>"boolean",_other:()=>"unknown"});return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:kx(e.availability)}:{}}}function laD({description:e,schema:t}){let r="boolean";if(e==null&&t.default==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),i}function faD({description:e,schema:t}){let r="long";if(e==null&&t.default==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),i}function daD({description:e,schema:t}){let r="string",i=yaD(t);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function paD({description:e,schema:t}){let r="integer",i=ITp(t,r);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function _aD({description:e,schema:t}){let r="float";if(e==null)return r;let i={type:r};return e!=null&&(i.docs=e),i}function haD({description:e,schema:t}){let r="double",i=ITp(t,r);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function yaD(e){if(e==null)return;let{format:t,pattern:r,minLength:i,maxLength:n}=e,a=vaD(t);if(!(a==null&&r==null&&i==null&&n==null))return{format:a,pattern:r,minLength:i,maxLength:n}}function vaD(e){switch(e){case"date":case"date-time":case"password":case"byte":case"bytes":case"binary":case"email":case"uuid":case"uri":case"hostname":case"ipv4":case"ipv6":return e;default:return}}function ITp(e,t){if(e==null)return;let{minimum:r,maximum:i,multipleOf:n}=e,{exclusiveMinimum:a,exclusiveMaximum:u}=e;if(r=Z7s(r,t),i=Z7s(i,t),n=Z7s(n,t),!(r==null&&i==null&&a==null&&u==null&&n==null))return{min:r,max:i,exclusiveMin:a,exclusiveMax:u,multipleOf:n}}function Z7s(e,t){if(e===void 0)return;let[r,i]=t==="integer"?[oaD,uaD]:[saD,caD];return e<r||e>i?void 0:e}function k7s({schema:e,fileContainingReference:t,context:r,namespace:i}){let n=r.getSchema(e.schema,i);if(n==null)return"unknown";let a=maD(n)??e.schema,u=MPn(n),l=PaD(n),d=wEo({context:r,fileContainingReference:t,declarationFile:EPn(u),type:a}),s=n.type==="nullable"?`optional<${d}>`:d;return e.description==null&&l==null?s:{type:n.type==="nullable"?`optional<${d}>`:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:kx(e.availability)}:{}}}function e6s({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=I0({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=`list<${bM(u)}>`;return e.description==null&&e.title==null?l:{...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:kx(e.availability)}:{},type:l}}function t6s({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=PEo(e.key),l=I0({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),d=e.encoding!=null?mEo(e.encoding):void 0,s=`map<${bM(u)}, ${bM(l)}>`;if(e.description==null&&d==null&&e.title==null)return s;let o={type:s};return e.description!=null&&(o.docs=e.description),e.encoding!=null&&(o.encoding=d),e.availability!=null&&(o.availability=kx(e.availability)),o}function r6s({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){if(!i.respectNullableSchemas)return jEo({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});let u=I0({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=bM(u),d=APn(u),s=Mla(u),o=X7s(u),c=l.startsWith("nullable<")?l:`nullable<${l}>`;if(e.availability==null&&e.description==null&&d==null&&s==null&&o==null&&e.title==null)return xTp({typeReference:c,itemType:l});let b={type:c};return(e.description!=null||d!=null)&&(b.docs=e.description??d),s!=null&&(b.default=s),o!=null&&(b.validation=o),e.availability!=null&&(b.availability=kx(e.availability)),xTp({typeReference:b,itemType:l})}function jEo({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=I0({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=bM(u),d=APn(u),s=Mla(u),o=X7s(u),c=l.startsWith("optional<")?l:`optional<${l}>`;if(e.availability==null&&e.description==null&&d==null&&s==null&&o==null&&e.title==null)return c;let b={type:c};return(e.description!=null||d!=null)&&(b.docs=e.description??d),s!=null&&(b.default=s),o!=null&&(b.validation=o),e.availability!=null&&(b.availability=kx(e.availability)),b}function i6s(){return"unknown"}function n6s(e){let t;switch(e.value.type){case"boolean":{t=`literal<${e.value.value}>`;break}case"string":{t=`literal<"${e.value.value}">`;break}default:Ko(e.value)}return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:kx(e.availability)}:{}}}function baD({schema:e,fileContainingReference:t,declarationFile:r,context:i,declarationDepth:n}){let a=Ala(e,n),u=e.nameOverride??e.generatedName;i.builder.addType(r,{name:u,schema:a.schema});let l=wEo({type:u,fileContainingReference:t,declarationFile:r,context:i});if(e.description==null&&e.default==null&&e.title==null)return l;let d={type:l};return e.description!=null&&(d.docs=e.description),e.default!=null&&(d.default=e.default.value),e.availability!=null&&(d.availability=kx(e.availability)),d}function gaD({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=a6s({schema:e,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=e.nameOverride??e.generatedName;i.builder.addType(r,{name:l,schema:u.schema});let d=wEo({type:l,fileContainingReference:t,declarationFile:r,context:i});return e.description==null&&e.title==null?d:{type:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:kx(e.availability)}:{}}}function OaD({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=o6s({schema:e,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=e.nameOverride??e.generatedName;i.builder.addType(r,{name:l,schema:u.schema});let d=wEo({type:l,fileContainingReference:t,declarationFile:r,context:i});return e.description==null&&e.title==null?d:{...e.title!=null?{"display-name":e.title}:{},type:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:kx(e.availability)}:{}}}function wEo({type:e,fileContainingReference:t,declarationFile:r,context:i}){if(r===t)return e;let n=i.builder.addImport({file:t,fileToImport:r});return n!=null?`${n}.${e}`:e}function maD(e){return py._visit(e,{primitive:t=>t.nameOverride??t.generatedName,object:t=>t.nameOverride??t.generatedName,array:t=>t.nameOverride??t.generatedName,map:t=>t.nameOverride??t.generatedName,enum:t=>t.nameOverride??t.generatedName,reference:t=>t.nameOverride??t.generatedName,literal:t=>t.nameOverride??t.generatedName,oneOf:t=>t.nameOverride??t.generatedName,optional:t=>t.nameOverride??t.generatedName,nullable:t=>t.nameOverride??t.generatedName,unknown:t=>t.nameOverride??t.generatedName,_other:()=>{}})}function PaD(e){return py._visit(e,{primitive:t=>t.title,object:t=>t.title,array:t=>t.title,map:t=>t.title,enum:t=>t.title,reference:t=>t.title,literal:t=>t.title,oneOf:t=>t.title,optional:t=>t.title,nullable:t=>t.title,unknown:t=>{},_other:()=>{}})}function xTp({typeReference:e,itemType:t}){return t.startsWith("optional<")?e:typeof e=="string"?`optional<${e}>`:{...e,type:`optional<${e.type}>`}}function JGr(e){switch(e.type){case"openapi":return{openapi:e.file};case"protobuf":return{proto:e.file};default:Ko(e)}}function RTp({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a;switch(e.type){case"primitive":a=SaD(e);break;case"array":a=jaD({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"map":a=waD({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"reference":a=DaD({schema:e,context:t,declarationFile:r,namespace:i});break;case"unknown":a=MaD(e.nameOverride,e.generatedName);break;case"optional":a=NTp({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"nullable":a=EaD({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"enum":a=Ala(e,n);break;case"literal":a=AaD(e,e.nameOverride,e.generatedName);break;case"object":a=a6s({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"oneOf":a=o6s({schema:e.value,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;default:Ko(e)}return a}function a6s({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a=t.isInState(a2.Request)&&t.respectReadonlySchemas&&(t.getEndpointMethod()==="POST"||t.getEndpointMethod()==="PUT"||t.getEndpointMethod()==="PATCH"),u=!1,l={},d=new Set;for(let g of e.properties){if(g.readonly&&(u=!0),a&&g.readonly)continue;if(Object.keys(g.conflict).length>0){if(Object.entries(g.conflict).every(([D,C])=>!C.differentSchema))continue;Object.entries(g.conflict).forEach(([D])=>{u6s({property:g.key,schemaId:D,context:t,namespace:i}).forEach(R=>{d.add(R)})})}let O=I0({schema:g.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1}),m=g.audiences,w=g.nameOverride,E=kx(g.availability),A=BaD(g);l[g.key]=CaD({typeReference:O,audiences:m,name:w,availability:E,propertyAccess:A})}let s=new Set;for(let g of e.allOfPropertyConflicts)g.allOfSchemaIds.forEach(O=>d.add(O)),g.conflictingTypeSignatures&&s.add(g.propertyKey);let o=[];for(let g of e.allOf){let O=FTp({schema:g.schema,context:t,namespace:i});if(O==null||d.has(g.schema)||d.has(O))continue;let m=I0({schema:py.reference(g),context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});o.push(bM(m))}for(let g of d){let O=s6s(t,g,i);for(let m of O.properties)l[m.key]==null&&(s.has(m.key)&&(l[m.key]="unknown"),l[m.key]=I0({schema:m.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1}));for(let m of O.allOf){if(d.has(m.schema))continue;let w=I0({schema:py.reference(m),context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});o.push(bM(w))}}let c={docs:e.description??void 0,properties:Object.fromEntries(Object.entries(l).map(([g,O])=>TaD(g)?[g,typeof O=="string"?{type:O,name:`_${g}`}:{...O,name:`_${g}`}]:[g,O]))};o.length>0&&(c.extends=o),e.additionalProperties&&(c["extra-properties"]=!0),e.availability!=null&&(c.availability=kx(e.availability)),e.source!=null&&(c.source=JGr(e.source)),c.inline=c6s(e,n);let b=e.nameOverride??e.generatedName;return{name:u&&t.respectReadonlySchemas&&!a?`${b}Read`:b,schema:c}}function u6s({property:e,schemaId:t,context:r,namespace:i}){let n=r.getSchema(t,i);if(n==null)return[];if(n.type==="reference")return u6s({property:e,schemaId:n.schema,context:r,namespace:i});if(n.type==="object"){let{properties:a,allOf:u}=s6s(r,t,i),l=a.some(s=>s.key===e),d=[...u.flatMap(s=>u6s({property:e,context:r,schemaId:s.schema,namespace:i}))];if(l||d.length>0)return[t,...d]}return[]}function s6s(e,t,r){let i=e.getSchema(t,r);if(i==null)return{properties:[],allOf:[]};if(i.type==="object")return{properties:i.properties,allOf:i.allOf};if(i.type==="reference")return s6s(e,i.schema,r);throw new Error(`Cannot getAllProperties for a non-object schema. schemaId=${t}, type=${i.type}`)}function jaD({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:e6s({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:i,declarationDepth:n})}}function waD({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:t6s({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:i,declarationDepth:n})}}function SaD(e){let t=PEo(e);if(typeof t=="string")return{name:e.nameOverride??e.generatedName,schema:t};let{default:r,...i}=t;return{name:e.nameOverride??e.generatedName,schema:{...i}}}function zTp(e){return e.camel==null&&e.pascal==null&&e.screamingSnake==null&&e.snake==null}function Ala(e,t){let r={enum:e.values.map(a=>{let u=a.nameOverride??a.generatedName,l=a.value;if(u===l&&a.description==null&&(a.casing==null||zTp(a.casing)))return u;let d={value:a.value};if(u!==l&&(d.name=u),a.description!=null&&(d.docs=a.description),a.casing!=null&&!zTp(a.casing)){let s={},o=!1;a.casing.camel!=null&&(s.camel=a.casing.camel,o=!0),a.casing.screamingSnake!=null&&(s["screaming-snake"]=a.casing.screamingSnake,o=!0),a.casing.snake!=null&&(s.snake=a.casing.snake,o=!0),a.casing.pascal!=null&&(s.pascal=a.casing.pascal,o=!0),o&&(d.casing=s)}return d})};e.description!=null&&(r.docs=e.description),e.default!=null&&(r.default=e.default.value),r.inline=c6s(e,t);let i=new Set,n={...r,enum:[],source:e.source!=null?JGr(e.source):void 0};for(let a of r.enum){let u=typeof a=="string"?a:a.name??a.value;i.has(u.toLowerCase())||(n.enum.push(a),i.add(u.toLowerCase()))}return{name:e.nameOverride??e.generatedName,schema:n}}function DaD({schema:e,context:t,declarationFile:r,namespace:i}){return{name:e.nameOverride??e.generatedName,schema:k7s({schema:e,context:t,fileContainingReference:r,namespace:i})}}function EaD({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return t.respectNullableSchemas?{name:e.nameOverride??e.generatedName,schema:r6s({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:i,declarationDepth:n})}:NTp({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n})}function NTp({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:jEo({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:i,declarationDepth:n})}}function MaD(e,t){return{name:e??t,schema:i6s()}}function AaD(e,t,r){return{name:t??r,schema:n6s(e)}}function o6s({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a=e.encoding!=null?mEo(e.encoding):void 0;if(e.type==="discriminated"){let l={};for(let s of e.commonProperties)l[s.key]=I0({schema:s.schema,fileContainingReference:r,context:t,namespace:i,declarationDepth:n+1});let d={};for(let[s,o]of Object.entries(e.schemas))d[s]=I0({schema:o,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});return{name:e.nameOverride??e.generatedName,schema:{discriminant:e.discriminantProperty,"base-properties":l,docs:e.description??void 0,availability:e.availability!=null?kx(e.availability):void 0,union:d,encoding:a,source:e.source!=null?JGr(e.source):void 0}}}let u=[];for(let l of e.schemas)u.push(I0({schema:l,fileContainingReference:r,context:t,namespace:i,declarationDepth:n+1}));return{name:e.nameOverride??e.generatedName,schema:{discriminated:!1,docs:e.description??void 0,union:u,encoding:a,source:e.source!=null?JGr(e.source):void 0,inline:c6s(e,n)}}}var qaD=/^[0-9]/;function TaD(e){return qaD.test(e)}function FTp({schema:e,context:t,namespace:r}){let i=t.getSchema(e,r);if(i!=null)return i.type==="reference"?FTp({context:t,schema:i.schema,namespace:r}):e}function CaD({typeReference:e,audiences:t,name:r,availability:i,propertyAccess:n}){return t.length===0&&r==null&&i==null&&n==null?e:{...typeof e=="string"?{type:e}:{...e},...t.length>0?{audiences:t}:{},...r!=null?{name:r}:{},...i!=null?{availability:i}:{},...n!=null?{access:n}:{}}}function c6s(e,t){return e.inline===!0||t>0?!0:void 0}function BaD(e){if(!(e.readonly&&e.writeonly)){if(e.readonly)return G6.ObjectPropertyAccess.ReadOnly;if(e.writeonly)return G6.ObjectPropertyAccess.WriteOnly}}function LTp(e){let t=e.replace(/^x-|^X-/,"");return vg(t)}var UTp="BasicAuthScheme",SEo="BearerAuthScheme";function VTp(e){if(e.authOverrides!=null){for(let[r,i]of Object.entries(e.authOverrides["auth-schemes"]??{}))e.builder.addAuthScheme({name:r,schema:i});e.authOverrides.auth!=null&&e.builder.setAuth(e.authOverrides.auth);return}let t=!1;for(let[r,i]of Object.entries(e.ir.securitySchemes))if(i.type==="basic"){let n={scheme:"basic"};i.usernameVariableName!=null&&(n.username===void 0?n.username={name:i.usernameVariableName}:n.username.name=i.usernameVariableName),i.usernameEnvVar!=null&&(n.username===void 0?n.username={env:i.usernameEnvVar}:n.username.env=i.usernameEnvVar),i.passwordVariableName!=null&&(n.password===void 0?n.password={name:i.passwordVariableName}:n.password.name=i.passwordVariableName),i.passwordEnvVar!=null&&(n.password===void 0?n.password={env:i.passwordEnvVar}:n.password.env=i.passwordEnvVar),e.builder.addAuthScheme({name:UTp,schema:n}),t||(e.builder.setAuth(UTp),t=!0)}else if(i.type==="bearer"){let n={scheme:"bearer"};i.tokenVariableName!=null&&(n.token===void 0?n.token={name:i.tokenVariableName}:n.token.name=i.tokenVariableName),i.tokenEnvVar!=null&&(n.token===void 0?n.token={env:i.tokenEnvVar}:n.token.env=i.tokenEnvVar),e.builder.addAuthScheme({name:SEo,schema:n}),t||(e.builder.setAuth(SEo),t=!0)}else if(i.type==="header")if(t)e.builder.addGlobalHeader({name:i.headerName,schema:{type:"string",name:i.headerVariableName??LTp(i.headerName),env:i.headerEnvVar}});else{let n={header:i.headerName,name:i.headerVariableName??"apiKey",type:"string"};i.headerEnvVar!=null&&(n.env=i.headerEnvVar),i.prefix!=null&&(n.prefix=i.prefix),e.builder.addAuthScheme({name:r,schema:n}),e.builder.setAuth(r),t=!0}else if(i.type==="oauth"){let n={scheme:"bearer"};e.builder.addAuthScheme({name:SEo,schema:n}),t||(e.builder.setAuth(SEo),t=!0),i.scopesEnum!=null&&i.scopesEnum.values.length>0&&e.builder.addType(ry.of("__package__.yml"),{name:"OauthScope",schema:Ala(i.scopesEnum,0).schema})}}function _Yt({header:e,context:t,fileContainingReference:r,namespace:i}){let n=I0({schema:e.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),a=bM(n),u=e.name.replace(/^x-|^X-/,""),l=e.parameterNameOverride!=null?e.parameterNameOverride:vg(u);if(e.description==null&&e.name===l&&e.env==null&&e.availability==null)return a;let d={type:a};return l!==e.name&&(d.name=l),e.description!=null&&(d.docs=e.description),e.env!=null&&(d.env=e.env),e.availability!=null&&(d.availability=kx(e.availability)),d}function DEo({pathParameter:e,context:t,fileContainingReference:r,namespace:i}){let n=I0({schema:e.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:0});if(e.variableReference==null&&e.description==null&&e.availability==null)return bM(n);let a=e.variableReference!=null?{variable:`$${e.variableReference}`}:{type:bM(n)};return e.description!=null&&(a.docs=e.description),e.availability!=null&&(a.availability=kx(e.availability)),a}function MEo({queryParameter:e,context:t,fileContainingReference:r,namespace:i}){let n=l6s({schema:e.schema,context:t,fileContainingReference:r,namespace:i});if(n==null)return;let a=bM(n.value),u=Mla(n.value);if(a==="unknown"?a="string":a==="optional<unknown>"&&(a="optional<string>"),e.description==null&&!n.allowMultiple&&e.parameterNameOverride==null&&e.availability==null)return a;let l={type:a};return u!=null&&(l.default=u),n.allowMultiple&&(l["allow-multiple"]=!0),e.description!=null&&(l.docs=e.description),e.parameterNameOverride!=null&&(l.name=e.parameterNameOverride),e.availability!=null&&(l.availability=kx(e.availability)),xaD(n.value)&&n.value.validation!==void 0&&(l.validation=n.value.validation),l}function l6s({schema:e,context:t,fileContainingReference:r,namespace:i}){if(e.type==="reference"){let n=t.getSchema(e.schema,i);if(n==null)return;if(n.type==="array")return{value:I0({schema:py.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:n.value,description:e.description??n.description,availability:e.availability,groupName:void 0,inline:void 0}),context:t,declarationFile:ry.of(W1),fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(n.type==="oneOf"&&n.value.type==="undiscriminated"){let a=[];for(let[u,l]of Object.entries(n.value.schemas))l.type==="literal"&&l.value.type==="string"&&(SPn.test(l.value.value)?a.push(l.value.value):a.push({value:l.value.value,name:DPn(l.value.value)}));if(a.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:a}}),{value:e.generatedName,allowMultiple:!1};if(n.value.schemas.length===2){let[u,l]=n.value.schemas;if(u!=null&&l!=null&&EEo({array:u,primitive:l}))return{value:I0({schema:py.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:l,description:e.description,availability:e.availability,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(u!=null&&l!=null&&EEo({array:u,primitive:l}))return{value:I0({schema:py.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:u,description:e.description,availability:e.availability,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}}for(let[u,l]of Object.entries(n.value.schemas))return l6s({schema:l,context:t,fileContainingReference:r,namespace:i})}else if(t.objectQueryParameters)return{value:I0({schema:e,context:t,fileContainingReference:r,declarationFile:ry.of(W1),namespace:i,declarationDepth:0}),allowMultiple:!1}}if(e.type==="optional"||e.type==="nullable"){if(e.value.type==="reference"){let n=t.getSchema(e.value.schema,i);if(n==null)return;if(n.type==="array")return{value:I0({schema:py.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:n.value,description:e.description??n.description,availability:e.availability,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,declarationFile:ry.of(W1),namespace:i,declarationDepth:0}),allowMultiple:!0};if(t.objectQueryParameters)return{value:I0({schema:e,context:t,fileContainingReference:r,declarationFile:ry.of(W1),namespace:i,declarationDepth:0}),allowMultiple:!1}}if(e.value.type==="array")return{value:I0({schema:py.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value.value,description:e.description,availability:e.availability,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(e.value.type==="oneOf"&&e.value.value.type==="undiscriminated"){let n=[];for(let[a,u]of Object.entries(e.value.value.schemas))u.type==="literal"&&u.value.type==="string"&&(SPn.test(u.value.value)?n.push(u.value.value):n.push({value:u.value.value,name:DPn(u.value.value)}));if(n.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:n}}),{value:`optional<${e.value.value.generatedName}>`,allowMultiple:!1};if(e.value.value.schemas.length===2){let[a,u]=e.value.value.schemas;if(a!=null&&u!=null&&EEo({array:a,primitive:u}))return{value:I0({schema:py.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:u,description:e.description,availability:e.availability,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(a!=null&&u!=null&&EEo({array:u,primitive:a}))return{value:I0({schema:py.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:a,description:e.description,availability:e.availability,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}}for(let[a,u]of Object.entries(e.value.value.schemas))return l6s({schema:py.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:u,description:void 0,availability:e.availability,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i})}else if(e.value.type==="object")return t.objectQueryParameters?{value:I0({schema:e,context:t,fileContainingReference:r,declarationFile:ry.of(W1),namespace:i,declarationDepth:0}),allowMultiple:!1}:void 0;return{value:I0({schema:e,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!1}}return e.type==="array"?{value:I0({schema:py.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:e.description,availability:e.availability,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}:{value:I0({schema:e,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!1}}function EEo({array:e,primitive:t}){return e?.type==="array"&&e.value.type==="primitive"&&t?.type==="primitive"&&e.value.schema.type===t.schema.type}function xaD(e){return e.type!=null}function WTp({websocketExample:e,context:t}){let r={messages:[]};e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=IaD(e.queryParameters)),e.headers!=null&&e.headers.length>0&&(r.headers=zaD({context:t,namedFullExamples:e.headers}));for(let i of e.messages){let n=fli(i.payload);n!=null&&r.messages.push({type:i.messageType,body:n})}return r}function IaD(e){let t={};return e.forEach(r=>{let i=fli(r.value);Array.isArray(i)?t[r.name]=i[0]:i!=null&&(t[r.name]=i)}),t}function zaD({context:e,namedFullExamples:t}){let r=e.builder.getGlobalHeaderNames(),i={};return t.forEach(n=>{let a=fli(n.value);r.has(n.name)||a!=null&&(i[n.name]=a)}),i}function fli(e){switch(e.type){case"primitive":return HTp(e.value);case"object":return $Tp(e.properties);case"array":return RaD(e.value);case"map":return NaD(e.value);case"oneOf":return FaD(e.value);case"enum":return e.value;case"literal":return LaD(e.value);case"unknown":return fli(e.value);default:Ko(e)}}function HTp(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`${e.value.slice(1)}`:e.value;case"datetime":try{return new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"date":return e.value;case"base64":case"boolean":return e.value;default:Ko(e)}}function $Tp(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,fli(r)]))}function RaD(e){return e.map(t=>fli(t))}function NaD(e){return Object.fromEntries(e.map(t=>[HTp(t.key),fli(t.value)]))}function FaD(e){return e.type==="discriminated"?$Tp(e.value):fli(e.value)}function LaD(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:Ko(e)}}function KGr(e){return e.find(t=>typeof t!="string"&&t.type==="namespace")?.name}function AEo(e,t){return t??(e?.groupName!=null?KGr(e.groupName):void 0)}function GTp({channel:e,context:t,declarationFile:r}){let i={path:e.path,url:e.servers[0]?.name,auth:!1};e.audiences!=null&&e.audiences.length>0&&(i.audiences=e.audiences),e.summary!=null&&(i["display-name"]=e.summary);let n=KGr(e.groupName),a={};if(e.handshake.pathParameters.length>0)for(let d of e.handshake.pathParameters)a[d.name]=DEo({pathParameter:d,context:t,fileContainingReference:r,namespace:n});Object.keys(a).length>0&&(i["path-parameters"]=a);let u={};if(e.handshake.queryParameters.length>0)for(let d of e.handshake.queryParameters){let s=MEo({queryParameter:d,context:t,fileContainingReference:r,namespace:n});s!=null&&(u[d.name]=s)}Object.keys(u).length>0&&(i["query-parameters"]=u);let l={};if(e.handshake.headers.length>0)for(let d of e.handshake.headers){let s=_Yt({header:d,context:t,fileContainingReference:r,namespace:n});l[d.name]=s}Object.keys(l).length>0&&(i.headers=l),t.builder.addChannel(r,{channel:i}),e.subscribe!=null&&t.builder.addChannelMessage(r,{messageId:"subscribe",message:{origin:"server",body:I0({schema:e.subscribe,context:t,fileContainingReference:r,namespace:n,declarationDepth:0})}}),e.publish!=null&&t.builder.addChannelMessage(r,{messageId:"publish",message:{origin:"client",body:I0({schema:e.publish,context:t,fileContainingReference:r,namespace:n,declarationDepth:0})}});for(let d of e.examples){let s=WTp({context:t,websocketExample:d});t.builder.addChannelExample(r,{example:s})}}var dli="Base",UaD="Default";function pli(e){return Object.entries(e).reduce((t,[r,i])=>(Dhn(i)?Object.entries(i.urls).forEach(([n,a])=>{t[n]=a}):t[r]=typeof i=="string"?i:i.url,t),{})}function QTp(e){if(e.environmentOverrides!=null){for(let[b,g]of Object.entries(e.environmentOverrides.environments??{}))e.builder.addEnvironment({name:b,schema:g});e.environmentOverrides["default-environment"]!=null&&e.builder.setDefaultEnvironment(e.environmentOverrides["default-environment"]),e.environmentOverrides["default-url"]!=null&&e.builder.setDefaultUrl(e.environmentOverrides["default-url"]);return}let t={},r=[];for(let b of e.ir.servers){let g=b.audiences?{url:b.url,audiences:b.audiences}:b.url;if(b.name==null){r.push(g);continue}t[b.name]=g}let i={},n=[];for(let b of e.ir.endpoints)for(let g of b.servers){if(g.url==null)continue;let O=g.audiences?{url:g.url,audiences:g.audiences}:g.url;if(g.name==null){n.push(O);continue}i[g.name]=O}let a={},u=[];for(let b of e.ir.websocketServers){let g=b.audiences?{url:b.url,audiences:b.audiences}:b.url;if(b.name==null){u.push(g);continue}a[b.name]=g}let l=Object.keys(t).length,d=Object.keys(i).length>0,s=Object.keys(a).length>0;if(n.length>0&&e.logger.error(`Skipping endpoint level servers ${n.map(b=>typeof b=="string"?b:b.url).join(", ")} because x-fern-server-name was not provided.`),l===0){let b=e.ir.servers[0]?.url,g=e.ir.servers[0]?.audiences;if(b!=null){let O=g?{url:b,audiences:g}:b;t[UaD]=O}}let o=Object.values(t).map(b=>typeof b=="string"?b:b.url),c=r.filter(b=>{let g=typeof b=="string"?b:b.url;return!o.includes(g)});if(c.length>0&&e.logger.error(`Skipping top level servers ${c.map(b=>typeof b=="string"?b:b.url).join(", ")} because x-fern-server-name was not provided.`),d)if(l===1){let b=Object.keys(t)[0],g=Object.values(t)[0],O=typeof g=="string"?g:g.url;e.builder.addEnvironment({name:b,schema:{urls:{[dli]:O,...pli(i),...pli(a)}}}),e.builder.setDefaultEnvironment(b),e.builder.setDefaultUrl(dli)}else{let b=!0;for(let[g,O]of Object.entries(t))b?(e.builder.addEnvironment({name:g,schema:{urls:{[dli]:typeof O=="string"?O:O.url,...pli(i),...pli(a)}}}),e.builder.setDefaultEnvironment(g),b=!1):e.builder.addEnvironment({name:g,schema:{urls:{[dli]:typeof O=="string"?O:O.url,...pli(i),...pli(a)}}});e.builder.setDefaultUrl(dli)}else{let b=!0;for(let[g,O]of Object.entries(t))b?(s?e.builder.addEnvironment({name:g,schema:{urls:{[dli]:typeof O=="string"?O:O.url,...pli(a)}}}):e.builder.addEnvironment({name:g,schema:O}),e.builder.setDefaultEnvironment(g),b=!1):s?e.builder.addEnvironment({name:g,schema:{urls:{[dli]:typeof O=="string"?O:O.url,...pli(a)}}}):e.builder.addEnvironment({name:g,schema:O});s&&e.builder.setDefaultUrl(dli)}}function qEo(e){return bM(e).startsWith("optional")?e:typeof e=="string"?`optional<${e}>`:{...e,type:`optional<${e.type}>`}}var f6s=class{schema;count=0;constructor(t){this.schema=t}increment(){this.count+=1}},VaD=.75,WaD=new Set("authorization");function JTp(e){if(e.globalHeaderOverrides!=null){for(let[r,i]of Object.entries(e.globalHeaderOverrides.headers??{}))e.builder.addGlobalHeader({name:r,schema:i});return}let t=Object.fromEntries((e.ir.globalHeaders??[]).map(r=>[r.header,r]));for(let[r,i]of Object.entries(t)){let n="optional<string>";if(i.name==null&&i.env==null&&typeof i.schema=="string")n=i.schema;else if(i!=null){let a=i.schema?MPn(i.schema):void 0,u=a!=null?KGr(a):void 0,l=ry.of("api.yml");n={name:i.name,env:i.env,type:i.schema!=null?bM(I0({schema:i.schema,context:e,fileContainingReference:u?sR(ry.of(vg(u)),l):l,namespace:u,declarationDepth:0}))??"optional<string>":"optional<string>"}}e.builder.addGlobalHeader({name:r,schema:n})}if(e.detectGlobalHeaders){let r={};for(let n of e.ir.endpoints)for(let a of n.headers){if(WaD.has(a.name.toLowerCase()))continue;let u=r[a.name];if(u==null){let l=t[a.name],d=_Yt({header:{...a,schema:l?.schema??a.schema,name:l?.name??a.name},fileContainingReference:ry.of(T3),context:e,namespace:void 0});u=new f6s(d),r[a.name]=u}u.increment()}let i=e.ir.endpoints.length*VaD;for(let[n,a]of Object.entries(r)){let u=t[n],l=a.count===e.ir.endpoints.length,d=a.count>=i;u==null&&(l?e.builder.addGlobalHeader({name:n,schema:a.schema}):d&&e.builder.addGlobalHeader({name:n,schema:qEo(a.schema)}))}}}function KTp(e){for(let t of e.ir.idempotencyHeaders??[]){let r=t.schema?MPn(t.schema):void 0,i=r!=null?KGr(r):void 0,n=_Yt({header:{...t,schema:t.schema??py.primitive({description:void 0,availability:void 0,generatedName:"",title:void 0,groupName:void 0,nameOverride:void 0,schema:sj.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0})}),name:t.name??t.header,parameterNameOverride:void 0,description:void 0,availability:void 0,source:void 0},fileContainingReference:ry.of(T3),context:e,namespace:i});e.builder.addIdempotencyHeader({name:t.header,schema:qEo(n)})}}function $$(e){switch(e.type){case"primitive":return XTp(e.value);case"object":return ZTp(e.properties);case"array":return kTp(e.value);case"map":return $aD(e.value);case"oneOf":return GaD(e.value);case"enum":return e.value;case"literal":return QaD(e.value);case"unknown":return $$(e.value);default:Ko(e)}}function YTp(e){switch(e.type){case"withStreaming":return e.sse?{stream:HaD(e.events)}:{stream:kTp(e.events)};case"withoutStreaming":return{body:$$(e.value)};default:Ko(e)}}function XTp(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`${e.value.slice(1)}`:e.value;case"datetime":try{return!e.value.endsWith("Z")&&!e.value.includes("+")&&(e.value+="Z"),new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"date":return e.value;case"base64":case"boolean":return e.value;default:Ko(e)}}function ZTp(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,$$(r)]))}function HaD(e){return e.map(t=>({event:"",data:$$(t)}))}function kTp(e){return e.map(t=>$$(t))}function $aD(e){return Object.fromEntries(e.map(t=>[XTp(t.key),$$(t.value)]))}function GaD(e){return e.type==="discriminated"?ZTp(e.value):$$(e.value)}function QaD(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:Ko(e)}}function eCp({endpointExample:e,context:t}){let r={};return e.type!=="full"?e.value:(e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.pathParameters!=null&&e.pathParameters.length>0&&(r["path-parameters"]=JaD(e.pathParameters)),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=KaD(e.queryParameters)),e.headers!=null&&e.headers.length>0&&(r.headers=YaD({context:t,namedFullExamples:e.headers})),e.request!=null&&(r.request=$$(e.request)),e.response!=null&&(r.response=YTp(e.response)),e.codeSamples!=null&&e.codeSamples.length>0&&(r["code-samples"]=e.codeSamples.map(i=>i.type==="language"?{name:i.name??void 0,docs:i.description??void 0,language:i.language,code:i.code,install:i.install??void 0}:{name:i.name??void 0,docs:i.description??void 0,sdk:i.sdk,code:i.code}).filter(u0)),r)}function JaD(e){let t={};return e.forEach(r=>{let i=$$(r.value);i!=null&&(t[r.parameterNameOverride??r.name]=i)}),t}function KaD(e){let t={};return e.forEach(r=>{let i=$$(r.value);Array.isArray(i)?t[r.name]=i[0]:i!=null&&(t[r.name]=i)}),t}function YaD({context:e,namedFullExamples:t}){let r=e.builder.getGlobalHeaderNames(),i={};return t.forEach(n=>{let a=$$(n.value);r.has(n.name)||a!=null&&(i[n.name]=a)}),i}function tCp(e){return W$._visit(e,{get:()=>G6.HttpMethodSchema.Get,post:()=>G6.HttpMethodSchema.Post,put:()=>G6.HttpMethodSchema.Put,patch:()=>G6.HttpMethodSchema.Patch,delete:()=>G6.HttpMethodSchema.Delete,head:()=>{throw new Error("HEAD is unsupported")},options:()=>{throw new Error("HEAD is unsupported")},trace:()=>{throw new Error("HEAD is unsupported")},_other:()=>{throw new Error("Unknown http method is unsupported")}})}function rCp(e){return e==="POST"||e==="PUT"||e==="PATCH"}function iCp({endpoint:e,declarationFile:t,context:r}){let{nonRequestReferencedSchemas:i}=r.ir,n=[],a=new Set,u=e.path,l=AEo(e.sdkName,e.namespace),d={};for(let m of e.pathParameters)m.parameterNameOverride&&(u=u.replace(m.name,m.parameterNameOverride)),d[m.parameterNameOverride??m.name]=DEo({pathParameter:m,context:r,fileContainingReference:t,namespace:l}),a.add(m.name);let s={};for(let m of e.queryParameters){let w=MEo({queryParameter:m,context:r,fileContainingReference:t,namespace:l});w!=null&&(s[m.name]=w,a.add(m.name))}let o;if(e.pagination!=null)switch(e.pagination.type){case"cursor":o={cursor:e.pagination.cursor,next_cursor:e.pagination.nextCursor,results:e.pagination.results};break;case"offset":o={offset:e.pagination.offset,step:e.pagination.step,results:e.pagination.results,"has-next-page":e.pagination.hasNextPage};break;case"custom":o={type:"custom",results:e.pagination.results};break;default:Ko(e.pagination)}let c={path:u,method:tCp(e.method),auth:e.authed,docs:e.description??void 0,pagination:o,source:e.source!=null?JGr(e.source):void 0};!kaD({context:r,request:e.request})&&Object.keys(d).length>0&&(c["path-parameters"]=d),e.summary!=null&&(c["display-name"]=e.summary);let b={},g=r.builder.getGlobalHeaderNames(),O=e.headers.filter(m=>!g.has(m.name));for(let m of O){let w=_Yt({header:m,context:r,fileContainingReference:t,namespace:l});b[m.name]=w,a.add(typeof w=="string"?m.name:w.name??m.name)}if(e.request!=null){r.setInState(a2.Request);let m=ZaD({endpoint:e,context:r,declarationFile:t,request:e.request,generatedRequestName:e.generatedRequestName,requestNameOverride:e.requestNameOverride??void 0,pathParameters:r.inlinePathParameters&&Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,nonRequestReferencedSchemas:Array.from(i),headers:Object.keys(b).length>0?b:void 0,usedNames:a,namespace:l});c.request=m.value,n=[...n,...m.schemaIdsToExclude??[]],r.unsetInState(a2.Request)}else{let m=r.inlinePathParameters&&Object.keys(d).length>0,w=Object.keys(s).length>0,E=Object.keys(b).length>0,A={};(m||w||E)&&(A.name=e.requestNameOverride??e.generatedRequestName),m&&(A["path-parameters"]=d),w&&(A["query-parameters"]=s),E&&(A.headers=b),Object.keys(A).length>0&&(c.request=A)}if(e.response!=null&&e.response._visit({json:m=>{let w=I0({schema:m.schema,context:r,fileContainingReference:t,namespace:l,declarationDepth:0});c.response={docs:m.description??void 0,type:bM(w)},m.statusCode!=null&&(c.response["status-code"]=m.statusCode),m.responseProperty!=null&&(c.response.property=m.responseProperty)},streamingJson:m=>{let w=I0({schema:m.schema,context:r,fileContainingReference:t,namespace:l,declarationDepth:0});c["response-stream"]={docs:m.description??void 0,type:bM(w),format:"json"}},streamingSse:m=>{let w=I0({schema:m.schema,context:r,fileContainingReference:t,namespace:l,declarationDepth:0});c["response-stream"]={docs:m.description??void 0,type:bM(w),format:"sse"}},file:m=>{c.response={docs:m.description??void 0,type:"file","status-code":m.statusCode}},streamingText:m=>{c["response-stream"]={docs:m.description??void 0,type:"text"}},text:m=>{c.response={docs:m.description??void 0,type:"text","status-code":m.statusCode}},_other:()=>{throw new Error("Unrecognized Response type: "+e.response?.type)}}),r.builder.getEnvironmentType()==="multi"){let m=r.getDefaultServerName(),w=e.servers[0];w==null?m!=null&&(c.url=m):c.url=w.name??void 0}return e.idempotent&&(c.idempotent=!0),e.availability!=null&&(c.availability=kx(e.availability)),Object.entries(e.errors).forEach(([m,w])=>{let E=w.generatedName,A=ry.of(W1);r.builder.enableUniqueErrorsPerEndpoint&&(E=`${e.generatedRequestName}${w.generatedName}`,w.schema!=null&&(w.schema.type!=="reference"&&w.schema.type!=="oneOf"?w.schema.generatedName=`${e.generatedRequestName}${w.schema.generatedName}`:w.schema.type==="oneOf"&&(w.schema.value.generatedName=`${e.generatedRequestName}${w.schema.value.generatedName}`)));let q={"status-code":parseInt(m)},D=BTp({location:nCp,namespaceOverride:l});if(w.schema!=null){let $=I0({schema:w.schema,context:r,fileContainingReference:D,declarationFile:D,namespace:l,declarationDepth:0});q.type=bM($),q.docs=w.description}r.builder.addError(D,{name:E,schema:r.isErrorUnknownSchema(parseInt(m))?{...q,type:"unknown"}:q}),c.errors==null&&(c.errors=[]);let C=r.builder.addImport({file:t,fileToImport:D});c.errors.push(C!=null?`${C}.${E}`:E),q.type!=null&&w.examples?.forEach($=>{let I={value:$$($.example),name:$.name,docs:$.description};r.builder.addErrorExample(D,{name:E,example:I})})}),e.examples.length>0&&(c.examples=XaD({endpointExamples:e.examples,context:r})),r.ir.hasEndpointsMarkedInternal&&(e.internal==null||!e.internal)?c.audiences=[d6s,...e.audiences]:e.audiences.length>0&&(c.audiences=e.audiences),{value:c,schemaIdsToExclude:n}}function XaD({endpointExamples:e,context:t}){return e.map(r=>{try{return eCp({endpointExample:r,context:t})}catch(i){throw console.error(`Error building endpoint example: ${i}`),i}})}function ZaD({endpoint:e,declarationFile:t,context:r,request:i,requestNameOverride:n,generatedRequestName:a,pathParameters:u,queryParameters:l,nonRequestReferencedSchemas:d,headers:s,usedNames:o,namespace:c}){if(i.type==="json"){let b=i.schema.type==="reference"?i.schema.schema:void 0,g=i.schema.type==="reference"?r.getSchema(i.schema.schema,c):i.schema;if(g?.type!=="object"||b!=null&&d.includes(b)){let A=I0({schema:i.schema,fileContainingReference:t,context:r,namespace:c,declarationDepth:0}),q={schemaIdsToExclude:[],value:{body:A}},D=Object.keys(u??{}).length>0,C=Object.keys(l??{}).length>0,R=Object.keys(s??{}).length>0;return D&&(q.value["path-parameters"]=u),C&&(q.value["query-parameters"]=l),R&&(q.value.headers=s),(D||C||R)&&(q.value.name=n??a),i.contentType!=null&&(q.value["content-type"]=i.contentType),i.description!=null&&(q.value.docs=i.description),q}let O=Object.fromEntries(g.properties.filter(A=>A.readonly==null?!0:!(rCp(e.method)&&A.readonly)).map(A=>{let q=I0({schema:A.schema,fileContainingReference:t,context:r,namespace:c,declarationDepth:1}),D=A.nameOverride??A.key,C=kx(A.availability);if(!o.has(D)&&A.audiences.length<=0)return o.add(D),A.nameOverride!=null?[A.key,{type:bM(q),docs:APn(q),name:A.nameOverride,availability:C}]:[A.key,C?{...typeof q=="string"?{type:q}:q,availability:C}:q];let R={type:bM(q),docs:APn(q)};return o.has(D)&&(R.name=A.generatedName),A.audiences.length>0&&(R.audiences=A.audiences),C!=null&&(R.availability=C),o.add(D),[A.key,R]})),m=g.allOf.map(A=>{let q=I0({schema:py.reference(A),fileContainingReference:t,context:r,namespace:c,declarationDepth:0});return bM(q)}),w={properties:O};m.length>0&&(w.extends=m),i.additionalProperties&&(w["extra-properties"]=!0);let E={name:n??g.nameOverride??g.generatedName,"path-parameters":u,"query-parameters":l,headers:s,body:w};return i.contentType!=null&&(E["content-type"]=i.contentType),i.description!=null&&(E.docs=i.description),{schemaIdsToExclude:b!=null?[b]:[],value:E}}else{if(i.type==="octetStream")return{schemaIdsToExclude:[],value:{body:"bytes","content-type":zB.APPLICATION_OCTET_STREAM,...i.description?{docs:i.description}:{}}};if(i.type==="multipart"){let b=Object.fromEntries(i.properties.map(g=>{if(g.schema.type==="file"){let O=g.schema.isArray?"list<file>":"file";if(O=g.schema.isOptional?`optional<${O}>`:O,g.description!=null||g.contentType!=null){let m={type:O};if(g.description!=null&&(m.docs=g.description),g.contentType!=null){let w=g.contentType.split(",")[0];m["content-type"]=w}return[g.key,m]}return[g.key,O]}else{let O=I0({schema:g.schema.value,fileContainingReference:t,context:r,namespace:c,declarationDepth:1});if(g.contentType!=null||g.exploded||g.encoding==="form"){let m=typeof O=="string"?{type:O}:O;g.contentType!=null&&(m["content-type"]=g.contentType),g.encoding==="form"?m.style="form":g.exploded&&(m.style="exploded"),O=m}return[g.key,O]}}));return{schemaIdsToExclude:i.name==null?[]:[i.name],value:{name:n??i.name??a,"path-parameters":u,"query-parameters":l,headers:s,body:{properties:b},"content-type":zB.MULTIPART_FORM_DATA,...i.description?{docs:i.description}:{}}}}else Ko(i)}}function kaD({context:e,request:t}){if(!e.inlinePathParameters)return!1;if(t==null)return!0;switch(t.type){case"octetStream":return!1;case"multipart":return!0;case"json":return!0;default:Ko(t)}}function eoD({location:e,namespaceOverride:t}){return t!=null?{...e,file:sR(ry.of(t),e.file)}:e}function toD(e){let t=e.namespace,r=e.tags.filter(d=>d!==t)[0],i=e.operationId;if(i==null)return r!=null?{file:ry.of(`${vg(r)}.yml`),endpointId:e.summary!=null?vg(e.summary):vg(`${e.method}_${e.path.split("/").join("_")}`)}:e.summary!=null?{file:ry.of(W1),endpointId:vg(e.summary)}:{file:ry.of(W1),endpointId:vg(`${e.method}_${e.path.split("/").join("_")}`)};if(r==null)return{file:ry.of(W1),endpointId:i};let n=qla(r),a=qla(i);if(u1e(n,a))return{file:ry.of("__package__.yml"),endpointId:r};let u=noD({operationId:i,tag:r,path:e.path,method:e.method});if(u!=null)return u;let l=[];for(let d=0;d<n.length;++d){let s=n[d];if(s!=null&&s===a[d])l.push(s);else{let o=vg(r);return{file:ry.of(`${o}.yml`),endpointId:i,tag:r}}}if(l.length>=a.length)throw new Error(`Cannot get file for endpoint ${JSON.stringify(e)}`);return{file:ry.of(vg(l.join("_"))+".yml"),endpointId:vg(a.slice(l.length).join("_")),tag:r}}function Tla(e){let t=e.tags[0];if(e.sdkName!=null){let r=Y7s({sdkName:e.sdkName,namespaceOverride:e.namespace}),i=`${r}.yml`,n=r.toLowerCase()===t?.toLowerCase().replaceAll(" ","");return{file:ry.of(i),endpointId:e.sdkName.methodName,tag:n?t:void 0}}return eoD({namespaceOverride:e.namespace,location:toD(e)})}function qla(e){let t;return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)?t=e.split(/(?=[A-Z])/):t=e.split(/[^a-zA-Z0-9]+/),t=t.map(r=>r.toLowerCase()),t=CCe(t),t}var roD=new RegExp("[^a-zA-Z0-9{}]+"),ioD=new RegExp("[{}]","g");function noD({operationId:e,tag:t,path:r,method:i}){let a=`${r.split(roD).join("_").replaceAll(ioD,"_")}_${i.toLowerCase()}`;if(e.endsWith(a))return{file:ry.of(vg(t)+".yml"),endpointId:vg(e.slice(0,-1*a.length)),tag:t}}function aCp(e){let t=new Set,{endpoints:r,tags:i}=e.ir,n=[];for(let a of r){let{endpointId:u,file:l,tag:d}=Tla(a),s=l.split(".")[0];s!=null&&t.add(s);let o;if(a.sdkName!=null){let g=e.ir.groups;for(let O of a.sdkName.groupName){let m=typeof O=="string"?O:O.name,w=g[m];if(w==null)break;if(w.summary!=null||w.description!=null){o=g[m];break}}}let c=d==null?void 0:i.tagsById[d];e.setInState(a2.Endpoint),e.setEndpointMethod(a.method);let b=iCp({context:e,endpoint:a,declarationFile:l});e.unsetEndpointMethod(),e.unsetInState(a2.Endpoint),n=[...n,...b.schemaIdsToExclude],e.builder.addEndpoint(l,{name:u,schema:b.value,source:a.source!=null?JGr(a.source):void 0}),(c?.id!=null||c?.description!=null)&&e.builder.setServiceInfo(l,{"display-name":o?.summary??c?.id,docs:o?.description??c?.description??void 0})}return{schemaIdsToExclude:n,sdkGroups:t}}function oCp(e){for(let[t,r]of Object.entries(e.ir.variables)){let i=r.groupName!=null?KGr(r.groupName):void 0,n=I0({schema:py.primitive(r),context:e,fileContainingReference:ry.of(W1),namespace:i,declarationDepth:0});e.builder.addVariable({name:t,schema:{type:bM(n),docs:r.description??void 0}})}}function uCp(e){for(let t of e.ir.webhooks){let r=uoD({webhook:t,context:e});if(r==null)continue;let i=AEo(t.sdkName,t.namespace),n={};for(let u of t.headers)n[u.name]=_Yt({header:u,context:e,fileContainingReference:r.file,namespace:i});let a={method:t.method,"display-name":t.summary??void 0,headers:n,payload:I0({schema:t.payload,context:e,fileContainingReference:r.file,namespace:i,declarationDepth:0}),examples:t.examples!=null?t.examples.map(u=>({docs:u.description,name:u.name,payload:$$(u.payload)})):void 0};e.builder.addWebhook(r.file,{name:r.endpointId,schema:a}),t.description!=null&&(a.docs=t.description)}}function aoD({location:e,namespaceOverride:t}){if(e!=null)return t!=null?{...e,file:sR(ry.of(t),e.file)}:e}function ooD({webhook:e,context:t}){let r=e.tags[0],i=e.operationId;if(r==null)return{file:ry.of(W1),endpointId:i};let n=qla(r),a=qla(i);if(u1e(n,a))return{file:ry.of("__package__.yml"),endpointId:r};let u=[];for(let l=0;l<n.length;++l){let d=n[l];if(d!=null&&d===a[l])u.push(d);else{let s=vg(r);return{file:ry.of(`${s}.yml`),endpointId:i,tag:r}}}if(u.length>=a.length){t.logger.warn(`Skipping webhook ${e.operationId} because couldn't compute file location`);return}return{file:ry.of(vg(u.join("_"))+".yml"),endpointId:vg(a.slice(u.length).join("_")),tag:r}}function uoD({webhook:e,context:t}){return e.sdkName!=null?{file:CTp({sdkName:e.sdkName,namespaceOverride:e.namespace}),endpointId:e.sdkName.methodName}:aoD({namespaceOverride:e.namespace,location:ooD({webhook:e,context:t})})}var soD=ry.of(W1);function sCp(e){switch(e.type){case"object":return hYt(e.groupName);case"enum":return hYt(e.groupName);case"oneOf":return hYt(e.value.groupName);case"array":return hYt(e.groupName);case"map":return hYt(e.groupName);case"reference":return hYt(e.groupName);case"literal":return hYt(e.groupName);case"optional":return hYt(e.groupName);case"nullable":return hYt(e.groupName);case"primitive":return hYt(e.groupName);case"unknown":return soD;default:Ko(e)}}function hYt(e){return EPn(e)}var d6s="external",nCp=ry.of(W1);function cCp({schemas:e,schemaIdsToExclude:t,namespace:r,context:i}){for(let[n,a]of Object.entries(e)){if(t.includes(n))continue;let u=sCp(a),l=RTp({schema:a,context:i,declarationFile:u,namespace:r,declarationDepth:0});if(Foi(l.schema)){let d=bM(l.schema);if(d===(l.name??n)||d===`optional<${l.name??n}>`)continue}i.builder.addType(u,{name:l.name??n,schema:l.schema})}}function lCp(e){e.ir.apiVersion!=null&&e.builder.setApiVersion(e.ir.apiVersion),QTp(e),JTp(e),KTp(e),VTp(e),oCp(e),e.ir.basePath!=null&&e.builder.setBasePath(e.ir.basePath),e.ir.hasEndpointsMarkedInternal&&e.builder.addAudience(d6s);let t=aCp(e),r=t.sdkGroups;e.setInState(a2.Webhook),uCp(e),e.unsetInState(a2.Webhook),e.setInState(a2.Channel);for(let n of Object.values(e.ir.channels)){let a=EPn(n.groupName);GTp({channel:n,context:e,declarationFile:a})}e.unsetInState(a2.Channel);let i=coD({context:e,schemaIdsToExcludeFromServices:t.schemaIdsToExclude});cCp({schemas:e.ir.groupedSchemas.rootSchemas,schemaIdsToExclude:i,namespace:void 0,context:e});for(let[n,a]of Object.entries(e.ir.groupedSchemas.namespacedSchemas))cCp({schemas:a,schemaIdsToExclude:i,namespace:n,context:e});return e.ir.tags.orderedTagIds!=null&&e.ir.tags.orderedTagIds.length>0&&e.ir.tags.orderedTagIds.every(a=>r.has(a))&&e.builder.addNavigation({navigation:e.ir.tags.orderedTagIds}),e.builder.build()}function coD({context:e,schemaIdsToExcludeFromServices:t}){let r=e.getReferencedSchemaIds();if(r==null)return t;let i=new Set([...Object.keys(e.ir.groupedSchemas.rootSchemas),...Object.values(e.ir.groupedSchemas.namespacedSchemas).flatMap(a=>Object.keys(a))]),n=new Set(t);for(let a of i)r.includes(a)||n.add(a);return Array.from(n)}function p6s(e){let t=new OEo(e);return lCp(t)}var Zxi={enableUniqueErrorsPerEndpoint:!1,detectGlobalHeaders:!0,objectQueryParameters:!1,respectReadonlySchemas:!1,respectNullableSchemas:!1,onlyIncludeReferencedSchemas:!1,inlinePathParameters:!1};function _6s({options:e,overrides:t}){return{enableUniqueErrorsPerEndpoint:t?.enableUniqueErrorsPerEndpoint??e?.enableUniqueErrorsPerEndpoint??Zxi.enableUniqueErrorsPerEndpoint,detectGlobalHeaders:t?.detectGlobalHeaders??e?.detectGlobalHeaders??Zxi.detectGlobalHeaders,objectQueryParameters:t?.objectQueryParameters??e?.objectQueryParameters??Zxi.objectQueryParameters,respectReadonlySchemas:t?.respectReadonlySchemas??e?.respectReadonlySchemas??Zxi.respectReadonlySchemas,respectNullableSchemas:t?.respectNullableSchemas??e?.respectNullableSchemas??Zxi.respectNullableSchemas,onlyIncludeReferencedSchemas:t?.onlyIncludeReferencedSchemas??e?.onlyIncludeReferencedSchemas??Zxi.onlyIncludeReferencedSchemas,inlinePathParameters:t?.inlinePathParameters??e?.inlinePathParameters??Zxi.inlinePathParameters}}var TEo=class{args;constructor(t){this.args=t}convert({context:t,ir:r,settings:i,absoluteFilePath:n}){let a=p6s({taskContext:t,ir:r,options:_6s({overrides:{...i,respectReadonlySchemas:i?.respectReadonlySchemas??this.args.respectReadonlySchemas,respectNullableSchemas:i?.respectNullableSchemas??this.args.respectNullableSchemas,onlyIncludeReferencedSchemas:i?.onlyIncludeReferencedSchemas??this.args.onlyIncludeReferencedSchemas,inlinePathParameters:i?.inlinePathParameters??this.args.inlinePathParameters,objectQueryParameters:i?.objectQueryParameters??this.args.objectQueryParameters}}),authOverrides:this.args.generatorsConfiguration?.api?.auth!=null?{...this.args.generatorsConfiguration?.api}:void 0,environmentOverrides:this.args.generatorsConfiguration?.api?.environments!=null?{...this.args.generatorsConfiguration?.api}:void 0,globalHeaderOverrides:this.args.generatorsConfiguration?.api?.headers!=null?{...this.args.generatorsConfiguration?.api}:void 0});return{absoluteFilePath:n??this.args.absoluteFilePath,rootApiFile:{defaultUrl:a.rootApiFile["default-url"],contents:a.rootApiFile,rawContents:rp.dump(a.rootApiFile)},namedDefinitionFiles:{...od(a.definitionFiles,u=>({absoluteFilepath:n??this.args.absoluteFilePath,rawContents:rp.dump(u),contents:u})),[ry.of(W1)]:{absoluteFilepath:n??this.args.absoluteFilePath,rawContents:rp.dump(a.packageMarkerFile),contents:a.packageMarkerFile}},packageMarkers:{},importedDefinitions:{}}}};var Cla=class extends F8t{inlinePathParameters;objectQueryParameters;onlyIncludeReferencedSchemas;respectReadonlySchemas;respectNullableSchemas;exampleGeneration;converter;constructor(t){super(t),this.inlinePathParameters=t.inlinePathParameters,this.objectQueryParameters=t.objectQueryParameters,this.onlyIncludeReferencedSchemas=t.onlyIncludeReferencedSchemas,this.respectReadonlySchemas=t.respectReadonlySchemas,this.respectNullableSchemas=t.respectNullableSchemas,this.exampleGeneration=t.exampleGeneration,this.converter=new TEo(t)}async getDefinition({context:t,absoluteFilePath:r,relativePathToDependency:i},n){let a=await this.getOpenAPIIr({context:t,relativePathToDependency:i},n);return this.converter.convert({context:t,ir:a,settings:n,absoluteFilePath:r})}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new cSe({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:i,cliVersion:this.cliVersion})}};function qPn(e){if(e.settings==null)return;let t={detectGlobalHeaders:!0};return e.settings.unions==="v1"&&(t.discriminatedUnionV2=!0),t}var p6p=vi(Cqo(),1);var kU={BEARER_FORMAT:"x-bearer-format",ENUM_VAR_NAMES:"x-enum-varnames",INTERNAL:"x-internal",EXAMPLES:"x-examples",TAGS:"x-tags",REDOCLY_CODE_SAMPLES_KEBAB:"x-code-samples",REDOCLY_CODE_SAMPLES_CAMEL:"x-codeSamples"};var Cfa={of(e){return e}};var z3p={properties:{"stream-condition":{type:"string"},response:"Schema","response-stream":"Schema"},required:["stream-condition","response","response-stream"],extensionsPrefix:"x-"},n9s={id:"",typeExtension:{oas3:e=>({...e,XFernStreaming:z3p,Operation:{...e.Operation,properties:{...e.Operation?.properties,"x-fern-streaming":"XFernStreaming"}}})}},fd={SOURCE:Cfa.of("source"),SDK_METHOD_NAME:Cfa.of("x-fern-sdk-method-name"),SDK_GROUP_NAME:Cfa.of("x-fern-sdk-group-name"),REQUEST_NAME_V1:"x-request-name",REQUEST_NAME_V2:"x-fern-request-name",TYPE_NAME:"x-fern-type-name",BOOLEAN_LITERAL:"x-fern-boolean-literal",SERVER_NAME_V1:"x-name",SERVER_NAME_V2:"x-fern-server-name",BASE_PATH:"x-fern-base-path",GROUPS:Cfa.of("x-fern-groups"),OPENAPI_OVERIDES_FILEPATH:"x-fern-overrides-filepath",TYPE_DEFINITION:"x-fern-type",STREAMING:"x-fern-streaming",PAGINATION:"x-fern-pagination",WEBHOOK:"x-fern-webhook",ASYNC_CONFIG:"x-fern-async-config",SDK_VARIABLES:"x-fern-sdk-variables",SDK_VARIABLE:"x-fern-sdk-variable",PARAMETER_NAME:"x-fern-parameter-name",BASIC_AUTH_USERNAME_VARIABLE_NAME:"x-fern-username-variable-name",BASIC_AUTH_PASSWORD_VARIABLE_NAME:"x-fern-password-variable-name",BEARER_TOKEN_VARIABLE_NAME:"x-fern-token-variable-name",HEADER_VARIABLE_NAME:"x-fern-header-variable-name",FERN_ENUM:"x-fern-enum",AUDIENCES:"x-fern-audiences",IGNORE:"x-fern-ignore",AVAILABILITY:"x-fern-availability",RESPONSE_PROPERTY:"x-fern-sdk-return-value",RESOLUTIONS:"x-fern-resolutions",EXAMPLES:"x-fern-examples",FERN_BEARER_TOKEN:"x-fern-bearer",FERN_HEADER_AUTH:"x-fern-header",FERN_BASIC_AUTH:"x-fern-basic",FERN_GLOBAL_HEADERS:"x-fern-global-headers",FERN_IDEMPOTENCY_HEADERS:"x-fern-idempotency-headers",IDEMPOTENT:"x-fern-idempotent",FERN_PROPERTY_NAME:"x-fern-property-name",IS_UNDISCRIMINATED:"x-fern-undiscriminated",FERN_VERSION:"x-fern-version",ENCODING:"x-fern-encoding",TRANSPORT:"x-fern-transport"};var Y$={disableExamples:!1,discriminatedUnionV2:!1,useTitlesAsName:!0,audiences:void 0,optionalAdditionalProperties:!0,coerceEnumsToLiterals:!0,respectReadonlySchemas:!1,respectNullableSchemas:!1,onlyIncludeReferencedSchemas:!1,inlinePathParameters:!1,preserveSchemaIds:!1,objectQueryParameters:!1,shouldUseUndiscriminatedUnionsWithLiterals:!1,shouldUseIdiomaticRequestNames:!1,filter:void 0,asyncApiNaming:"v1",exampleGeneration:void 0,defaultFormParameterEncoding:"json"};function a9s({options:e,overrides:t}){return{disableExamples:t?.disableExamples??Y$.disableExamples,discriminatedUnionV2:t?.discriminatedUnionV2??e?.discriminatedUnionV2??Y$.discriminatedUnionV2,useTitlesAsName:t?.useTitlesAsName??e?.useTitlesAsName??Y$.useTitlesAsName,audiences:t?.audiences??e?.audiences??Y$.audiences,optionalAdditionalProperties:t?.optionalAdditionalProperties??e?.optionalAdditionalProperties??Y$.optionalAdditionalProperties,coerceEnumsToLiterals:t?.coerceEnumsToLiterals??e?.coerceEnumsToLiterals??Y$.coerceEnumsToLiterals,respectReadonlySchemas:t?.respectReadonlySchemas??e?.respectReadonlySchemas??Y$.respectReadonlySchemas,respectNullableSchemas:t?.respectNullableSchemas??e?.respectNullableSchemas??Y$.respectNullableSchemas,onlyIncludeReferencedSchemas:t?.onlyIncludeReferencedSchemas??e?.onlyIncludeReferencedSchemas??Y$.onlyIncludeReferencedSchemas,inlinePathParameters:t?.inlinePathParameters??e?.inlinePathParameters??Y$.inlinePathParameters,preserveSchemaIds:t?.preserveSchemaIds??Y$.preserveSchemaIds,shouldUseUndiscriminatedUnionsWithLiterals:t?.shouldUseUndiscriminatedUnionsWithLiterals??e?.shouldUseUndiscriminatedUnionsWithLiterals??Y$.shouldUseUndiscriminatedUnionsWithLiterals,shouldUseIdiomaticRequestNames:t?.shouldUseIdiomaticRequestNames??e?.shouldUseIdiomaticRequestNames??Y$.shouldUseIdiomaticRequestNames,objectQueryParameters:t?.objectQueryParameters??e?.objectQueryParameters??Y$.objectQueryParameters,filter:t?.filter??e?.filter??Y$.filter,asyncApiNaming:t?.asyncApiNaming??e?.asyncApiNaming??Y$.asyncApiNaming,exampleGeneration:t?.exampleGeneration??e?.exampleGeneration??void 0,defaultFormParameterEncoding:t?.defaultFormParameterEncoding??e?.defaultFormParameterEncoding??void 0}}var R3p={naming:"v1"};function bf(e,t){let r=Array.isArray(t)?t:[t];for(let i of r){let n=e[i];if(n!=null)return n}}function Bfa(e,t,r,i,n=[]){try{let a=bf(e,t);if(a!=null)return r.parse(a)}catch{let u=CCe(n).join(" -> ");i.error(`${u.length>0?`${u}: `:""}Failed to parse ${t}`)}}function MIi(e){let t=bf(e,"examples");return t!=null&&Array.isArray(t)?t:[]}function N3p({schema:e,logger:t}){return bf(e,fd.ENCODING)??void 0}function F3p(e){return bf(e,fd.FERN_ENUM)}function L3p({nameOverride:e,generatedName:t,title:r,schema:i,description:n,availability:a}){let u=bf(i,fd.SDK_GROUP_NAME),l=bf(i,fd.TYPE_DEFINITION);if(l!=null)return xfa({fernType:l,nameOverride:e,generatedName:t,title:r,description:n,availability:a,groupName:typeof u=="string"?[u]:u})}function xfa({fernType:e,nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u}){return yU({type:e,_default:void 0,validation:void 0,visitor:{primitive:l=>{switch(l.v1){case"BASE_64":return El.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:Jd.base64({example:void 0})});case"BOOLEAN":return El.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:Jd.boolean({default:void 0,example:void 0})});case"DATE":return El.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:Jd.date({example:void 0})});case"DATE_TIME":return El.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:Jd.datetime({example:void 0})});case"FLOAT":return El.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:Jd.float({example:void 0})});case"DOUBLE":return El.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:Jd.double({default:void 0,minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,example:void 0})});case"UINT":return El.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:Jd.uint({default:void 0,example:void 0})});case"INTEGER":return El.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:Jd.int({default:void 0,minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,example:void 0})});case"UINT_64":return El.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:Jd.uint64({default:void 0,example:void 0})});case"LONG":return El.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:Jd.int64({default:void 0,example:void 0})});case"STRING":case"UUID":case"BIG_INTEGER":return El.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:Jd.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})});default:Ko(l.v1)}},unknown:()=>El.unknown({nameOverride:t,generatedName:r,title:i,example:void 0,description:n,availability:a,groupName:u}),map:({keyType:l,valueType:d})=>l?.type==="primitive"&&d!=null?El.map({nameOverride:t,generatedName:r,title:i,key:l,value:d,description:n,availability:a,groupName:u,encoding:void 0,example:void 0,inline:void 0}):void 0,list:l=>l!=null?El.array({nameOverride:t,generatedName:r,title:i,value:l,description:n,availability:a,groupName:u,example:void 0,inline:void 0}):void 0,optional:l=>l!=null?El.optional({nameOverride:t,generatedName:r,title:i,value:l,description:n,availability:a,groupName:u,inline:void 0}):void 0,nullable:l=>l!=null?El.nullable({nameOverride:t,generatedName:r,title:i,value:l,description:n,availability:a,groupName:u,inline:void 0}):void 0,set:l=>l!=null?El.array({nameOverride:t,generatedName:r,title:i,value:l,description:n,availability:a,groupName:u,example:void 0,inline:void 0}):void 0,literal:l=>El.literal({nameOverride:t,generatedName:r,title:i,value:l._visit({string:d=>YB.string(d),boolean:d=>YB.boolean(d),_other:()=>{throw new Error("Unexpected literal type")}}),description:n,availability:a,groupName:u}),named:()=>{}}})}function U3p(e){let t=bf(e,fd.SOURCE);if(t!=null)return t.endsWith(".proto")?Kre.protobuf({file:t}):Kre.openapi({file:t})}function AIi(e){if(e!=null&&typeof e=="boolean")return e}function Kd(e){return e.$ref!=null}function V3p({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,additionalProperties:n,description:a,availability:u,wrapAsNullable:l,context:d,groupName:s,example:o,encoding:c,source:b,namespace:g}){return typeof n=="boolean"||mjn(n)?Bqo({nameOverride:e,generatedName:t,title:r,wrapAsNullable:l,description:a,availability:u,keySchema:{nameOverride:void 0,generatedName:`${t}Key`,title:void 0,description:void 0,availability:void 0,schema:Jd.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:void 0}),groupName:void 0},valueSchema:El.unknown({nameOverride:void 0,generatedName:`${t}Value`,title:void 0,description:void 0,availability:void 0,example:void 0,groupName:void 0}),groupName:s,example:o,encoding:c}):Bqo({nameOverride:e,generatedName:t,title:r,wrapAsNullable:l,description:a,availability:u,keySchema:{nameOverride:void 0,generatedName:`${t}Key`,title:void 0,description:void 0,availability:void 0,schema:Jd.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:void 0}),groupName:void 0},valueSchema:W3p(Pb(n,d.options.optionalAdditionalProperties?l:!1,d,[...i,"Value"],b,g,void 0,void 0,void 0)),groupName:s,example:o,encoding:c})}function W3p(e){switch(e.type){case"array":case"enum":case"map":case"object":e.inline=!0;break;case"literal":case"primitive":case"reference":case"unknown":break;case"nullable":case"optional":e.inline=!0,e.value=W3p(e.value);break;case"oneOf":e.value.inline=!0;break;default:Ko(e)}return e}function Bqo({nameOverride:e,generatedName:t,title:r,keySchema:i,valueSchema:n,wrapAsNullable:a,description:u,availability:l,groupName:d,example:s,encoding:o}){return a?El.nullable({nameOverride:e,generatedName:t,title:r,value:El.map({nameOverride:e,generatedName:t,title:r,description:u,availability:i.availability,key:i,value:n,groupName:d,encoding:o,example:s,inline:void 0}),description:u,availability:l,groupName:d,inline:void 0}):El.map({nameOverride:e,generatedName:t,title:r,description:u,availability:l,key:i,value:n,groupName:d,encoding:o,example:s,inline:void 0})}function mjn(e){return e==null?!1:typeof e=="boolean"?e:!Kd(e)&&Object.keys(e).length===0}function H3p({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,item:n,description:a,availability:u,wrapAsNullable:l,context:d,groupName:s,example:o,source:c,namespace:b}){let g=n==null?El.unknown({nameOverride:e,generatedName:t,title:r,description:void 0,availability:void 0,example:void 0,groupName:s}):Pb(n,!1,d,[...i,"Item"],c,b);return uDD({nameOverride:e,generatedName:t,title:r,groupName:s,itemSchema:g,wrapAsNullable:l,description:a,availability:u,example:o})}function uDD({nameOverride:e,generatedName:t,title:r,itemSchema:i,wrapAsNullable:n,description:a,availability:u,groupName:l,example:d}){return n?El.nullable({nameOverride:e,generatedName:t,title:r,value:El.array({nameOverride:e,generatedName:t,title:r,value:i,description:a,availability:u,groupName:l,example:d,inline:void 0}),description:a,availability:u,groupName:l,inline:void 0}):El.array({nameOverride:e,generatedName:t,title:r,value:i,description:a,availability:u,groupName:l,example:d,inline:void 0})}function nie(e){switch(bf(e,fd.AVAILABILITY)){case"deprecated":return $U.Deprecated;case"beta":return $U.Beta;case"generally-available":return $U.GenerallyAvailable;default:break}if(!Kd(e)&&e.deprecated)return $U.Deprecated}function o9s({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,availability:u,required:l,wrapAsNullable:d,discriminator:s,context:o,groupName:c,encoding:b,source:g,namespace:O}){let m=s.propertyName,w=Object.fromEntries(Object.entries(s.mapping??{}).map(([A,q])=>{let D=Pjn({$ref:q},!1,o,[q],b,g,O);return o.markReferencedByDiscriminatedUnion({$ref:q},m,1),[A,D]})),E=Object.entries(n).filter(([A])=>A!==m).map(([A,q])=>{let D=l!=null&&l.includes(A),C=Pb(q,!D,o,[...i,A],g,O);return{key:A,schema:C}});return $3p({nameOverride:e,generatedName:t,title:r,wrapAsNullable:d,properties:E,description:a,availability:u,discriminant:m,subtypes:w,groupName:c,source:g})}function u9s({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,availability:u,required:l,wrapAsNullable:d,discriminant:s,variants:o,context:c,groupName:b,encoding:g,source:O,namespace:m}){let w=Object.fromEntries(Object.entries(o).map(([A,q])=>{if(Kd(q)){let D=Pjn(q,!1,c,[q.$ref],g,O,m);return c.markReferencedByDiscriminatedUnion(q,s,1),[A,D]}else{let D=jjn(q,!1,c,[...i,A],g,O,m,new Set([s]));return[A,D]}})),E=Object.entries(n).filter(([A])=>A!==s).map(([A,q])=>{let D=l!=null&&l.includes(A),C=Pb(q,!D,c,[...i,A],O,m);return{key:A,schema:C}});return $3p({nameOverride:e,generatedName:t,title:r,wrapAsNullable:d,properties:E,description:a,availability:u,discriminant:s,subtypes:w,groupName:b,source:O})}function $3p({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,properties:n,description:a,availability:u,discriminant:l,subtypes:d,groupName:s,source:o}){return i?El.nullable({nameOverride:e,generatedName:t,title:r,value:El.oneOf(PY.discriminated({description:a,availability:u,discriminantProperty:l,nameOverride:e,generatedName:t,title:r,schemas:d,commonProperties:n,groupName:s,encoding:void 0,source:o,inline:void 0})),groupName:s,description:a,availability:u,inline:void 0}):El.oneOf(PY.discriminated({description:a,availability:u,discriminantProperty:l,nameOverride:e,generatedName:t,title:r,schemas:d,commonProperties:n,groupName:s,encoding:void 0,source:o,inline:void 0}))}function G3p(e){if(e.proto!=null)return Xmn.protobuf({typeName:e.proto.type})}function SYt({nameOverride:e,generatedName:t,title:r,fernEnum:i,enumVarNames:n,enumValues:a,_default:u,description:l,availability:d,wrapAsNullable:s,groupName:o,context:c,source:b,inline:g}){let O=cDD(n??[]),m=new Set(a),w=Array.from(m).map((A,q)=>{let D=i?.[A],C=O[q],R=SPn.test(A),$=D?.name??C,I=R?A:DPn(A);return $!=null&&!SPn.test($)&&(c?.logger.warn(`Enum name override ${$} is not a valid name. Falling back on ${I}.`),$=void 0),{nameOverride:$,generatedName:I,value:A,description:D?.description,availability:d,casing:{snake:D?.casing?.snake??void 0,pascal:D?.casing?.pascal??void 0,screamingSnake:D?.casing?.screamingSnake??void 0,camel:D?.casing?.camel??void 0}}}),E=u!=null?w.find(A=>A.value===u):void 0;return sDD({wrapAsNullable:s,nameOverride:e,generatedName:t,title:r,values:w,_default:E,description:l,availability:d,groupName:o,source:b,inline:g})}function sDD({wrapAsNullable:e,nameOverride:t,generatedName:r,title:i,values:n,_default:a,description:u,availability:l,groupName:d,source:s,inline:o}){return e?El.nullable({nameOverride:t,generatedName:r,title:i,value:El.enum({nameOverride:t,generatedName:r,title:i,values:n,description:u,default:a,availability:l,example:void 0,groupName:d,source:s,inline:o}),description:u,availability:l,groupName:d,inline:o}):El.enum({nameOverride:t,generatedName:r,title:i,values:n,description:u,availability:l,default:a,example:void 0,groupName:d,source:s,inline:o})}function cDD(e){if(e.length<=1||e[0]==null)return e;let t=e[0],r=0;for(;t[r]!=null&&e.every(i=>i[r]===t[r]);)r++;return e.map(i=>i.substring(r))}function Q3p({nameOverride:e,generatedName:t,title:r,format:i,_default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,description:o,availability:c,wrapAsNullable:b,example:g,groupName:O}){return i==="int64"?n5({nameOverride:e,generatedName:t,title:r,primitive:Jd.int64({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="uint32"?n5({nameOverride:e,generatedName:t,title:r,primitive:Jd.uint({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="uint64"?n5({nameOverride:e,generatedName:t,title:r,primitive:Jd.uint64({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):n5({nameOverride:e,generatedName:t,title:r,primitive:Jd.int({default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O})}function J3p(e){return typeof e=="string"?YB.string(e):typeof e=="boolean"?YB.boolean(e):YB.string(`${e}`)}function K3p({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,value:n,description:a,availability:u,groupName:l}){return i?El.nullable({nameOverride:e,generatedName:t,title:r,value:El.literal({nameOverride:e,generatedName:t,title:r,value:J3p(n),description:a,availability:u,groupName:l}),description:a,availability:u,groupName:l,inline:void 0}):El.literal({nameOverride:e,generatedName:t,title:r,value:J3p(n),description:a,availability:u,groupName:l})}function s9s({nameOverride:e,generatedName:t,title:r,format:i,_default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,description:o,availability:c,wrapAsNullable:b,example:g,groupName:O}){return i==null||i==="double"?n5({nameOverride:e,generatedName:t,title:r,primitive:Jd.double({default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="float"?n5({nameOverride:e,generatedName:t,title:r,primitive:Jd.float({example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="int32"?n5({nameOverride:e,generatedName:t,title:r,primitive:Jd.int({default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="int64"?n5({nameOverride:e,generatedName:t,title:r,primitive:Jd.int64({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="uint32"?n5({nameOverride:e,generatedName:t,title:r,primitive:Jd.uint({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="uint64"?n5({nameOverride:e,generatedName:t,title:r,primitive:Jd.uint64({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="time-delta"?n5({nameOverride:e,generatedName:t,title:r,primitive:Jd.float({example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):n5({nameOverride:e,generatedName:t,title:r,primitive:Jd.float({example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O})}var lDD={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="schemas",applyStrategy:e=>{let t=[e[3]??""];return{refUnderProcessing:e.slice(4),newBreadcrumbs:t}}},fDD={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="responses",applyStrategy:e=>{let t=[e[3]??""];return e=e.slice(4),{refUnderProcessing:e.slice(4),newBreadcrumbs:t}}},dDD={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="parameters",applyStrategy:e=>{let t=[e[3]??""];return e=e.slice(4),e[0]==="schema"&&(e=e.slice(1)),{refUnderProcessing:e,newBreadcrumbs:t}}},pDD={isApplicable:e=>e[0]==="properties",applyStrategy:e=>{let t=[e[1]??""];return{refUnderProcessing:e.slice(2),newBreadcrumbs:t}}},_DD={isApplicable:e=>e[0]==="items",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},hDD={isApplicable:e=>e[0]==="allOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},yDD={isApplicable:e=>e[0]==="anyOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},vDD={isApplicable:e=>e[0]==="oneOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})};function xqo(e){let t=e.split("/").map(a=>a.replace(/~1/g,"/")),r=[],i=[lDD,fDD,dDD,pDD,_DD,hDD,yDD,vDD],n;do{n=t;for(let a of i)if(a.isApplicable(t)){let{refUnderProcessing:u,newBreadcrumbs:l}=a.applyStrategy(t);t=u,r=[...r,...l]}}while(t.join("")!==n.join(""));return r}function s2(e,t){let i=e.map(n=>/^[^a-zA-Z0-9]+$/.test(n)?n:q3(vg(n))).join("");return/^\d/.test(i)?Ela(i)??i:i}function c9s(e){let t=e.join("_");return vg(t)}function kD(e){switch(e.type){case"object":return py.object({allOf:e.allOf,properties:e.properties.map(t=>gDD(t)),allOfPropertyConflicts:e.allOfPropertyConflicts,description:e.description,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName,additionalProperties:e.additionalProperties,availability:e.availability,source:e.source,inline:e.inline});case"array":return py.array({description:e.description,availability:e.availability,value:kD(e.value),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName,inline:e.inline});case"enum":return py.enum({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,values:e.values,default:e.default,groupName:e.groupName,source:e.source,inline:e.inline});case"literal":return py.literal({description:e.description,availability:e.availability,value:e.value,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName});case"nullable":return py.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:kD(e.value),groupName:e.groupName,inline:e.inline});case"optional":return py.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:kD(e.value),groupName:e.groupName,inline:e.inline});case"primitive":return py.primitive({description:e.description,availability:e.availability,schema:Y3p(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName});case"map":return py.map({description:e.description,availability:e.availability,key:py.primitive({description:e.key.description,availability:e.key.availability,schema:Y3p(e.key.schema),generatedName:e.key.generatedName,title:e.key.title,nameOverride:e.key.nameOverride,groupName:e.groupName}),value:kD(e.value),generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,groupName:e.groupName,encoding:e.encoding,inline:e.inline});case"reference":return py.reference({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schema:e.schema,groupName:e.groupName,source:e.source});case"oneOf":return py.oneOf(bDD(e.value));case"unknown":return py.unknown({nameOverride:e.nameOverride,generatedName:e.generatedName});default:Ko(e)}}function bDD(e){switch(e.type){case"discriminated":return QGr.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:kD(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,kD(r)])),groupName:e.groupName,encoding:e.encoding,source:e.source,inline:e.inline});case"undiscriminated":return QGr.undiscriminated({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schemas:e.schemas.map(t=>kD(t)),groupName:e.groupName,encoding:e.encoding,source:e.source,inline:e.inline});default:Ko(e)}}function Y3p(e){switch(e.type){case"string":return sj.string(e);case"base64":return sj.base64();case"boolean":return sj.boolean(e);case"date":return sj.date();case"datetime":return sj.datetime();case"double":return sj.double(e);case"float":return sj.float();case"int":return sj.int(e);case"int64":return sj.int64(e);case"uint":return sj.uint();case"uint64":return sj.uint64();default:Ko(e)}}function gDD(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:kD(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly,writeonly:e.writeonly}}function Iqo(e,t){return Zre(kD(e),kD(t))}function X3p({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,required:u,wrapAsNullable:l,allOf:d,context:s,propertiesToExclude:o,groupName:c,fullExamples:b,additionalProperties:g,availability:O,encoding:m,source:w,namespace:E}){let A=[...u??[]],q={...n},D=[],C=[];for(let U of d)if(Kd(U)){let H=s.resolveSchemaReference(U);if(H.discriminator!=null&&H.discriminator.mapping!=null)continue;if(H.oneOf!=null){for(let K of H.oneOf){let te=Kd(K)?s.resolveSchemaReference(K):K,fe=Pb(te,!1,s.DUMMY,i,w,E);fe.type==="object"&&D.push(...fe.properties.map(me=>me.schema.type!=="optional"&&me.schema.type!=="nullable"?{...me,schema:El.optional({nameOverride:void 0,generatedName:"",title:void 0,value:me.schema,description:void 0,availability:me.availability,groupName:void 0,inline:void 0})}:me))}continue}let k=Nli(U);if(k==null)continue;C.push({schemaId:k,convertedSchema:l9s(U,[k],w,s.options.preserveSchemaIds),properties:Z3p({schema:U,context:s,breadcrumbs:i,source:w,namespace:E})}),s.markSchemaAsReferencedByNonRequest(k)}else{let H=Pb(U,!1,s,i,w,E);H.type==="object"&&D.push(...H.properties)}let R={};for(let U of C)for(let[H,k]of Object.entries(U.properties)){let K=R[H];K!=null?(K.schemaIds.push(U.schemaId),K.schemas.some(fe=>Iqo(fe,k))||K.schemas.push(k)):R[H]={schemaIds:[U.schemaId],schemas:[k]}}let $=[];for(let[U,H]of Object.entries(R))H.schemaIds.length>1&&$.push({propertyKey:U,allOfSchemaIds:H.schemaIds,conflictingTypeSignatures:H.schemas.length>1});let I=Object.entries(q).map(([U,H])=>{let k=A.includes(U),K=bf(H,fd.AUDIENCES)??[],te=nie(H),fe=Kd(H)?!1:H.readOnly,me=Kd(H)?!1:H.writeOnly,be=bf(H,fd.FERN_PROPERTY_NAME),we=[...i,U],Ze=c9s(we),Mt=k?Pb(H,!1,s,we,w,E):El.optional({nameOverride:e,generatedName:Ze,title:r,description:void 0,availability:te,value:Pb(H,!1,s,we,w,E),groupName:c,inline:void 0}),De={};for(let Te of C){let xt=Te.properties[U];xt!=null&&!Iqo(Mt,xt)?De[Te.schemaId]={differentSchema:!0}:xt!=null&&(De[Te.schemaId]={differentSchema:!1})}return{key:U,schema:Mt,nameOverride:be,audiences:K,conflict:De,generatedName:c9s([...i,U]),availability:te,readonly:fe,writeonly:me}});return I.push(...D.map(U=>{let H=U.conflict;for(let k of C){let K=k.properties[U.key];K!=null&&!Iqo(U.schema,K)?H[k.schemaId]={differentSchema:!0}:K!=null&&(H[k.schemaId]={differentSchema:!1})}return{...U,conflict:H}})),ODD({nameOverride:e,generatedName:t,title:r,wrapAsNullable:l,properties:I.filter(U=>!o.has(U.key)),description:a,allOf:C.map(U=>U.convertedSchema),allOfPropertyConflicts:$,groupName:c,fullExamples:b,additionalProperties:g,availability:O,source:w})}function ODD({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,properties:n,description:a,allOf:u,allOfPropertyConflicts:l,groupName:d,fullExamples:s,additionalProperties:o,availability:c,source:b}){return i?El.nullable({nameOverride:e,generatedName:t,title:r,value:El.object({description:a,properties:n,nameOverride:e,generatedName:t,title:r,allOf:u,allOfPropertyConflicts:l,groupName:d,fullExamples:s,additionalProperties:mjn(o),availability:void 0,source:b,inline:void 0}),description:a,availability:c,groupName:d,inline:void 0}):El.object({description:a,properties:n,nameOverride:e,generatedName:t,title:r,allOf:u,allOfPropertyConflicts:l,groupName:d,fullExamples:s,additionalProperties:mjn(o),availability:c,source:b,inline:void 0})}function Z3p({schema:e,context:t,breadcrumbs:r,source:i,namespace:n}){let a={},[u,l]=Kd(e)?[t.resolveSchemaReference(e),xqo(e.$ref)]:[e,r];for(let d of u.allOf??[])a={...a,...Z3p({schema:d,context:t,breadcrumbs:l,source:i,namespace:n})};for(let[d,s]of Object.entries(u.properties??{})){let o=Pb(s,!1,t,[...l,d],i,n);a[d]=o}return a}function k3p({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,description:n,availability:a,wrapAsNullable:u,context:l,subtypes:d,groupName:s,encoding:o,source:c,subtypePrefixOverrides:b,namespace:g}){let O=e7p(d);return t7p({uniqueSubtypes:O,nameOverride:e,generatedName:t,title:r,wrapAsNullable:u,description:n,availability:a,groupName:s,context:l,encoding:o,source:c})}function wjn({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,description:n,availability:a,wrapAsNullable:u,context:l,subtypes:d,groupName:s,encoding:o,source:c,subtypePrefixOverrides:b,namespace:g}){let O=mDD({schemas:d}),m=d.flatMap((E,A)=>{if(!Kd(E)&&E.enum!=null&&l.options.coerceEnumsToLiterals&&E.type==="string")return E.enum.map(D=>El.literal({nameOverride:void 0,generatedName:s2([t,D],l.options.preserveSchemaIds),title:void 0,value:YB.string(String(D)),groupName:void 0,description:void 0,availability:D.availability}));let q=O[A];if(b!=null){let D=b[A];D!=null&&"name"in D&&(q=D.name)}return[Pb(E,!1,l,[...i,q??`${A}`],c,g)]}),w=e7p(m);return t7p({uniqueSubtypes:w,nameOverride:e,generatedName:t,title:r,wrapAsNullable:u,description:n,availability:a,groupName:s,context:l,encoding:o,source:c})}function e7p(e){let t=[];for(let r=0;r<e.length;++r){let i=e[r],n=!1;for(let a=r+1;a<e.length;++a){let u=e[a];if(i!=null&&u!=null&&Zre(i,u)){n=!0;break}}i!=null&&!n&&t.push(i)}return t}function t7p({uniqueSubtypes:e,nameOverride:t,generatedName:r,title:i,wrapAsNullable:n,description:a,availability:u,groupName:l,context:d,encoding:s,source:o}){if(Object.entries(e).every(([b,g])=>g.type==="literal")){let b={},g=[];return Object.entries(e).forEach(([O,m])=>{m.type==="literal"&&m.value.type==="string"&&(g.push(m.value.value),m.description!=null&&(b[m.value.value]={description:m.description}))}),SYt({nameOverride:t,generatedName:r,title:i,wrapAsNullable:n,description:a,availability:u,fernEnum:b,enumVarNames:void 0,enumValues:g,_default:void 0,groupName:l,context:d,source:o,inline:void 0})}return e.length===1&&e[0]!=null?e[0]:r7p({nameOverride:t,generatedName:r,title:i,wrapAsNullable:n,description:a,availability:u,subtypes:e,groupName:l,encoding:s,source:o})}function f9s({nameOverride:e,generatedName:t,title:r,description:i,availability:n,wrapAsNullable:a,context:u,groupName:l,discriminator:d,encoding:s,source:o,namespace:c}){let b=Object.entries(d.mapping??{}).map(([m,w],E)=>{let A={$ref:w},q=Pjn(A,!1,u,[w],s,o,c);return u.markSchemaWithDiscriminantValue(A,d.propertyName,m),q.type==="object"&&(q.properties={[d.propertyName]:El.literal({nameOverride:void 0,generatedName:s2([t,m],u.options.preserveSchemaIds),title:void 0,value:YB.string(m),groupName:void 0,description:void 0,availability:void 0}),...q.properties.filter(D=>D.key!==d.propertyName)}),q}),g=[];for(let m=0;m<b.length;++m){let w=b[m],E=!1;for(let A=m+1;A<b.length;++A){let q=b[A];if(w!=null&&q!=null&&Zre(w,q)){E=!0;break}}w!=null&&!E&&g.push(w)}if(Object.entries(g).every(([m,w])=>w.type==="literal")){let m={},w=[];return Object.entries(g).forEach(([E,A])=>{A.type==="literal"&&A.value.type==="string"&&(w.push(A.value.value),A.description!=null&&(m[A.value.value]={description:A.description}))}),SYt({nameOverride:e,generatedName:t,title:r,wrapAsNullable:a,description:i,availability:n,fernEnum:m,enumVarNames:void 0,enumValues:w,_default:void 0,groupName:l,context:u,source:o,inline:void 0})}return g.length===1&&g[0]!=null?g[0]:r7p({nameOverride:e,generatedName:t,title:r,wrapAsNullable:a,description:i,availability:n,subtypes:g,groupName:l,encoding:s,source:o})}function mDD({schemas:e}){let t={},r=0;for(let a of e){if(!Kd(a)){if(a.properties!=null&&Object.entries(a.properties).length>0){let u=Object.keys(a.properties),l={},d=u;for(let[s,o]of Object.entries(t)){let c=bGa(o,u);d=bGa(d,o),l[s]=c}l[r]=d,t=l}}r++}let i=[],n=0;for(let a of e){let u=t[n];if(u!=null&&u.length>0){let l=u.sort();if(l[0]!=null){i.push(l[0]),++n;continue}}Kd(a)?i.push(lli(n)??`${n}`):a.type==="array"||a.type==="boolean"||a.type==="integer"||a.type==="number"||a.type==="string"?i.push(""):i.push(lli(n)??`${n}`),++n}return i}function r7p({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,description:n,availability:a,subtypes:u,groupName:l,encoding:d,source:s}){return i?El.nullable({nameOverride:e,generatedName:t,title:r,value:El.oneOf(PY.undiscriminated({description:n,availability:a,nameOverride:e,generatedName:t,title:r,schemas:u,groupName:l,encoding:d,source:s,inline:void 0})),description:n,availability:a,groupName:l,inline:void 0}):El.oneOf(PY.undiscriminated({description:n,availability:a,nameOverride:e,generatedName:t,title:r,schemas:u,groupName:l,encoding:d,source:s,inline:void 0}))}function Sjn(e){if(e.default!=null&&typeof e.default=="string")return e.default}function zqo({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="number")return e.example;let i=MIi(e);for(let n of i??[])if(typeof n=="number")return n;if(r&&typeof r=="number")return r}function i7p({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="boolean")return e.example;let i=MIi(e);for(let n of i??[])if(typeof n=="boolean")return n;if(r&&typeof r=="boolean")return r}function oQr({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="string")return e.example;let i=MIi(e);for(let n of i??[])if(typeof n=="string")return n;if(r&&typeof r=="string")return r}function n7p({schema:e,logger:t,fallback:r}){if(e.example!=null&&Array.isArray(e.example))return e.example;let i=MIi(e);for(let n of i??[])if(Array.isArray(n))return n;if(r&&Array.isArray(r))return r}var qIi="#/components/schemas/";function Pb(e,t,r,i,n,a,u=!1,l=new Set,d){let s=U3p(e)??n,o=ADD({schema:e,logger:r.logger});if(Kd(e)){let c=Nli(e);return c!=null?(u?r.markSchemaAsReferencedByRequest(c):r.markSchemaAsReferencedByNonRequest(c),Pjn(e,t,r,i,o,s,a)):jjn(r.resolveSchemaReference(e),t,r,xqo(e.$ref),o,s,a,l,u,d)}return jjn(e,t,r,i,o,s,a,l,u,d)}function Pjn(e,t,r,i,n,a,u){let l=e.$ref.includes("properties")?jjn(r.resolveSchemaReference(e),t,r,i,n,a,u,new Set):El.reference(l9s(e,i,a,r.options.preserveSchemaIds));return t?El.nullable({title:void 0,nameOverride:void 0,generatedName:s2(i,r.options.preserveSchemaIds),value:l,description:void 0,availability:void 0,groupName:void 0,inline:void 0}):l}function PDD(e){if(e!=null&&!e.includes(" ")&&/^[a-zA-Z]+$/.test(e))return e}function jjn(e,t,r,i,n,a,u,l=new Set,d=!1,s){typeof e=="string"&&(e={type:e});let o=bf(e,fd.TYPE_NAME)??(r.options.useTitlesAsName?PDD(e.title):void 0),c=bf(e,fd.SDK_GROUP_NAME)??bf(e,kU.TAGS)?.[0],b=(typeof c=="string"?[c]:c)??[];b=r.resolveGroupName(b);let g=s2(i,r.options.preserveSchemaIds),O=e.title,m=e.description,w=nie(e),E=[];e.example!=null&&E.push({name:void 0,value:e.example,description:void 0});let A=bf(e,kU.EXAMPLES);A!=null&&Object.keys(A).length>0&&E.push(...Object.entries(A).map(([C,R])=>({name:R?.summary??C,value:R.value,description:R.description})));let q=MIi(e);q!=null&&Object.keys(q).length>0&&E.push(...q.map(C=>({name:void 0,value:C,description:void 0})));let D=L3p({schema:e,description:m,title:O,nameOverride:o,generatedName:g,availability:w});if(D!=null)return D;if(Array.isArray(e.type)){let C=e.type.indexOf("null"),R=C!==-1;e.type.length===1?e.type=e.type[0]:e.type.length===2&&R?(e.type.splice(C,1),e.type=e.type[0],e.nullable=!0):(R&&(e.type.splice(C,1),e.nullable=!0),e.oneOf==null?e.oneOf=e.type:e.oneOf.push(...e.type))}if(!t&&e.nullable===!0)return jjn(e,!0,r,i,n,a,u,l,d,s);if(e.enum!=null&&(e.type==="string"||e.type==null)){if(!Fqo(e.enum))return n5({nameOverride:o,generatedName:g,title:O,primitive:Jd.string({default:Sjn(e),minLength:e.minLength,maxLength:e.maxLength,pattern:e.pattern,format:e.format,example:oQr({schema:e,logger:r.logger,fallback:s})}),groupName:b,wrapAsNullable:t,description:m,availability:w});let C=F3p(e);return e.enum.length===1&&e.enum[0]!=null&&C==null?K3p({nameOverride:o,generatedName:g,title:O,wrapAsNullable:t,value:e.enum[0],description:m,availability:w,groupName:b}):SYt({nameOverride:o,generatedName:g,title:O,fernEnum:C,enumVarNames:bf(e,[kU.ENUM_VAR_NAMES]),enumValues:e.enum,_default:e.default,description:m,availability:w,wrapAsNullable:t,groupName:b,context:r,source:a,inline:void 0})}if(Fqo(e.type)&&e.type.length>1){let C=e.type.includes("null"),R=e.type.filter($=>$!=="null").map($=>({type:$,nullable:C}));return wjn({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,wrapAsNullable:t,context:r,subtypes:R,groupName:b,encoding:n,source:a,namespace:u})}if(e.type==="boolean"){let C=bf(e,fd.BOOLEAN_LITERAL);return C!=null?a7p({nameOverride:o,generatedName:g,title:O,literal:YB.boolean(C),wrapAsNullable:t,description:m,availability:w,groupName:b}):n5({nameOverride:o,generatedName:g,title:O,primitive:Jd.boolean({default:jDD(e.default),example:i7p({schema:e,logger:r.logger,fallback:s})}),wrapAsNullable:t,description:m,availability:w,groupName:b})}if(e.type==="number")return s9s({nameOverride:o,generatedName:g,title:O,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:AIi(e.exclusiveMinimum),exclusiveMaximum:AIi(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:w,wrapAsNullable:t,example:zqo({schema:e,logger:r.logger,fallback:s}),groupName:b});if(e.type==="integer")return Q3p({nameOverride:o,generatedName:g,title:O,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:AIi(e.exclusiveMinimum),exclusiveMaximum:AIi(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:w,wrapAsNullable:t,example:zqo({schema:e,logger:r.logger,fallback:s}),groupName:b});if(e.type==="float")return s9s({nameOverride:o,generatedName:g,title:O,format:"float",_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:AIi(e.exclusiveMinimum),exclusiveMaximum:AIi(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:w,wrapAsNullable:t,example:zqo({schema:e,logger:r.logger,fallback:s}),groupName:b});if(e.type==="string"){if(e.format==="date-time")return n5({nameOverride:o,generatedName:g,title:O,primitive:Jd.datetime({example:oQr({schema:e,logger:r.logger,fallback:s})}),wrapAsNullable:t,description:m,availability:w,groupName:b});if(e.format==="json-string")return El.unknown({nameOverride:o,generatedName:g,title:O,description:m,availability:w,groupName:b,example:void 0});let C=s7p(e,"const");return C!=null?a7p({nameOverride:o,generatedName:g,title:O,literal:YB.string(C),wrapAsNullable:t,description:m,availability:w,groupName:b}):n5({nameOverride:o,generatedName:g,title:O,primitive:Jd.string({default:Sjn(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:oQr({schema:e,logger:r.logger,fallback:s})}),groupName:b,wrapAsNullable:t,description:m,availability:w})}if(e.type==="array")return H3p({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,item:e.items,description:m,availability:w,wrapAsNullable:t,context:r,groupName:b,example:n7p({schema:e,logger:r.logger,fallback:s}),source:a,namespace:u});if(e.additionalProperties!=null&&e.additionalProperties!==!1&&Rqo(e))return V3p({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,additionalProperties:e.additionalProperties,description:m,availability:w,wrapAsNullable:t,context:r,groupName:b,encoding:n,example:e.example,source:a,namespace:u});if(e.type==="object"&&e.discriminator!=null&&e.discriminator.mapping!=null)return r.options.discriminatedUnionV2?f9s({nameOverride:o,generatedName:g,title:O,description:m,availability:w,wrapAsNullable:t,context:r,groupName:b,discriminator:e.discriminator,encoding:n,source:a,namespace:u}):o9s({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,discriminator:e.discriminator,properties:e.properties??{},required:e.required,wrapAsNullable:t,context:r,groupName:b,encoding:n,source:a,namespace:u});if(e.oneOf!=null&&e.oneOf.length>0){let C=bf(e,fd.IS_UNDISCRIMINATED);if(e.discriminator!=null&&e.discriminator.mapping!=null&&Object.keys(e.discriminator.mapping).length>0)return r.options.discriminatedUnionV2||C?f9s({nameOverride:o,generatedName:g,title:O,description:m,availability:w,wrapAsNullable:t,context:r,groupName:b,discriminator:e.discriminator,encoding:n,source:a,namespace:u}):o9s({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,discriminator:e.discriminator,properties:e.properties??{},required:e.required,wrapAsNullable:t,context:r,groupName:b,encoding:n,source:a,namespace:u});if(e.oneOf.length===1&&e.oneOf[0]!=null){let R=Pb(e.oneOf[0],t,r,i,a,u,d);return Djn(R,m,b)}else if(e.oneOf.length>1){if(e.oneOf.length===2&&e.oneOf[0]!=null&&e.oneOf[1]!=null){let U=e.oneOf[0],H=e.oneOf[1];if(!Kd(U)&&U.type==="null")return Pb(H,!0,r,i,a,u);if(!Kd(H)&&H.type==="null")return Pb(U,!0,r,i,a,u)}let R=DDD({schemas:e.oneOf});if(R!=null)return SYt({nameOverride:o,generatedName:g,title:O,fernEnum:void 0,enumVarNames:void 0,enumValues:R,_default:e.default,description:m,availability:w,wrapAsNullable:t,groupName:b,context:r,source:a,inline:void 0});let $=o7p({schemas:e.oneOf,context:r});if($!=null&&!r.options.discriminatedUnionV2&&!C)return u9s({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},required:e.required,description:m,availability:w,wrapAsNullable:t,discriminant:$.discriminant,variants:$.schemas,context:r,groupName:b,encoding:n,source:a,namespace:u});let I=e.oneOf.filter(U=>!Kd(U)&&U.type==="null").length>0;return wjn({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,wrapAsNullable:t||I,context:r,subtypes:e.oneOf.filter(U=>Kd(U)||U.type!=="null"),encoding:n,groupName:b,source:a,namespace:u})}}if(e.anyOf!=null&&e.anyOf.length>0){if(e.anyOf.length===1&&e.anyOf[0]!=null){let $=Pb(e.anyOf[0],t,r,i,a,u,d);return Djn($,m,b)}if(e.anyOf.length===2){let[$,I]=e.anyOf;if($!=null&&I!=null){if(!Kd($)&&$.type==="null"){let U=Pb(I,!0,r,i,a,u);return Djn(U,m,b)}else if(!Kd(I)&&I.type==="null"){let U=Pb($,!0,r,i,a,u);return Djn(U,m,b)}}}let C=o7p({schemas:e.anyOf,context:r});if(C!=null&&!r.options.discriminatedUnionV2)return u9s({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},required:e.required,description:m,availability:w,wrapAsNullable:t,discriminant:C.discriminant,variants:C.schemas,context:r,groupName:b,encoding:n,source:a,namespace:u});let R=e.anyOf.filter($=>!Kd($)&&$.type==="null").length>0;return wjn({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,wrapAsNullable:t||R,context:r,subtypes:e.anyOf.filter($=>Kd($)||$.type!=="null"),encoding:n,groupName:b,source:a,namespace:u})}if(e.allOf!=null||e.properties!=null){let C=[];for(let $ of e.allOf??[])(Kd($)||Object.keys($).length>0)&&C.push($);if((e.properties==null||Rqo(e))&&C.length===1&&C[0]!=null){let $=Pb(C[0],t,r,i,a,u,d);return Djn($,m,b)}let R=C.filter($=>{let I=Nqo($);return I||r.logger.warn(`Skipping non-object allOf element: ${JSON.stringify($)}`),I});if((e.properties==null||Rqo(e))&&R.length===1&&R[0]!=null){let $=Pb(R[0],t,r,i,a,u,d);return Djn($,m,b)}return X3p({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},description:m,required:e.required,wrapAsNullable:t,allOf:R,context:r,propertiesToExclude:l,groupName:b,fullExamples:E,additionalProperties:e.additionalProperties,availability:w,encoding:n,source:a,namespace:u})}if(e.type==="object"&&wDD(e)&&SDD(e)&&Rqo(e))return Bqo({nameOverride:o,generatedName:g,title:O,description:m,availability:w,wrapAsNullable:t,keySchema:{nameOverride:void 0,generatedName:`${g}Key`,title:void 0,description:void 0,availability:void 0,schema:Jd.string({default:Sjn(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:oQr({schema:e,logger:r.logger,fallback:s})}),groupName:b},valueSchema:El.unknown({nameOverride:void 0,generatedName:`${g}Value`,title:void 0,description:void 0,availability:void 0,example:void 0,groupName:b}),groupName:b,encoding:n,example:e.example});if(e.type==null){let C=e.example??e.default;return El.unknown({nameOverride:o,generatedName:g,title:O,description:m,availability:w,groupName:b,example:C})}throw new Error(`Failed to convert schema breadcrumbs=${JSON.stringify(i)} value=${JSON.stringify(e)}`)}function jDD(e){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.toLowerCase();if(t==="true")return!0;if(t==="false")return!1}}}function Nli(e){if(e.$ref.startsWith(qIi))return e.$ref.replace(qIi,"")}function l9s(e,t,r,i){let n=bf(e,fd.TYPE_NAME),a=s2(t,i),u=e.description,l=nie(e),d=Nli(e);if(d==null)throw new Error(`Invalid schema reference ${JSON.stringify(e)}`);return py.reference({generatedName:a,nameOverride:n,title:void 0,schema:d,description:u??void 0,availability:l,groupName:void 0,source:r})}function wDD(e){return e.oneOf==null||e.oneOf.length===0}function SDD(e){return e.allOf==null||e.allOf.length===0}function Rqo(e){return e.properties==null||CK(e.properties)===0}function Fqo(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function Djn(e,t,r){return e.type==="reference"?El.reference({...e,description:t,availability:e.availability,groupName:r}):e.type==="optional"?El.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:t,availability:e.availability,groupName:r,inline:void 0}):e.type==="nullable"?El.nullable({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:t,availability:e.availability,groupName:r,inline:void 0}):e}function Nqo(e){return Kd(e)||e.type==="object"||e.properties!=null?!0:e.allOf!=null?e.allOf.every(t=>Nqo(t)):e.oneOf!=null?e.oneOf.every(t=>Nqo(t)):e.anyOf!=null?e.anyOf.every(t=>Nqo(t)):!1}function a7p({literal:e,wrapAsNullable:t,groupName:r,description:i,availability:n,nameOverride:a,generatedName:u,title:l}){return t?El.nullable({nameOverride:a,generatedName:u,title:l,value:El.literal({nameOverride:a,generatedName:u,title:l,value:e,description:i,availability:n,groupName:r}),groupName:r,description:i,availability:n,inline:void 0}):El.literal({nameOverride:a,generatedName:u,title:l,value:e,groupName:r,description:i,availability:n})}function n5({primitive:e,wrapAsNullable:t,groupName:r,description:i,availability:n,generatedName:a,nameOverride:u,title:l}){return r=typeof r=="string"?[r]:r,t?El.nullable({nameOverride:u,generatedName:a,title:l,value:El.primitive({nameOverride:u,generatedName:a,title:l,schema:e,description:i,availability:n,groupName:r}),groupName:r,description:i,availability:n,inline:void 0}):El.primitive({nameOverride:u,generatedName:a,title:l,schema:e,description:i,availability:n,groupName:r})}function DDD({schemas:e}){let t=new Set;for(let r of e){if(Kd(r))return;if(r.enum!=null&&Fqo(r.enum))r.enum.forEach(i=>t.add(i));else return}return Array.from(t)}function o7p({schemas:e,context:t}){let r={};for(let i of e){let n=u7p({schema:i,context:t});for(let[a,u]of Object.entries(n)){let l=r[a];l!=null?l[u]=i:r[a]={[u]:i}}}for(let[i,n]of Object.entries(r))if(Object.keys(n).length===e.length)return{discriminant:i,schemas:n}}function u7p({schema:e,context:t}){let r=Kd(e)?t.resolveSchemaReference(e):e;return EDD({schema:r,context:t})}function EDD({schema:e,context:t}){let r={};if(e.anyOf!=null){for(let i of e.anyOf){let n=u7p({schema:i,context:t});for(let[a,u]of Object.entries(n??{}))r[a]=u}return r}for(let[i,n]of Object.entries(e.properties??{})){let a=Kd(n)?t.resolveSchemaReference(n):n;a.type==="string"&&a.enum!=null&&Fqo(a.enum)&&MDD(a.enum).length===1&&a.enum[0]!=null&&(r[i]=a.enum[0]);let u=s7p(a,"const");a.type==="string"&&u!=null&&(r[i]=u),i==="type"&&a.example!=null&&(r[i]=a.example)}return r}function MDD(e){if(!e)return[];let t=new Set;return e.forEach(r=>{typeof r=="string"?t.add(r.toLowerCase()):t.add(r)}),Array.from(t)}function s7p(e,t){let r=e[t];if(r!=null)return r}function ADD({schema:e,logger:t}){let r=N3p({schema:e,logger:t});if(r!=null)return G3p(r)}var Ejn=class{document;taskContext;logger;DUMMY;options;namespace;static MESSAGE_REFERENCE_PREFIX="#/components/messages/";constructor({document:t,taskContext:r,options:i,namespace:n}){this.document=t,this.taskContext=r,this.logger=r.logger,this.DUMMY=this,this.options=i,this.namespace=n}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveTags(t,r){if(this.namespace==null&&t==null&&r!=null)return[r];let i=[];if(this.namespace!=null){let n={type:"namespace",name:this.namespace};i.push(n)}return i.concat(t??[])}resolveSchemaReference(t){if(!t.$ref.startsWith(qIi))throw new Error(`Failed to resolve schema reference: ${t.$ref}`);let i=t.$ref.substring(qIi.length).split("/"),n=this.document.components;if(n==null||n.schemas==null)throw new Error("Document does not have components.schemas.");let[a,u,l]=i;if(a==null||a==="")throw new Error(`${t.$ref} cannot be resolved. No schema key provided.`);let d=n.schemas[a];if(d==null)throw new Error(`Schema "${a}" is undefined in document.components.schemas.`);if(Kd(d)&&(d=this.resolveSchemaReference(d)),u==="properties"&&l!=null){let s=d.properties?.[l];if(s==null)throw new Error(`Property "${l}" not found on "${a}". Full ref: ${t.$ref}`);Kd(s)?d=this.resolveSchemaReference(s):d=s}return d}referenceExists(t){let r=t.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return!1;i=i[n]}return!0}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}markReferencedByDiscriminatedUnion(t,r,i){}markSchemaWithDiscriminantValue(t,r,i){}};var Lqo=class extends Ejn{getExampleMessageReference(t){return`#/components/messages/${t.messageId}`}resolveMessageReference(t){let r="#/components/messages/",i=this.document.components;if(i==null||i.messages==null||!t.$ref.startsWith(r))throw new Error(`Failed to resolve message reference: ${t.$ref} in v2 components`);let n=t.$ref.substring(r.length),a=i.messages[n];if(a==null)throw new Error(`${t.$ref} is undefined`);return a}};function Mjn(e,t){let r={},i={};return e==null?r=t:i={[e]:t},{rootSchemas:r,namespacedSchemas:i}}function Fli(e){if(typeof e=="string")return Q0.primitive(i_.string(e));if(typeof e=="number")return Number.isInteger(e)?Q0.primitive(i_.int(e)):Q0.primitive(i_.double(e));if(typeof e=="boolean")return Q0.primitive(i_.boolean(e));if(Array.isArray(e)){let t=e.map(r=>Fli(r));return t.length===0?void 0:Q0.array(t.filter(r=>r!=null))}else if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string")){let t=[];for(let[r,i]of Object.entries(e)){let n=Fli(i);n!=null&&t.push({key:i_.string(r),value:n})}return Q0.map(t)}}function Ifa(e){if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string"))return e}function c7p(e){if(e!=null&&Array.isArray(e))return e}var Lli=class{schemas;nonRequestReferencedSchemas;context;constructor(t,r,i){this.schemas=t,this.nonRequestReferencedSchemas=r,this.context=i}buildExample({schema:t,exampleId:r,example:i,options:n,skipReadonly:a}){return this.buildExampleHelper({schema:t,visitedSchemaIds:new Set,exampleId:r,example:i,options:{...n,maxCheckerDepth:n.maxCheckerDepth??5},depth:0,skipReadonly:a??!1})}buildExampleHelper({exampleId:t,example:r,schema:i,depth:n,visitedSchemaIds:a,options:u,skipReadonly:l}){switch(i.type){case"enum":return typeof r=="string"&&l7p({schema:i,value:r})?Q0.enum(r):i.values[0]!=null?Q0.enum(i.values[0]?.value):void 0;case"literal":return Q0.literal(i.value);case"nullable":{if(r==null&&!this.hasExample(i.value,0,a,u)&&(u.ignoreOptionals||this.exceedsMaxDepth(n,u)))return;let d=this.buildExampleHelper({schema:i.value,visitedSchemaIds:a,exampleId:t,example:r,depth:n,options:u,skipReadonly:l});return d!=null&&d.type==="array"&&d.value.length===0||d!=null&&d.type==="map"&&d.value.length===0||d!=null&&d.type==="object"&&Object.keys(d.properties).length===0?void 0:d}case"optional":{if(r==null&&!this.hasExample(i.value,0,a,u)&&(u.ignoreOptionals||this.exceedsMaxDepth(n,u))||Object.is(r,null))return;let d=this.buildExampleHelper({schema:i.value,visitedSchemaIds:a,exampleId:t,example:r,depth:n,options:u,skipReadonly:l});return d!=null&&d.type==="array"&&d.value.length===0||d!=null&&d.type==="map"&&d.value.length===0||d!=null&&d.type==="object"&&Object.keys(d.properties).length===0?void 0:d}case"primitive":{let d=this.buildExampleFromPrimitive({schema:i.schema,example:r,options:u});return Q0.primitive(d)}case"reference":{let d=this.schemas[i.schema];if(d!=null&&!a.has(i.schema)){a.add(i.schema);let s=d?.type==="object"&&!this.nonRequestReferencedSchemas.has(i.schema),o=this.buildExampleHelper({example:r,schema:d,exampleId:t,visitedSchemaIds:a,depth:n,options:u,skipReadonly:s||this.context.options.respectReadonlySchemas?l:!1});return a.delete(i.schema),o}return}case"oneOf":switch(i.value.type){case"discriminated":{let d={},s={},o={},c=Ifa(r),b=c?.[i.value.discriminantProperty],g=i.value.schemas[b],O=[],m=this.getDiscriminatedUnionVariantSchema(i.value,c);m!=null&&O.push(m),O.push(...Object.entries(i.value.schemas));for(let w of O)if(b!=null&&g!=null&&g.type==="object"){s=this.getAllProperties(g),o=this.getAllRequiredProperties(g),d[i.value.discriminantProperty]=Q0.primitive(i_.string(b));break}else{let E=this.buildExampleHelper({exampleId:t,schema:w[1],example:void 0,visitedSchemaIds:a,depth:n,options:u,skipReadonly:l});if(E!=null){this.mergeExampleWith(E,d),d[i.value.discriminantProperty]=Q0.primitive(i_.string(w[0]));break}}for(let w of i.value.commonProperties){s[w.key]={schema:w.schema,readonly:!1};let E=this.getResolvedSchema(w.schema);E.type!=="optional"&&E.type!=="nullable"&&(o[w.key]=w.schema)}for(let[w,E]of Object.entries(s)){let A=w in o;if(A&&c?.[w]!=null){let q=this.buildExampleHelper({schema:E.schema,exampleId:t,example:c[w],visitedSchemaIds:a,depth:n+1,options:u,skipReadonly:l});if(q!=null)d[w]=q;else return}else{let q=this.buildExampleHelper({exampleId:t,schema:E.schema,example:c?.[w],visitedSchemaIds:a,depth:n+1,options:u,skipReadonly:l});if(q!=null)d[w]=q;else if(A)return}}return Q0.oneOf(eli.discriminated(d))}case"undiscriminated":{let d=this.getUnDiscriminatedUnionVariantSchema(i.value,r);if(d!=null)return this.buildExampleHelper({exampleId:t,example:r,schema:d,visitedSchemaIds:a,depth:n,options:u,skipReadonly:l});break}}return;case"unknown":if(r!=null){let d=Fli(r);if(d!=null)return Q0.unknown(d)}return u.ignoreOptionals||this.exceedsMaxDepth(n,u)?void 0:u.isParameter?Q0.primitive(i_.string(u.name??"string")):Q0.map([{key:i_.string("key"),value:Q0.primitive(i_.string("value"))}]);case"array":{let d=c7p(r),s=[];if(d!=null&&d.length>0)for(let o of d){let c=this.buildExampleHelper({exampleId:t,example:o,schema:i.value,depth:n+1,visitedSchemaIds:a,options:u,skipReadonly:l});c!=null&&s.push(c)}else if(i.example!=null&&i.example.length>0)for(let o of i.example){let c=this.buildExampleHelper({exampleId:t,example:o,schema:i.value,depth:n+1,visitedSchemaIds:a,options:u,skipReadonly:l});c!=null&&s.push(c)}else{let o=this.buildExampleHelper({exampleId:t,example:void 0,schema:i.value,depth:n+1,visitedSchemaIds:a,options:u,skipReadonly:l});o!=null&&s.push(o)}return Q0.array(s)}case"map":{let d=Ifa(r??i.example);if(d!=null&&Object.entries(d).length>0){let c=[];for(let[b,g]of Object.entries(d)){let O=this.buildExampleFromPrimitive({schema:i.key.schema,example:b,options:u}),m=this.buildExampleHelper({exampleId:t,example:g,schema:i.value,visitedSchemaIds:a,depth:n+1,options:u,skipReadonly:l});m!=null&&c.push({key:O,value:m})}return Q0.map(c)}if(i.key.schema.type==="string"&&i.value.type==="unknown")return Q0.map([{key:i_.string("key"),value:Q0.unknown(Q0.primitive(i_.string("value")))}]);let s=this.buildExampleFromPrimitive({schema:i.key.schema,example:void 0,options:{...u,name:"key"}}),o=this.buildExampleHelper({exampleId:t,example:void 0,schema:i.value,visitedSchemaIds:a,depth:n+1,options:{...u,name:"value"},skipReadonly:l});return o!=null?Q0.map([{key:s,value:o}]):Q0.map([])}case"object":{let d={},s=i.fullExamples?.find(g=>g.name===t)??i.fullExamples?.find(g=>g.name==null)??i.fullExamples?.[0],o=Ifa(r)??(s!=null?Ifa(s.value):{})??{},c=this.getAllProperties(i),b=this.getAllRequiredProperties(i);for(let[g,O]of Object.entries(c)){if(l&&O.readonly)continue;let m=g in b,w=Object.keys(o).includes(g),E=this.buildExampleHelper({schema:O.schema,exampleId:t,example:o[g],visitedSchemaIds:a,depth:n+1,options:{...u,name:g},skipReadonly:l});if(m&&E!=null)d[g]=E;else{if(m)return;(w&&E!=null||!u.ignoreOptionals&&E!=null)&&(d[g]=E)}}if(i.additionalProperties){for(let[g,O]of Object.entries(o))if(!(g in d)){let m=this.buildExampleHelper({schema:El.unknown({example:O,title:void 0,availability:void 0,description:void 0,generatedName:"",nameOverride:void 0,groupName:void 0}),exampleId:t,example:O,visitedSchemaIds:a,depth:n+1,options:{...u,name:g},skipReadonly:l});m!=null&&(d[g]=m)}}return Q0.object({properties:d})}default:Ko(i)}}mergeExampleWith(t,r){t._visit({array:Qo,enum:Qo,literal:Qo,map:i=>{for(let n of i){let a=n.key;a.type==="string"&&(r[a.value]=n.value)}},object:i=>{for(let[n,a]of Object.entries(i.properties))r[n]=a},oneOf:i=>{if(i.type==="discriminated")for(let[n,a]of Object.entries(i.value))r[n]=a;else this.mergeExampleWith(i.value,r)},primitive:Qo,unknown:Qo,_other:Qo})}getObjectSchema(t){if(t.type==="object")return t;if(t.type==="reference"){let r=this.schemas[t.schema];if(r!=null)return this.getObjectSchema(r)}}getDiscriminatedUnionVariantSchema(t,r){let i=r?.[t.discriminantProperty];if(i==null||typeof i!="string")return Object.entries(t.schemas)[0];let n=t.schemas[i];return n==null?Object.entries(t.schemas)[0]:[i,n]}getUnDiscriminatedUnionVariantSchema(t,r){return r==null?t.schemas[0]:t.schemas.map(a=>({schema:a,heuristic:this.calcExampleHeuristic(a,r)})).sort((a,u)=>u.heuristic-a.heuristic)[0]?.schema}calcExampleHeuristic(t,r){switch(t.type){case"literal":return t.value.value===r?5:0;case"enum":return l7p({schema:t,value:r})?5:0;case"object":{if(!Hj(r))return 0;let i=this.getAllProperties(t),n=0;for(let[a,u]of Object.entries(i))r[a]!=null?(n++,n+=this.calcExampleHeuristic(u.schema,r[a])):n--;return n}case"array":{if(!Array.isArray(r))return 0;let i=0;for(let n of r)i+=this.calcExampleHeuristic(t.value,n);return i}case"map":{if(!Hj(r))return 0;let i=0;for(let[,n]of Object.entries(r))i+=this.calcExampleHeuristic(t.value,n);return i}case"nullable":case"optional":return this.calcExampleHeuristic(t.value,r);case"reference":{let i=this.getResolvedSchema(t);return i==null?0:this.calcExampleHeuristic(i,r)}case"oneOf":return Object.values(t.value.schemas).map(n=>this.calcExampleHeuristic(n,r)).sort((n,a)=>a-n)[0]??0;case"primitive":return r==null?0:t.schema._visit({int:()=>typeof r=="number",int64:()=>typeof r=="number",uint:()=>typeof r=="number",uint64:()=>typeof r=="number",float:()=>typeof r=="number",double:()=>typeof r=="number",string:()=>typeof r=="string",datetime:()=>typeof r=="string",date:()=>typeof r=="string",base64:()=>typeof r=="string",boolean:()=>typeof r=="boolean",_other:()=>!0})?1:-1;default:return 0}}hasExample(t,r,i=new Set,n){if(this.exceedsMaxCheckerDepth(r,n))return!1;switch(t.type){case"array":return this.hasExample(t.value,r+1,i,n);case"enum":return t.example!=null;case"literal":return!1;case"map":return t.example!=null||t.key.schema.example!=null&&this.hasExample(t.value,r+1,i,n);case"object":{if(t.fullExamples!=null&&t.fullExamples.length>0)return!0;for(let u of t.properties)if(this.hasExample(u.schema,r+1,i,n))return!0;return!1}case"primitive":return t.schema.example!=null;case"reference":{let a=this.schemas[t.schema];if(a!=null&&!i.has(t.schema)){i.add(t.schema);let u=this.hasExample(a,r,i,n);return i.delete(t.schema),u}return!1}case"unknown":return t.example!=null;case"oneOf":return Object.values(t.value.schemas).some(a=>this.hasExample(a,r,i,n));default:return!1}}exceedsMaxCheckerDepth(t,r){return t>(r.maxCheckerDepth??0)}exceedsMaxDepth(t,r){return t>(r.maxDepth??0)}getAllProperties(t){let r={};for(let i of t.properties)r[i.key]={schema:i.schema,readonly:i.readonly??!1};for(let i of t.allOf){let n=this.schemas[i.schema];if(n==null)continue;let a=this.getResolvedSchema(n);a.type==="object"&&(r={...this.getAllProperties(a),...r})}return r}getAllRequiredProperties(t){let r={};for(let i of t.properties){let n=this.getResolvedSchema(i.schema);n.type!=="optional"&&n.type!=="nullable"&&(r[i.key]=i.schema)}for(let i of t.allOf){let n=this.schemas[i.schema];if(n==null)continue;let a=this.getResolvedSchema(n);a.type==="object"&&(r={...this.getAllRequiredProperties(a),...r})}return r}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}buildExampleFromPrimitive({example:t,schema:r,options:i}){switch(r.type){case"string":return t!=null&&typeof t=="string"?i_.string(t):r.example!=null?i_.string(r.example):i_.string(i.name??yg.STRING);case"base64":return t!=null&&typeof t=="string"?i_.base64(t):r.example!=null?i_.base64(r.example):i_.base64(yg.BASE64);case"boolean":return t!=null&&typeof t=="boolean"?i_.boolean(t):r.example!=null?i_.boolean(r.example):i_.boolean(yg.BOOLEAN);case"date":return t!=null&&typeof t=="string"?i_.date(t):r.example!=null?i_.date(r.example):i_.date(yg.DATE);case"datetime":return t!=null&&typeof t=="string"?i_.datetime(t):r.example!=null?i_.datetime(r.example):i_.datetime(yg.DATE_TIME);case"double":return t!=null&&typeof t=="number"?i_.double(t):r.example!=null?i_.double(r.example):i_.double(yg.DOUBLE);case"float":return t!=null&&typeof t=="number"?i_.float(t):r.example!=null?i_.float(r.example):i_.float(yg.FLOAT);case"int":return t!=null&&typeof t=="number"?i_.int(t):r.example!=null?i_.int(r.example):i_.int(yg.INT);case"int64":return t!=null&&typeof t=="number"?i_.int64(t):r.example!=null?i_.int64(r.example):i_.int64(yg.INT64);case"uint":return t!=null&&typeof t=="number"?i_.uint(t):r.example!=null?i_.uint(r.example):i_.uint(yg.UINT);case"uint64":return t!=null&&typeof t=="number"?i_.uint64(t):r.example!=null?i_.uint64(r.example):i_.uint64(yg.UINT64);default:Ko(r)}}};function l7p({schema:e,value:t}){return e.values.map(r=>r.value).includes(t)}function DYt(e){switch(e.type){case"object":return El.object({allOf:e.allOf,properties:e.properties.map(t=>TDD(t)),allOfPropertyConflicts:e.allOfPropertyConflicts,description:e.description,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,groupName:e.groupName,fullExamples:void 0,additionalProperties:e.additionalProperties,availability:e.availability,source:e.source,inline:void 0});case"array":return El.array({description:e.description,availability:e.availability,value:DYt(e.value),generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,groupName:e.groupName,example:void 0,inline:void 0});case"enum":return El.enum({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,values:e.values,default:e.default,groupName:e.groupName,example:void 0,source:e.source,inline:void 0});case"literal":return El.literal({description:e.description,availability:e.availability,value:e.value,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,groupName:e.groupName});case"nullable":return El.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:DYt(e.value),groupName:e.groupName,inline:void 0});case"optional":return El.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:DYt(e.value),groupName:e.groupName,inline:void 0});case"primitive":return El.primitive({description:e.description,availability:e.availability,schema:f7p(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName});case"map":return El.map({description:e.description,availability:e.availability,key:El.primitive({description:e.key.description,availability:e.key.availability,schema:f7p(e.key.schema),generatedName:e.key.generatedName,nameOverride:e.key.nameOverride,title:e.key.title,groupName:e.groupName}),value:DYt(e.value),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName,encoding:e.encoding,example:void 0,inline:void 0});case"reference":return El.reference({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schema:e.schema,groupName:e.groupName,source:e.source});case"oneOf":return El.oneOf(qDD(e.value));case"unknown":return El.unknown({nameOverride:e.nameOverride,generatedName:e.generatedName,title:void 0,example:void 0,groupName:void 0,description:void 0,availability:void 0});default:Ko(e)}}function qDD(e){switch(e.type){case"discriminated":return PY.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:DYt(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,DYt(r)])),groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});case"undiscriminated":return PY.undiscriminated({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:e.schemas.map(t=>DYt(t)),groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});default:Ko(e)}}function f7p(e){switch(e.type){case"string":return Jd.string({default:e.default,pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:void 0});case"base64":return Jd.base64({example:void 0});case"boolean":return Jd.boolean({default:e.default,example:void 0});case"date":return Jd.date({example:void 0});case"datetime":return Jd.datetime({example:void 0});case"double":return Jd.double({default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:e.exclusiveMinimum,exclusiveMaximum:e.exclusiveMaximum,multipleOf:e.multipleOf,example:void 0});case"float":return Jd.float({example:void 0});case"int":return Jd.int({default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:e.exclusiveMinimum,exclusiveMaximum:e.exclusiveMaximum,multipleOf:e.multipleOf,example:void 0});case"int64":return Jd.int64({default:e.default,example:void 0});case"uint":return Jd.uint({default:void 0,example:void 0});case"uint64":return Jd.uint64({default:void 0,example:void 0});default:Ko(e)}}function TDD(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:DYt(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly,writeonly:e.writeonly}}function Uqo(e){return e.type!=="optional"&&e.type!=="nullable"}function d9s(e){return e==="POST"||e==="PUT"||e==="PATCH"}function zfa(e){if(e.type==="full")return e.request==null&&e.response==null&&e.queryParameters==null&&e.pathParameters==null&&e.headers==null;{let t=e.value;return t.request==null&&t.response==null&&t["query-parameters"]==null&&t["path-parameters"]==null&&t.headers==null}}var Vqo=class{schemas;context;exampleTypeFactory;logger;constructor(t,r){this.schemas=t,this.context=r,this.schemas=t,this.exampleTypeFactory=new Lli(t,r.nonRequestReferencedSchemas,r),this.logger=r.logger}buildEndpointExample(t){this.logger.debug(`Building endpoint example for ${t.method.toUpperCase()} ${t.path}`);let r=BDD(t.request),i=xDD(t.response);if(r?.type==="unsupported"||i?.type==="unsupported")return[];let n=[];if(r!=null&&r.type==="present"){let c=this.isSchemaRequired(r.schema);if(r.examples.length===0){let b=this.exampleTypeFactory.buildExample({skipReadonly:d9s(t.method),schema:r.schema,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});b!=null&&n.push([void 0,b])}else for(let{name:b,value:g}of r.examples){let O=this.exampleTypeFactory.buildExample({skipReadonly:d9s(t.method),schema:r.schema,exampleId:b,example:g,options:{isParameter:!1,ignoreOptionals:!0}});O!=null&&n.push([b,O])}if(c&&n.length===0)return this.logger.trace(`Failed to generate required request example for ${t.method.toUpperCase()} ${t.path}`),[]}let a=[];if(i!=null&&i.type==="present"){let c=this.isSchemaRequired(i.schema);if(t.response?.type==="json"&&t.response.statusCode===204)a.push([void 0,TIe.withoutStreaming(Q0.object({properties:{}}))]);else if(i.examples.length===0){let b=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:i.schema,exampleId:void 0,example:void 0,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});b!=null&&(t.response?.type==="json"?a.push([void 0,TIe.withoutStreaming(b)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&a.push([void 0,TIe.withStreaming({sse:t.response?.type==="streamingSse",events:[b]})]))}else for(let{name:b,value:g}of i.examples){let O=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:i.schema,exampleId:b,example:g,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});O!=null&&(t.response?.type==="json"?a.push([b,TIe.withoutStreaming(O)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&a.push([void 0,TIe.withStreaming({sse:t.response?.type==="streamingSse",events:[O]})]))}if(c&&a.length===0)return this.logger.trace(`Failed to generate required response example for ${t.method.toUpperCase()} ${t.path}`),[]}let u=[];for(let c of t.pathParameters){let b=this.isSchemaRequired(c.schema),g=this.exampleTypeFactory.buildExample({schema:c.schema,exampleId:void 0,example:void 0,options:{name:c.name,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!EYt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for path parameter ${c.name} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),b&&g==null)return[];g!=null&&u.push({name:c.name,parameterNameOverride:c.parameterNameOverride,value:g})}let l=[];for(let c of t.queryParameters){let b=this.isSchemaRequired(c.schema),g=this.exampleTypeFactory.buildExample({schema:c.schema,exampleId:void 0,example:void 0,options:{name:c.name,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!EYt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for query parameter ${c.name} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),b&&g==null)return[];g!=null&&l.push({name:c.name,value:g})}let d=[];for(let c of t.headers){let b=this.isSchemaRequired(c.schema),g=this.exampleTypeFactory.buildExample({schema:c.schema,exampleId:void 0,example:void 0,options:{name:c.name,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!EYt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for header ${c.name} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),b&&g==null)return[];g!=null&&d.push({name:c.name,value:g})}let s=[];t.request!=null&&t.response!=null?s=CDD(n,a):t.request!=null?s=n.map(([c,b])=>({id:c,request:b,response:void 0})):t.response!=null&&(s=a.map(([c,b])=>({id:c,request:void 0,response:b})));let o=t.examples.filter(c=>zfa(c)).flatMap(c=>{if(c.type==="unknown"){if(c.value!=null){let b=c.value["code-samples"];if(b!=null)return this.convertCodeSamples(b)}return}else return c.codeSamples}).filter(c=>u0(c));return s.length===0?[L8t.full({name:void 0,description:void 0,pathParameters:u,queryParameters:l,headers:d,request:void 0,response:void 0,codeSamples:o})]:s.map(({id:c,request:b,response:g})=>L8t.full({name:c,description:void 0,pathParameters:u,queryParameters:l,headers:d,request:b,response:g,codeSamples:o}))}convertCodeSamples(t){return t.map(r=>"language"in r?GGr.language({name:r.name??void 0,description:r.docs??void 0,language:r.language,code:r.code,install:r.install??void 0}):GGr.sdk({name:r.name??void 0,description:r.docs??void 0,sdk:r.sdk==="c#"?GU.Csharp:r.sdk,code:r.code})).filter(u0)}isSchemaRequired(t){return Uqo(this.getResolvedSchema(t))}getResolvedSchema(t){return t}};function CDD(e,t){let r=[];if(e.length<=1){let[n,a]=e[0]??[];if(t.length===0)return r.push({id:n,request:a,response:void 0}),r;for(let[u,l]of t)r.push({id:u??n,request:a,response:l});return r}if(t.length<=1){let[n,a]=t[0]??[];if(t.length===0)return r.push({id:n,request:void 0,response:a}),r;for(let[u,l]of e)r.push({id:u??n,request:l,response:a});return r}let i=new Set;for(let[n,a]of e){let u=t.find(([d])=>d==null)?.[1]??t[0]?.[1];if(n==null){if(u==null)continue;r.push({id:void 0,request:a,response:u});continue}let l=!1;for(let d=0;d<t.length;d++){let[s,o]=t[d];s==null||i.has(d)||n===s&&(r.push({id:n,request:a,response:o}),s!=null&&i.add(d),l=!0)}!l&&u!=null&&r.push({id:n,request:a,response:u})}for(let n=0;n<t.length;n++){if(i.has(n))continue;let[a,u]=t[n],l=e.find(([d])=>d==null)?.[1]??e[0]?.[1];l!=null&&r.push({id:a,request:l,response:u})}return r}function BDD(e){if(e!=null)return e.type==="multipart"?{type:"present",schema:IDD(e),examples:[]}:e.type==="json"?{type:"present",schema:e.schema,examples:e.fullExamples??[]}:{type:"unsupported"}}function xDD(e){if(e!=null)return e.type!=="json"&&e.type!=="streamingJson"&&e.type!=="streamingSse"?{type:"unsupported"}:{type:"present",schema:e.schema,examples:e.fullExamples??[]}}function EYt(e){switch(e.type){case"primitive":case"enum":case"literal":return!0;case"unknown":return EYt(e);case"array":case"object":case"map":return!1;case"oneOf":switch(e.value.type){case"discriminated":return!1;case"undiscriminated":return EYt(e.value.value);default:return!1}default:Ko(e)}}function IDD(e){return El.object({properties:e.properties.map(t=>t.schema.type==="file"?null:{key:t.key,schema:DYt(t.schema.value),audiences:[],conflict:{},generatedName:t.key,nameOverride:void 0,availability:void 0,readonly:void 0,writeonly:void 0,inline:void 0}).filter(u0),allOf:[],allOfPropertyConflicts:[],fullExamples:void 0,description:e.description,nameOverride:void 0,generatedName:"",title:void 0,groupName:void 0,additionalProperties:!1,availability:void 0,source:e.source,inline:void 0})}var Ajn=class{exampleTypeFactory;schemas;constructor(t,r){this.exampleTypeFactory=new Lli(t,new Set,r),this.schemas=t}buildWebsocketSessionExamplesForExtension({context:t,extensionExamples:r,publish:i,subscribe:n,handshake:a,source:u,namespace:l}){let d=[];for(let s of r){let o=[];for(let g of a.queryParameters){let O=this.isSchemaRequired(g.schema),m=this.exampleTypeFactory.buildExample({schema:g.schema,exampleId:void 0,example:s.queryParameters?.[g.name],options:{name:g.name,isParameter:!0,ignoreOptionals:!0}});m!=null&&!EYt(m)&&(m=void 0),!(O&&m==null)&&m!=null&&o.push({name:g.name,value:m})}let c=[];for(let g of a.headers){let O=this.isSchemaRequired(g.schema),m=this.exampleTypeFactory.buildExample({schema:g.schema,exampleId:void 0,example:s.headers?.[g.name],options:{name:g.name,isParameter:!0,ignoreOptionals:!0}});m!=null&&!EYt(m)&&(m=void 0),!(O&&m==null)&&m!=null&&c.push({name:g.name,value:m})}let b=[];for(let g of s.messages){let O=t.getExampleMessageReference(g),m=t.resolveMessageReference({$ref:O}),w=Kd(m.payload)?t.resolveSchemaReference(m.payload):m.payload,E=this.exampleTypeFactory.buildExample({schema:Pb(w,!1,t,[g.messageId],u,l),exampleId:void 0,example:g.value,options:{isParameter:!1,ignoreOptionals:!0}});E!=null&&b.push({messageType:g.type,payload:E,description:void 0})}d.push({name:s.summary,queryParameters:o,headers:c,description:s.description,messages:b})}return d}buildWebsocketSessionExample({publish:t,subscribe:r,handshake:i}){let n={name:void 0,queryParameters:[],headers:[],description:void 0,messages:[]},a=[];for(let l of i.queryParameters){let d=this.isSchemaRequired(l.schema),s=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(s!=null&&!EYt(s)&&(s=void 0),d&&s==null)return;s!=null&&a.push({name:l.name,value:s})}let u=[];for(let l of i.headers){let d=this.isSchemaRequired(l.schema),s=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(s!=null&&!EYt(s)&&(s=void 0),d&&s==null)return;s!=null&&u.push({name:l.name,value:s})}if(t!=null){let l=this.exampleTypeFactory.buildExample({schema:t,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});l!=null&&n.messages.push({messageType:"publish",payload:l,description:void 0})}if(r!=null){let l=this.exampleTypeFactory.buildExample({schema:r,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});l!=null&&n.messages.push({messageType:"subscribe",payload:l,description:void 0})}return n}isSchemaRequired(t){return Uqo(this.getResolvedSchema(t))}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}};var RY={FERN_PARAMETER_OPTIONAL:"x-fern-optional",FERN_DISPLAY_NAME:"x-fern-display-name",FERN_SDK_GROUP_NAME:"x-fern-sdk-group-name",FERN_EXAMPLES:"x-fern-examples",BASE_PATH:"x-fern-base-path",FERN_ENUM:"x-fern-enum",IGNORE:"x-fern-ignore"};function Wqo(e){return bf(e,RY.FERN_EXAMPLES)??[]}function Hqo(e,t){return t.includes("://")?t:`${e}://${t}`}function $qo(e){return e.startsWith("/")?e:"/"+e}function _7p({context:e,breadcrumbs:t,source:r,asyncApiOptions:i,document:n}){let a={},u={};for(let[s,o]of Object.entries(n.components?.schemas??{})){let c=Pb(o,!1,e,[s],r,e.namespace);a[s]=c}let l=new Ajn(a,e),d={};for(let[s,o]of Object.entries(n.servers??{}))d[s]={name:s,url:Hqo(o.protocol,o.url)};for(let[s,o]of Object.entries(n.channels??{})){let c=bf(o,RY.IGNORE);if(c!=null&&c){e.logger.debug(`Channel ${s} is marked with x-fern-ignore. Skipping.`);continue}let b=[];if(o.parameters!=null)for(let[E,A]of Object.entries(o.parameters??{}))b.push({name:E,description:A.description,parameterNameOverride:void 0,schema:A.schema!=null?Pb(A.schema,!1,e,t,r,e.namespace):El.primitive({schema:Jd.string({default:void 0,pattern:void 0,format:void 0,maxLength:void 0,minLength:void 0,example:void 0}),description:void 0,availability:void 0,generatedName:"",title:void 0,groupName:void 0,nameOverride:void 0}),variableReference:void 0,availability:nie(A),source:r});let g=[],O=[];if(o.bindings?.ws!=null){if(o.bindings.ws.headers!=null){let E=o.bindings.ws.headers.required??[];for(let[A,q]of Object.entries(o.bindings.ws.headers.properties??{})){let D=Kd(q)?e.resolveSchemaReference(q):q;g.push({name:A,schema:Pb(D,!E.includes(A),e,[...t,A],r,e.namespace),description:D.description,parameterNameOverride:void 0,env:void 0,availability:nie(D),source:r})}}if(o.bindings.ws.query!=null){let E=o.bindings.ws.query.required??[];for(let[A,q]of Object.entries(o.bindings.ws.query.properties??{})){let D=Kd(q)?e.resolveSchemaReference(q):q;O.push({name:A,schema:Pb(D,!E.includes(A),e,[...t,A],r,e.namespace),description:D.description,parameterNameOverride:void 0,availability:nie(D),source:r})}}}let m;o.publish!=null&&("oneOf"in o.publish.message?m=d7p({generatedName:o.publish.operationId??"PublishEvent",event:o.publish,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:i}):m=p7p({action:"Publish",channelPath:s,message:o.publish.message,context:e,source:r}));let w;if(o.subscribe!=null&&("oneOf"in o.subscribe.message?w=d7p({generatedName:o.subscribe.operationId??"SubscribeEvent",event:o.subscribe,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:i}):w=p7p({action:"Subscribe",channelPath:s,message:o.subscribe.message,context:e,source:r})),g.length>0||O.length>0||m!=null||w!=null){let E=Wqo(o),A=[];if(E.length>0)A=l.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:E,handshake:{headers:g,queryParameters:O},publish:m,subscribe:w,source:r,namespace:e.namespace});else{let q=l.buildWebsocketSessionExample({handshake:{headers:g,queryParameters:O},publish:m,subscribe:w});q!=null&&A.push(q)}u[s]={audiences:bf(o,fd.AUDIENCES)??[],handshake:{headers:g.map(q=>({...q,schema:kD(q.schema),env:q.env})),queryParameters:O.map(q=>({...q,schema:kD(q.schema)})),pathParameters:b.map(q=>({...q,parameterNameOverride:void 0,schema:kD(q.schema)}))},groupName:[bf(o,RY.FERN_SDK_GROUP_NAME)??s],publish:m!=null?kD(m):m,subscribe:w!=null?kD(w):w,servers:(o.servers?.map(q=>d[q])??Object.values(d)).filter(q=>q!=null),summary:bf(o,RY.FERN_DISPLAY_NAME),path:$qo(s),description:void 0,examples:A,source:r}}}return{groupedSchemas:Mjn(e.namespace,a),channels:u??void 0,servers:Object.values(d),basePath:bf(n,RY.BASE_PATH)}}function d7p({generatedName:e,event:t,context:r,breadcrumbs:i,source:n,options:a,asyncApiOptions:u}){if("oneOf"in t.message&&t.message.oneOf!=null){let l=[],d=[];for(let s of t.message.oneOf){let o,c={type:"notFound"};if(Kd(s)){let b=r.resolveMessageReference(s);!Kd(b.payload)&&u.naming==="v2"?(c=b.name?{type:"name",name:b.name}:c,o={...b.payload,title:b.name??b.payload.title,description:b.name??b.payload.description}):o=b.payload}else o=s;d.push(c),l.push(o)}return wjn({description:t.description??t.message.description,availability:nie(t.message),subtypes:l,nameOverride:t.operationId,generatedName:e,title:t.message.title,groupName:void 0,wrapAsNullable:!1,breadcrumbs:i,context:r,encoding:void 0,source:n,namespace:r.namespace,subtypePrefixOverrides:u.naming==="v2"?d:[]})}}function p7p({action:e,channelPath:t,message:r,context:i,source:n}){if(r.payload!=null){let a=r.payload;return Kd(r.payload)&&(a=i.resolveSchemaReference(r.payload)),Kd(a)?Pb(a,!1,i,[t,e],n,i.namespace):Pb(a,!1,i,[t,e],n,i.namespace)}}var Gqo=class extends Ejn{getExampleMessageReference(t){return`#/channels/${t.channelId}/messages/${t.messageId}`}resolveMessageReference(t){let r="#/channels/",i="#/components/messages/";if(t.$ref.startsWith(r)){let l=t.$ref.split("/"),d=l[2],s=l[4];if(d==null||s==null||!this.document.channels?.[d])throw new Error(`Failed to resolve message reference ${t.$ref} in channel ${d}`);let c=this.document.channels[d].messages?.[s];if(c==null)throw new Error(`${t.$ref} is undefined`);return{name:s,...c}}let n=this.document.components;if(!t.$ref.startsWith(i)||!n?.messages)throw new Error(`Failed to resolve message reference: ${t.$ref} in v3 components`);let a=t.$ref.substring(i.length),u=n.messages[a];if(u==null)throw new Error(`${t.$ref} is undefined`);return{name:a,...u}}};var h7p="#/channels/",y7p="#/servers/",p9s="$message.";function b7p({context:e,breadcrumbs:t,source:r,asyncApiOptions:i,document:n}){let a={},u={},l={},d=[],s={};for(let[m,w]of Object.entries(n.components?.schemas??{}))a[m]=Pb(w,!1,e,[m],r,e.namespace);for(let[m,w]of Object.entries(n.channels??{}))if(u[m]||(u[m]={}),w.messages)for(let[E,A]of Object.entries(w.messages))A&&A.payload!=null&&(l[E]||(l[E]=[]),l[E].push({channelId:m,payload:A.payload}));for(let[m,w]of Object.entries(l))if(w.length===1){let E=w[0],A=E.channelId;u[A]=u[A]||{},u[A][m]=Pb(E.payload,!1,e,[m],r,e.namespace)}else{d.push(m);for(let{channelId:E,payload:A}of w){let q=`${E}_${m}`;u[E]||(u[E]={}),u[E][q]=Pb(A,!1,e,[q],r,e.namespace)}}let o=Object.values(u).reduce((m,w)=>({...m,...w}),{}),c=new Ajn(o,e),b={};for(let[m,w]of Object.entries(n.servers??{}))b[m]={name:m,url:Hqo(w.protocol,w.host)};let g={};for(let[m,w]of Object.entries(n.operations??{})){if(bf(w,RY.IGNORE))continue;let E=zDD(w);if(g[E]||(g[E]={subscribe:[],publish:[]}),w.action==="receive")g[E].subscribe.push(...w.messages);else if(w.action==="send")g[E].publish.push(...w.messages);else throw new Error(`Operation ${m} has an invalid action: ${w.action}`)}let O={};for(let[m,w]of Object.entries(g)){O[m]={subscribe:void 0,publish:void 0};let E=m.split("/").pop()??m,A=E.charAt(0).toUpperCase()+E.slice(1);w.subscribe.length>0&&u[m]!=null&&(O[m].subscribe=v7p({generatedName:A+"SubscribeEvent",channelPath:m,messages:w.subscribe,breadcrumbs:t,context:e,source:r,messageSchemas:u[m],duplicatedMessageIds:d})),w.publish.length>0&&u[m]!=null&&(O[m].publish=v7p({generatedName:A+"PublishEvent",channelPath:m,messages:w.publish,breadcrumbs:t,context:e,source:r,messageSchemas:u[m],duplicatedMessageIds:d}))}for(let[m,w]of Object.entries(n.channels??{})){if(bf(w,RY.IGNORE))continue;let E=[],A=[],q=[];if(w.parameters!=null)for(let[D,C]of Object.entries(w.parameters)){let{type:R,parameterKey:$}=RDD(C.location),I=bf(C,RY.FERN_PARAMETER_OPTIONAL),U=q3(vg(m))+q3(vg(D)),H=bf(C,RY.FERN_ENUM),k=C.enum!=null&&Array.isArray(C.enum)?FDD({parameterName:U,fernEnum:H,parameterDescription:C.description,enumValues:C.enum,defaultValue:C.default,context:e,source:r}):El.primitive({schema:Jd.string({default:C.default,pattern:void 0,format:void 0,maxLength:void 0,minLength:void 0,example:C.examples?.[0]}),description:void 0,availability:void 0,generatedName:"",title:U,groupName:void 0,nameOverride:void 0});I&&(k=El.optional({value:k,description:void 0,availability:void 0,generatedName:"",title:U,groupName:void 0,nameOverride:void 0,inline:void 0}));let K={name:$,description:C.description,parameterNameOverride:void 0,schema:k,variableReference:void 0,availability:nie(C),source:r};R==="header"?E.push({...K,env:void 0}):R==="path"?A.push(K):R==="payload"&&q.push(K)}if(E.length>0||q.length>0||O[m]!=null&&(O[m].publish!=null||O[m].subscribe!=null)){let D=Wqo(w),C=[];if(D.length>0)C=c.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:D,handshake:{headers:E,queryParameters:q},publish:O[m]?.publish,subscribe:O[m]?.subscribe,source:r,namespace:e.namespace});else{let R=c.buildWebsocketSessionExample({handshake:{headers:E,queryParameters:q},publish:O[m]?.publish,subscribe:O[m]?.subscribe});R!=null&&C.push(R)}s[m]={audiences:bf(w,fd.AUDIENCES)??[],handshake:{headers:E.map(R=>({...R,schema:kD(R.schema),env:R.env})),queryParameters:q.map(R=>({...R,schema:kD(R.schema)})),pathParameters:A.map(R=>({...R,parameterNameOverride:void 0,schema:kD(R.schema)}))},groupName:[bf(w,RY.FERN_SDK_GROUP_NAME)??m],publish:O[m]?.publish!=null?kD(O[m].publish):void 0,subscribe:O[m]?.subscribe!=null?kD(O[m].subscribe):void 0,summary:bf(w,RY.FERN_DISPLAY_NAME),servers:w.servers?.map(R=>NDD(b,R))??Object.values(b),path:w.address??$qo(m),description:void 0,examples:C,source:r}}}return{groupedSchemas:Mjn(e.namespace,a),channels:s,servers:Object.values(b),basePath:bf(n,RY.BASE_PATH)}}function zDD(e){if(!e.channel.$ref.startsWith(h7p))throw new Error(`Failed to resolve channel path from operation ${e.channel.$ref}`);return e.channel.$ref.substring(h7p.length)}function RDD(e){try{let[t,r]=e.split("#/");if(t==null||r==null)throw new Error(`Invalid location format: ${e}; unable to parse message type and parameter key`);if(!t.startsWith(p9s))throw new Error(`Invalid location format: ${e}; expected ${p9s} prefix`);let i=t.substring(p9s.length);if(i!=="header"&&i!=="path"&&i!=="payload")throw new Error(`Invalid message type: ${i}. Must be one of: header, path, payload`);return{type:i,parameterKey:r}}catch{throw new Error(`Invalid location format: ${e}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`)}}function NDD(e,t){if(!t.$ref.startsWith(y7p))throw new Error(`Failed to resolve server name from server ref ${t.$ref}`);let r=t.$ref.substring(y7p.length),i=e[r];if(i==null)throw new Error(`Failed to find server with name ${r}`);return i}function FDD({parameterName:e,fernEnum:t,parameterDescription:r,enumValues:i,defaultValue:n,context:a,source:u}){return SYt({nameOverride:void 0,generatedName:e,title:void 0,wrapAsNullable:!1,description:r??void 0,availability:void 0,fernEnum:t??{},enumVarNames:void 0,enumValues:i,_default:n,groupName:void 0,context:a,source:u,inline:void 0})}function v7p({generatedName:e,channelPath:t,messages:r,context:i,breadcrumbs:n,source:a,messageSchemas:u,duplicatedMessageIds:l}){if(r.length>0){let d=[];for(let s of r){let o=i.resolveMessageReference(s),c;l.some(g=>g===o.name)?c=`${t}_${o.name}`:c=o.name;let b=u[c];b!=null&&d.push(b)}return k3p({description:void 0,availability:void 0,subtypes:d,nameOverride:void 0,generatedName:e,title:void 0,groupName:void 0,wrapAsNullable:!1,breadcrumbs:n,context:i,encoding:void 0,source:a,namespace:i.namespace,subtypePrefixOverrides:[]})}}function g7p({document:e,taskContext:t,options:r,source:i,asyncApiOptions:n,namespace:a}){let u=[];if(a!=null&&u.push(a),parseFloat(e.asyncapi)<3){let l=e;l.tags?.[0]!=null?u.push(l.tags[0].name):n.naming!=="v2"&&u.push("websocket");let d=new Lqo({document:l,taskContext:t,options:r,namespace:a});return _7p({context:d,breadcrumbs:u,source:i,asyncApiOptions:n,document:l})}else{let l=e,d=new Gqo({document:l,taskContext:t,options:r,namespace:a});return b7p({context:d,breadcrumbs:u,source:i,asyncApiOptions:n,document:l})}}function O7p(e){let t=LDD(e),r={};return _9s({obj:t,occurrences:r,breadcrumbs:[]}),r}function _9s({obj:e,occurrences:t,breadcrumbs:r}){if(e!=null){if(Array.isArray(e)){for(let i of e)_9s({obj:i,occurrences:t,breadcrumbs:r});return}if(typeof e=="object"){if(e.$ref!=null&&typeof e.$ref=="string"){let i=e.$ref;t[i]==null?t[i]=1:t[i]+=1;return}for(let i in e)_9s({obj:e[i],occurrences:t,breadcrumbs:[...r,i]})}}}function LDD(e){return{...e,paths:Object.fromEntries(Object.entries(e.paths??{}).map(([t,r])=>[t,{...r,get:r?.get!=null?Rfa(r.get):void 0,put:r?.put!=null?Rfa(r.put):void 0,post:r?.post!=null?Rfa(r.post):void 0,patch:r?.patch!=null?Rfa(r.patch):void 0,delete:r?.delete!=null?Rfa(r.delete):void 0}]))}}function Rfa(e){return{...e,requestBody:e.requestBody!=null?Kd(e.requestBody)?e.requestBody:UDD(e.requestBody):void 0}}function UDD(e){let t,r;for(let i in e.content){let n=zB.parse(i);n!=null&&(n.isJSON()?t=e.content[i]:n.isMultipart()&&(r=e.content[i]))}return r!=null&&t!=null?{...e,content:{[zB.MULTIPART_FORM_DATA]:r}}:e}var Qqo=class{endpoints;parser=new fTi;constructor({context:t,options:r}){this.endpoints=r.filter?.endpoints?new Set(this.validateAndFilterEndpoints({context:t,endpoints:r.filter.endpoints})):void 0}skipEndpoint({method:t,path:r}){return this.endpoints!=null&&!this.endpoints.has(`${t} ${r}`)}hasEndpoints(){return this.endpoints!=null}validateAndFilterEndpoints({context:t,endpoints:r}){let i=[];for(let n of r){let a=this.parser.tryParse(n);if(a==null){t.logger.debug(`Ignoring configured filter endpoint "${n}"; expected format "POST /users/get"`);continue}i.push(`${a.method} ${a.path}`)}return i}};var m7p="#/components/parameters/",P7p="#/components/responses/",j7p="#/components/examples/",w7p="#/components/requestBodies/",qjn=class{logger;document;taskContext;authHeaders;refOccurrences;DUMMY;options;source;filter;namespace;constructor({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:u}){this.document=t,this.logger=r.logger,this.taskContext=r,this.authHeaders=i,this.refOccurrences=O7p(t),this.options=n,this.source=a,this.filter=new Qqo({context:r,options:n}),this.DUMMY=this.getDummy(),this.namespace=u}getNumberOfOccurrencesForRef(t){return this.refOccurrences[t.$ref]??0}resolveTagsToTagIds(t){let r=[];return this.namespace!=null&&r.push(this.namespace),r.concat(t??[])}resolveTags(t){let r=[];if(this.namespace!=null){let i={type:"namespace",name:this.namespace};r.push(i)}return r.concat(t??[])}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveSchemaReference(t){let r=t.$ref.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return{"x-fern-type":"unknown"};i=i[n]}return i==null?(this.logger.warn(`Encountered undefined reference: ${t.$ref}`),{"x-fern-type":"unknown"}):(Kd(i)&&(i=this.resolveSchemaReference(i)),i)}resolveParameterReference(t){if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(m7p))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(m7p.length),i=this.document.components.parameters[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Kd(i)?this.resolveParameterReference(i):i}resolveRequestBodyReference(t){if(this.document.components==null||this.document.components.requestBodies==null||!t.$ref.startsWith(w7p))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(w7p.length),i=this.document.components.requestBodies[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Kd(i)?this.resolveRequestBodyReference(i):i}resolveResponseReference(t){if(this.document.components==null||this.document.components.responses==null||!t.$ref.startsWith(P7p))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(P7p.length),i=this.document.components.responses[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Kd(i)?this.resolveResponseReference(i):i}resolveExampleReference(t){if(this.document.components==null||this.document.components.examples==null||!t.$ref.startsWith(j7p))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(j7p.length),i=this.document.components.examples[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Kd(i)?this.resolveExampleReference(i):i}referenceExists(t){let r=t.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return!1;i=i[n]}return!0}};var Tjn=class extends qjn{constructor({document:t,taskContext:r,options:i,source:n,namespace:a}){super({document:t,taskContext:r,authHeaders:new Set,options:i,source:n,namespace:a})}getDummy(){return this}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}getReferencedSchemas(){return new Set}markReferencedByDiscriminatedUnion(t,r,i){}getReferencesFromDiscriminatedUnion(t){}excludeSchema(t){}isSchemaExcluded(t){return!1}markSchemaWithDiscriminantValue(t,r,i){}getDiscriminatedUnionMetadata(t){}};var Jqo=class extends qjn{nonRequestReferencedSchemas=new Set;twoOrMoreRequestsReferencedSchemas=new Set;singleRequestReferencedSchemas=new Set;discriminatedUnionReferences={};discriminatedUnionMetadata={};schemasToExclude=new Set;constructor({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:u}){super({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:u})}getDummy(){return new Tjn({document:this.document,taskContext:this.taskContext,options:this.options,source:this.source,namespace:this.namespace})}markSchemaAsReferencedByNonRequest(t){this.nonRequestReferencedSchemas.add(t)}markSchemaAsReferencedByRequest(t){this.singleRequestReferencedSchemas.has(t)?this.twoOrMoreRequestsReferencedSchemas.add(t):this.singleRequestReferencedSchemas.add(t)}getReferencedSchemas(){return new Set([...this.nonRequestReferencedSchemas,...this.twoOrMoreRequestsReferencedSchemas])}markReferencedByDiscriminatedUnion(t,r,i){let n=this.discriminatedUnionReferences[t.$ref];n!=null?(n.discriminants.add(r),n.numReferences+=i):this.discriminatedUnionReferences[t.$ref]={discriminants:new Set([r]),numReferences:i}}getReferencesFromDiscriminatedUnion(t){return this.discriminatedUnionReferences[t.$ref]}markSchemaWithDiscriminantValue(t,r,i){let n=this.discriminatedUnionMetadata[t.$ref];n!=null?n.discriminants.set(r,i):this.discriminatedUnionMetadata[t.$ref]={discriminants:new Map([[r,i]])}}getDiscriminatedUnionMetadata(t){return this.discriminatedUnionMetadata[t.$ref]}excludeSchema(t){this.schemasToExclude.add(t)}isSchemaExcluded(t){return this.schemasToExclude.has(t)}};function S7p(e){return bf(e,fd.ASYNC_CONFIG)}var D7p="$request.";function E7p(e){let t=bf(e,fd.STREAMING);if(t!=null)return typeof t=="boolean"?t?{type:"stream",format:"json"}:void 0:t["stream-condition"]==null&&t.format!=null?{type:"stream",format:t.format}:{type:"streamCondition",format:t.format??"json",streamDescription:t["stream-description"],streamConditionProperty:VDD(t["stream-condition"]),responseStream:t["response-stream"],response:t.response}}function VDD(e){return e.startsWith(D7p)?e.slice(D7p.length):e}function M7p(e){let t=e;if(t.cursor!=null)return qIe.cursor({cursor:t.cursor,nextCursor:t.next_cursor,results:t.results});if("offset"in e){let r=e;return qIe.offset({offset:r.offset,results:r.results,step:r.step,hasNextPage:r["has-next-page"]})}if("type"in e&&e.type==="custom"){let r=e;return qIe.custom({results:r.results})}throw new Error("Invalid pagination extension")}function A7p(e,t){let r=bf(t,fd.PAGINATION);if(r!=null){if(typeof r=="boolean"){let i=bf(e,fd.PAGINATION);if(typeof i=="boolean")throw new Error("Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.");return i==null?void 0:M7p(i)}return M7p(r)}}var WDD=Yu.object({lang:Yu.string(),label:Yu.optional(Yu.string()),source:Yu.string()}),h9s=Yu.array(WDD);var q7p={README_EXT:"x-readme"};function HDD(e){if(!Array.isArray(e))return!1;for(let t of e)if(!Hj(t)||typeof t.language!="string"||typeof t.code!="string")return!1;return!0}function T7p(e){let t=bf(e,q7p.README_EXT);if(!Hj(t))return[];let r=t["code-samples"];if(!HDD(r))return[];let i=[];for(let n of r)i.push({name:n.name,language:n.language,code:n.code,install:n.install,docs:void 0});return i}function C7p(e,t,r){let n=(bf(t,fd.EXAMPLES)??[]).filter(s=>{let o=G6.serialization.ExampleEndpointCallSchema.parse(s);return o.ok||r.logger.error(`Failed to parse x-fern-example in ${e.path}/${e.method}`),o.ok}),a=Bfa(t,kU.REDOCLY_CODE_SAMPLES_KEBAB,h9s,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],l=[...Bfa(t,kU.REDOCLY_CODE_SAMPLES_CAMEL,h9s,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],...a];l.length>0&&n.push({"code-samples":l.map(s=>({name:s.label??s.lang,language:s.lang,code:s.source,install:void 0,docs:void 0}))});let d=T7p(t);return d.length>0&&n.push({"code-samples":d}),n.map(L8t.unknown)}function B7p(e){let t=bf(e,fd.AVAILABILITY);if(t==="ga"||t==="generally-available")return $U.GenerallyAvailable;if(t==="beta"||t==="pre-release")return $U.Beta;if(t==="deprecated")return $U.Deprecated;if(e.deprecated)return $U.Deprecated}function Kqo(e){return{url:$DD({url:e.url,variables:e.variables??{}}),description:e.description,name:GDD(e),audiences:bf(e,fd.AUDIENCES)}}function $DD({url:e,variables:t}){let r=Object.fromEntries(Object.entries(t).map(([i,n])=>[i,n.default]));for(let[i,n]of Object.entries(r))e=e.replace(`{${i}}`,n);return e}function GDD(e){let t=bf(e,[fd.SERVER_NAME_V1,fd.SERVER_NAME_V2]);if(t!=null)return t;if(e.description?.toLowerCase()==="production")return"Production";if(e.description?.toLowerCase()==="sandbox")return"Sandbox"}function x7p(e){return bf(e,fd.PARAMETER_NAME)}function I7p(e){return bf(e,fd.SDK_VARIABLE)}function Yqo({path:e,httpMethod:t,parameters:r,context:i,requestBreadcrumbs:n,source:a}){let u={pathParameters:[],queryParameters:[],headers:[]};for(let l of r){let d=bf(l,fd.IGNORE);if(d!=null&&d){i.logger.debug(`${t.toUpperCase()} ${e} has a parameter marked with x-fern-ignore. Skipping.`);continue}let s=Kd(l)?i.resolveParameterReference(l):l,o=s.required??!1,c=nie(s),b=[...n,s.name],g=s2(b,i.options.preserveSchemaIds),O=s.schema!=null?Pb(s.schema,!o,i,b,a,i.namespace,!1,new Set,oQr({schema:s,logger:i.logger})):o?El.primitive({nameOverride:void 0,generatedName:g,title:void 0,schema:Jd.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:oQr({schema:s,logger:i.logger})}),description:void 0,availability:c,groupName:void 0}):El.optional({nameOverride:void 0,generatedName:g,title:void 0,value:El.primitive({nameOverride:void 0,generatedName:g,title:void 0,schema:Jd.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:oQr({schema:s,logger:i.logger})}),description:void 0,availability:void 0,groupName:void 0}),description:void 0,availability:c,groupName:void 0,inline:void 0});if(s.in==="header"&&s.schema!=null&&!Kd(s.schema)&&s.schema.default!=null){let w=s.schema.default;typeof w=="string"&&w.length>0&&(O=El.literal({nameOverride:void 0,generatedName:g,title:void 0,value:YB.string(w),description:void 0,availability:c,groupName:void 0}))}let m={name:s.name,schema:O,description:s.description,parameterNameOverride:x7p(s),availability:c,source:a};s.in==="query"?u.queryParameters.push(m):s.in==="path"?u.pathParameters.push({...m,variableReference:I7p(s)}):s.in==="header"?!QDD.has(s.name.toLowerCase())&&!i.authHeaders.has(s.name)?u.headers.push({...m,env:void 0}):i.logger.debug(`Ignoring ${s.name} header, in ${t.toUpperCase()} ${e}`):i.logger.warn(`Skipping ${s.in} parameter, ${s.name}, in ${t.toUpperCase()} ${e}`)}return u}var QDD=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]);function z7p(e,t){for(let r of Object.keys(e))if(r.includes("text/event-stream")){let i=e[r];if(i==null)continue;let n=i.schema;return{contentType:r,schema:n??{},examples:Nfa(i,t)}}}function Cjn(e,t){for(let r of Object.keys(e))if(r.includes("json")||r==="*/*"){let i=e[r];if(i==null)continue;let n=i.schema;return{contentType:r.includes("*")?void 0:r,schema:n??{},examples:Nfa(i,t)}}}function R7p(e,t){for(let r of Object.keys(e)){let i=e[r];if(i==null)continue;return{schema:i.schema??{},examples:Nfa(i,t)}}}function Nfa(e,t){let r=[];e.example!=null&&r.push({name:void 0,value:e.example,description:void 0});let i=bf(e,kU.EXAMPLES);return i!=null&&Object.keys(i).length>0&&r.push(...Object.entries(i).map(([n,a])=>({name:a.summary??n,value:a.value,description:a.description}))),e.examples!=null&&Object.keys(e.examples).length>0&&r.push(...Object.entries(e.examples).map(([n,a])=>{let u=Kd(a)?t.resolveExampleReference(a):a;return{name:u.summary??n,value:u.value,description:u.description}})),r}function JDD(e,t){for(let[r,i]of Object.entries(e.content))if(zB.parse(r)?.isURLEncoded())return{schema:i.schema,contentType:r,examples:Nfa(i,t)}}function KDD(e){for(let[t,r]of Object.entries(e.content))if(zB.parse(t)?.isMultipart())return{schema:r.schema,encoding:r.encoding}}function YDD(e){for(let t in e.content)if(zB.parse(t)?.isOctetStream())return!0;return!1}function XDD(e,t){let r=Kd(e)?y9s(e,t):{id:void 0,schema:e};return Object.entries(r.schema.properties??{}).find(([i,n])=>!Kd(n)&&n.type==="string"&&n.format==="binary")!=null}function Bjn({requestBody:e,document:t,context:r,requestBreadcrumbs:i,source:n,namespace:a}){let u=Kd(e)?r.resolveRequestBodyReference(e):e,l=KDD(u),d=l?.schema,s=l?.encoding,o=JDD(u,r),c=Cjn(u.content,r);if(YDD(u))return lSe.octetStream({description:u.description,source:n});if(d!=null&&c==null||d!=null&&XDD(d,t)){let b=Kd(d)?y9s(d,t):{id:void 0,schema:d},g=Pb(b.schema,!1,r,i,n,a),O=[];if(g.type==="object")for(let m of g.properties){if(m.schema.type==="primitive"&&m.schema.schema.type==="string"&&m.schema.schema.format==="binary"){O.push({key:m.key,schema:CIe.file({isOptional:!1,isArray:!1}),description:m.schema.description,contentType:s?.[m.key]?.contentType,exploded:!1,encoding:void 0});continue}if(m.schema.type==="optional"&&m.schema.value.type==="primitive"&&m.schema.value.schema.type==="string"&&m.schema.value.schema.format==="binary"){O.push({key:m.key,schema:CIe.file({isOptional:!0,isArray:!1}),description:m.schema.description,contentType:s?.[m.key]?.contentType,exploded:!1,encoding:void 0});continue}if(m.schema.type==="array"&&m.schema.value.type==="primitive"&&m.schema.value.schema.type==="string"&&m.schema.value.schema.format==="binary"){O.push({key:m.key,schema:CIe.file({isOptional:!1,isArray:!0}),description:m.schema.description,contentType:s?.[m.key]?.contentType,exploded:!1,encoding:void 0});continue}if(m.schema.type==="optional"&&m.schema.value.type==="array"&&m.schema.value.value.type==="primitive"&&m.schema.value.value.schema.type==="string"&&m.schema.value.value.schema.format==="binary"){O.push({key:m.key,schema:CIe.file({isOptional:!0,isArray:!0}),description:m.schema.description,contentType:s?.[m.key]?.contentType,exploded:!1,encoding:void 0});continue}let w=s?.[m.key]?.contentType;O.push({key:m.key,schema:CIe.json(m.schema),description:void 0,contentType:s?.[m.key]?.contentType,exploded:s?.[m.key]?.explode,encoding:w==null?r.options.defaultFormParameterEncoding:void 0})}return lSe.multipart({name:Kd(d)&&r.getNumberOfOccurrencesForRef(d)===1?b.id:void 0,description:b.schema.description,properties:O,source:n})}if(c!=null){let b=Pb(c.schema,!1,r,i,n,a,!0);return lSe.json({description:void 0,schema:b,contentType:c.contentType,fullExamples:c.examples,additionalProperties:!Kd(c.schema)&&mjn(c.schema.additionalProperties),source:n})}if(o!=null&&o.schema!=null){let b=Pb(o.schema,!1,r,i,n,a);return lSe.json({schema:b,description:u.description,contentType:o.contentType,source:n,fullExamples:o.examples,additionalProperties:!1})}}function y9s(e,t){if(!e.$ref.startsWith(qIi))throw new Error(`Failed to resolve schema reference because of unsupported prefix: ${e.$ref}`);let r=Nli(e);if(r==null)throw new Error(`Failed to resolve schema reference because missing schema id: ${e.$ref}`);let i=t.components?.schemas?.[r];if(i==null)throw new Error(`Failed to resolve schema reference because missing: ${e.$ref}`);return Kd(i)?y9s(i,t):{id:r,schema:i}}var v9s={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"},N7p=new Set(Object.values(v9s));var ZDD=["200","201","202","204"];function L7p({operationContext:e,responses:t,context:r,responseBreadcrumbs:i,responseStatusCode:n,streamFormat:a,source:u}){if(t==null)return{value:void 0,errors:{}};let l=kDD({responses:t,context:r,source:u,namespace:r.namespace}),d=!1,s;for(let o of n!=null?[n]:ZDD){let c=t[o];c!=null&&(d=!0,s==null&&(s=F7p({operationContext:e,response:c,context:r,responseBreadcrumbs:i,streamFormat:a,source:u,namespace:r.namespace,statusCode:typeof o=="string"?parseInt(o):o})))}if(s==null&&!d&&t.default!=null&&(s=F7p({operationContext:e,response:t.default,context:r,responseBreadcrumbs:i,streamFormat:a,source:u,namespace:r.namespace})),s!=null)switch(s.type){case"json":return{value:s,errors:l};case"streamingJson":case"streamingSse":return{value:s,errors:l};case"file":case"text":case"streamingText":return{value:s,errors:l};default:Ko(s)}return{value:void 0,errors:l}}function F7p({operationContext:e,streamFormat:t,response:r,context:i,responseBreadcrumbs:n,source:a,namespace:u,statusCode:l}){let d=Kd(r)?i.resolveResponseReference(r):r;if(d.content!=null&&Object.entries(d.content).find(([b,g])=>{if(g.schema==null)return!1;let O=Kd(g.schema)?i.resolveSchemaReference(g.schema):g.schema;return O.type==="string"&&O.format==="binary"}))return XB.file({description:d.description,source:a,statusCode:l});let s=z7p(d.content??{},i);if(s!=null&&t!=null)switch(t){case"json":return XB.streamingJson({statusCode:l,description:d.description,responseProperty:bf(e.operation,fd.RESPONSE_PROPERTY),fullExamples:s.examples,schema:Pb(s.schema,!1,i,n,a,u),source:a});case"sse":return XB.streamingSse({description:d.description,responseProperty:void 0,fullExamples:s.examples,schema:Pb(s.schema,!1,i,n,a,u),source:a,statusCode:l})}let o=Cjn(d.content??{},i);if(o!=null){if(t!=null)switch(t){case"json":return XB.streamingJson({description:d.description,responseProperty:void 0,fullExamples:o.examples,schema:Pb(o.schema,!1,i,n,a,u),source:a,statusCode:l});case"sse":return XB.streamingSse({description:d.description,responseProperty:void 0,fullExamples:o.examples,schema:Pb(o.schema,!1,i,n,a,u),source:a,statusCode:l})}return XB.json({description:d.description,schema:Pb(o.schema,!1,i,n,a,u),responseProperty:bf(e.operation,fd.RESPONSE_PROPERTY),fullExamples:o.examples,source:a,statusCode:l})}for(let[c,b]of Object.entries(d.content??{})){let g=zB.parse(c);if(g!=null){if(g.isOctetStream()||g.isPDF()||g.isAudio()||g.isImage()||g.isVideo())return XB.file({description:d.description,source:a,statusCode:l});if(g.isPlainText()){let O=b.schema;if(O==null)return XB.text({description:d.description,source:a,statusCode:l});let m=Kd(O)?i.resolveSchemaReference(O):O;return m.type==="string"&&m.format==="byte"?XB.file({description:d.description,source:a,statusCode:l}):XB.text({description:d.description,source:a,statusCode:l})}}}}function kDD({responses:e,context:t,source:r,namespace:i}){let n={};for(let[a,u]of Object.entries(e)){if(a==="default")continue;let l=parseInt(a);if(l<400||l>600)continue;let d=Kd(u)?t.resolveResponseReference(u):u,s=R7p(d.content??{},t),o=v9s[l];if(o==null){t.logger.warn(`No error name found for status code ${a}`);continue}n[l]={statusCode:l,nameOverride:void 0,generatedName:o,description:d.description,schema:Pb(s?.schema??{},!1,t,[o,"Body"],r,i),fullExamples:s?.examples,source:r}}return n}function uQr({operationContext:e,context:t,responseStatusCode:r,suffix:i,streamFormat:n,source:a}){let{document:u,operation:l,path:d,method:s,baseBreadcrumbs:o,sdkMethodName:c}=e,b=bf(l,fd.IDEMPOTENT),g=bf(l,[fd.REQUEST_NAME_V1,fd.REQUEST_NAME_V2]),O=[...o,"Request"],m=Yqo({parameters:[...e.pathItemParameters,...e.operationParameters],context:t,requestBreadcrumbs:O,path:d,httpMethod:s,source:a}),w=/{([^}]+)}/g,A=[...d.matchAll(w)].map(U=>U[1]).filter(U=>!m.pathParameters.some(H=>H.name===U));if(A.length>0)for(let U of A)m.pathParameters.push({name:U??"",variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:a,schema:El.primitive({schema:Jd.string({default:void 0,example:void 0,format:void 0,maxLength:void 0,minLength:void 0,pattern:void 0}),description:void 0,generatedName:"",nameOverride:void 0,groupName:void 0,availability:void 0,title:void 0}),description:void 0});let q=l.requestBody!=null?Bjn({requestBody:l.requestBody,document:u,context:new Tjn({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:O,source:a,namespace:t.namespace}):void 0;tED({context:t,convertedParameters:m})&&q!=null&&q.type==="json"&&q.schema.type!=="object"&&l.requestBody!=null?q=Bjn({requestBody:l.requestBody,document:u,context:t,requestBreadcrumbs:[...O,"Body"],source:a,namespace:t.namespace}):l.requestBody!=null&&(q=Bjn({requestBody:l.requestBody,document:u,context:t,requestBreadcrumbs:[...O],source:a,namespace:t.namespace}));let D=[...o,"Response"],C=L7p({operationContext:e,streamFormat:n,responses:l.responses,context:t,responseBreadcrumbs:D,responseStatusCode:r,source:a});e.method==="GET"&&(q=void 0);let R=B7p(l),$=C7p(e,l,t),I=bf(l,fd.SERVER_NAME_V2);return{summary:l.summary,internal:bf(l,kU.INTERNAL),idempotent:b,audiences:bf(l,fd.AUDIENCES)??[],operationId:l.operationId!=null&&i!=null?l.operationId+"_"+i:l.operationId,tags:t.resolveTagsToTagIds(l.tags),namespace:t.namespace,sdkName:c,pathParameters:m.pathParameters,queryParameters:m.queryParameters,headers:m.headers,requestNameOverride:g??void 0,generatedRequestName:s2(O,t.options.preserveSchemaIds),request:q,response:C.value,errors:C.errors,servers:I!=null?[{name:I,url:void 0,audiences:void 0}]:(l.servers??[]).map(U=>Kqo(U)),description:l.description,authed:eED(l,u),availability:R,method:s,path:d,examples:$,pagination:e.pagination,source:a}}function eED(e,t){return e.security!=null?Object.keys(e.security).length>0:t.security!=null?Object.keys(t.security).length>0:!1}function tED({context:e,convertedParameters:t}){return e.options.inlinePathParameters&&t.pathParameters.length>0||t.queryParameters.length>0||t.headers.length>0}function V7p({operationContext:e,context:t,asyncExtension:r,source:i}){let{operation:n,pathItemParameters:a,operationParameters:u}=e,l=r.discriminant.name,d=r.discriminant.value,s=r["response-status-code"],o=U7p({context:t,headerToIgnore:l,parameters:a}),c=U7p({context:t,headerToIgnore:l,parameters:u}),b=uQr({operationContext:{...e,pathItemParameters:o,operationParameters:c,operation:{...n,responses:Object.fromEntries(Object.entries(n.responses).filter(([O])=>parseInt(O)!==s))}},context:t,streamFormat:void 0,source:i}),g=uQr({operationContext:{...e,pathItemParameters:o,operationParameters:c,baseBreadcrumbs:[...e.baseBreadcrumbs,"async"]},context:t,suffix:"async",responseStatusCode:s,streamFormat:void 0,source:i});return g.headers.push({name:l,schema:El.literal({nameOverride:void 0,generatedName:s2([l],t.options.preserveSchemaIds),title:void 0,description:void 0,availability:void 0,value:YB.string(d),groupName:void 0}),description:void 0,parameterNameOverride:void 0,env:void 0,availability:void 0,source:i}),{sync:b,async:g}}function U7p({context:e,headerToIgnore:t,parameters:r}){return r.filter(i=>{let n=Kd(i)?e.resolveParameterReference(i):i;return!(n.in==="header"&&n.name===t)})}var b9s="stream";function G7p({operationContext:e,context:t,streamingExtension:r}){switch(r.type){case"stream":return{streaming:uQr({operationContext:e,context:t,streamFormat:r.format,source:t.source}),nonStreaming:void 0};case"streamCondition":{let i=W7p({context:t,operation:e.operation,streamingExtension:r,isStreaming:!0});if(i?.schemaReference!=null){let s=Nli(i.schemaReference);s!=null&&t.excludeSchema(s)}let n=H7p({operation:e.operation,response:r.responseStream}),a=uQr({operationContext:{...e,sdkMethodName:e.sdkMethodName!=null?{groupName:e.sdkMethodName.groupName,methodName:e.sdkMethodName.methodName+"_"+b9s}:void 0,operation:{...e.operation,description:r.streamDescription??e.operation.description,requestBody:i?.requestBody,responses:n},baseBreadcrumbs:[...e.baseBreadcrumbs,b9s]},context:t,streamFormat:r.format,suffix:b9s,source:t.source});a.examples=a.examples.filter(s=>$7p(s,t)!==!1);let u=W7p({context:t,operation:e.operation,streamingExtension:r,isStreaming:!1}),l=H7p({operation:e.operation,response:r.response}),d=uQr({streamFormat:void 0,operationContext:{...e,operation:{...e.operation,requestBody:u?.requestBody,responses:l}},context:t,source:t.source});return d.examples=d.examples.filter(s=>$7p(s,t)!==!0),{streaming:a,nonStreaming:d}}default:Ko(r)}}function W7p({context:e,operation:t,streamingExtension:r,isStreaming:i}){if(t.requestBody==null)return;let n=Kd(t.requestBody)?e.resolveRequestBodyReference(t.requestBody):t.requestBody,a=Cjn(n.content,e);if(a==null)return;let u=Kd(a.schema)?e.resolveSchemaReference(a.schema):a.schema;if(u.allOf==null&&u.properties==null)return;let l=u.properties?.[r.streamConditionProperty];l!=null&&Kd(l)&&(l=void 0);let d={...u,properties:{...u.properties,[r.streamConditionProperty]:{type:"boolean","x-fern-boolean-literal":i,...l??{}}},title:void 0,required:[...u.required??[],r.streamConditionProperty]};return{requestBody:{content:{[zB.APPLICATION_JSON]:{schema:d}}},schemaReference:Kd(a.schema)?a.schema:void 0}}function H7p({operation:e,response:t}){return{...e.responses,200:{description:"",content:{[zB.APPLICATION_JSON]:{schema:t}}}}}function $7p(e,t){return e._visit({unknown:r=>{let i=G6.serialization.ExampleEndpointCallSchema.parse(r);if(i.ok&&i.value.response!=null)return i.value.response.stream!=null},full:()=>{},_other:()=>{}})}function Q7p({context:e,operationContext:t,source:r}){let{document:i,operation:n,path:a,method:u,baseBreadcrumbs:l,sdkMethodName:d}=t,s=[...l,"Payload"],o=Yqo({parameters:[...t.pathItemParameters,...t.operationParameters],context:e,requestBreadcrumbs:s,path:a,httpMethod:u,source:r});if(n.requestBody==null){e.logger.error(`Skipping webhook ${u.toUpperCase()} ${a}: Missing a request body`);return}if(u!=="POST"&&u!=="GET"){e.logger.error(`Skipping webhook ${u.toUpperCase()} ${a}: Not POST or GET`);return}let c=Bjn({requestBody:n.requestBody,document:i,context:e,requestBreadcrumbs:[...l,"Payload"],source:r,namespace:e.namespace});if(c==null||c.type!=="json"){e.logger.error(`Skipping webhook ${a} because non-json request body`);return}if(n.operationId==null){e.logger.error(`Skipping webhook ${a} because no operation id present`);return}return{summary:n.summary,sdkName:d,namespace:e.namespace,method:u,operationId:n.operationId,tags:e.resolveTagsToTagIds(n.tags),headers:o.headers,generatedPayloadName:s2(s,e.options.preserveSchemaIds),payload:c.schema,description:n.description,examples:rED(c.fullExamples),source:r}}function rED(e){if(e==null)return[];let t=[];for(let r of e){let i=Fli(r.value);i!=null&&t.push({description:r.description,name:r.name,payload:i})}return t}function g9s({context:e,pathItemContext:t,operation:r,convertToWebhook:i}){let n=bf(r,fd.IGNORE);if(n!=null&&n){e.logger.debug(`${t.method.toUpperCase()} ${t.path} is marked with x-fern-ignore. Skipping.`);return}let a=iED(r,e),u=A7p(e.document,r),l={...t,sdkMethodName:a,baseBreadcrumbs:nED({operation:r,sdkMethodName:a,httpMethod:t.method,path:t.path,shouldUseIdiomaticRequestNames:e.options.shouldUseIdiomaticRequestNames}),operation:r,operationParameters:r.parameters??[],pagination:u};if(i){let c=Q7p({context:e,operationContext:l,source:e.source});return c!=null?{type:"webhook",value:c}:void 0}let d=E7p(r);if(d!=null){let c=G7p({context:e,operationContext:l,streamingExtension:d});return c!=null?{type:"streaming",streaming:c.streaming,nonStreaming:c.nonStreaming}:void 0}let s=S7p(r);if(s!=null){let c=V7p({context:e,operationContext:l,asyncExtension:s,source:e.source});return{type:"async",async:c.async,sync:c.sync}}return{type:"http",value:uQr({context:e,operationContext:l,streamFormat:void 0,source:e.source})}}function iED(e,t){let r=bf(e,fd.SDK_METHOD_NAME),i=bf(e,fd.SDK_GROUP_NAME)??[];if(r!=null){let n=typeof i=="string"?[i]:i;return n=t.resolveGroupName(n),{groupName:n,methodName:r}}}function nED({sdkMethodName:e,operation:t,httpMethod:r,path:i,shouldUseIdiomaticRequestNames:n}){let a=[];if(e!=null){if(n&&a.push(e.methodName),e.groupName.length>0){let u=e.groupName[e.groupName.length-1];u!=null&&a.push(typeof u=="string"?u:u.name)}n||a.push(e.methodName)}else t.operationId!=null?a.push(t.operationId):a.push(vg(`${r}_${i.split("/").join("_")}`));return a}function J7p(e,t,r,i){let n=[],a=Y7p(t),u={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let l of a){if(i.filter.skipEndpoint({method:l.method,path:e})){i.logger.debug(`Skipping endpoint "${l.method} ${e}"`);continue}let d=aED({operation:l.operation}),s=g9s({context:i,pathItemContext:{...u,method:l.method},operation:l.operation,convertToWebhook:d});s!=null&&n.push(s)}return n}function K7p(e,t,r,i){let n=[],a=Y7p(t),u={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let l of a){if(i.filter.skipEndpoint({method:l.method,path:e})){i.logger.debug(`Skipping endpoint "${l.method} ${e}"`);continue}let d=g9s({context:i,pathItemContext:{...u,method:l.method},operation:l.operation,convertToWebhook:!0});d!=null&&n.push(d)}return n}function Y7p(e){let t=[];return e.get!=null&&t.push({method:W$.Get,operation:e.get}),e.post!=null&&t.push({method:W$.Post,operation:e.post}),e.put!=null&&t.push({method:W$.Put,operation:e.put}),e.delete!=null&&t.push({method:W$.Delete,operation:e.delete}),e.patch!=null&&t.push({method:W$.Patch,operation:e.patch}),t}function aED({operation:e}){return bf(e,[fd.WEBHOOK])??!1}function X7p(e){let t=bf(e,fd.BASIC_AUTH_USERNAME_VARIABLE_NAME),r=bf(e,fd.BASIC_AUTH_PASSWORD_VARIABLE_NAME);return{usernameVariable:t,passwordVariable:r}}function Z7p(e){return bf(e,fd.FERN_BASIC_AUTH)}function O9s(e,t){if(Kd(e))throw new Error(`Converting referenced security schemes is unsupported: ${JSON.stringify(e)}`);return oED(e,t)}function oED(e,t){if(e.type==="apiKey"&&e.in==="header"){let r=bf(e,kU.BEARER_FORMAT),i=bf(e,fd.FERN_HEADER_AUTH);return k8.header({headerName:e.name,prefix:r!=null?"Bearer":i?.prefix,headerVariableName:i?.name??bf(e,fd.HEADER_VARIABLE_NAME),headerEnvVar:i?.env})}else if(e.type==="http"&&e.scheme==="bearer"){let r=bf(e,fd.FERN_BEARER_TOKEN);return k8.bearer({tokenVariableName:r?.name??bf(e,fd.BEARER_TOKEN_VARIABLE_NAME),tokenEnvVar:r?.env})}else if(e.type==="http"&&e.scheme==="basic"){let r=Z7p(e),i=X7p(e);return k8.basic({usernameVariableName:r?.username?.name??i.usernameVariable,usernameEnvVar:r?.username?.env,passwordVariableName:r?.password?.name??i.passwordVariable,passwordEnvVar:r?.password?.env})}else{if(e.type==="openIdConnect")return k8.bearer({tokenVariableName:void 0,tokenEnvVar:void 0});if(e.type==="oauth2")return k8.oauth({scopesEnum:uED(e,t)})}}function uED(e,t){let r=e.flows.authorizationCode?.scopes??e.flows.clientCredentials?.scopes??e.flows.implicit?.scopes??e.flows.password?.scopes;if(r!=null){let i=SYt({nameOverride:void 0,generatedName:"OauthScope",title:void 0,enumValues:Object.keys(r),fernEnum:Object.fromEntries(Object.entries(r).map(([a,u])=>[a,{description:u}])),_default:void 0,description:void 0,availability:void 0,enumVarNames:void 0,wrapAsNullable:!1,groupName:void 0,context:void 0,source:t,inline:void 0}),n=kD(i);if(n.type==="enum")return n}}function k7p(e){return bf(e,fd.BASE_PATH)}var sED=Yu.record(Yu.string(),Yu.object({summary:Yu.string().optional(),description:Yu.string().optional()}));function e6p({document:e,context:t}){return Bfa(e,fd.GROUPS,sED,t.logger)}function t6p({context:e,document:t}){return bf(t,fd.FERN_VERSION)??void 0}function r6p(e){let t=bf(e,fd.FERN_GLOBAL_HEADERS),r=[];for(let i of t??[])r.push({...i,schema:i.type!=null?xfa({fernType:i.type,description:void 0,availability:void 0,generatedName:i.name??i.header,title:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function i6p(e){let t=bf(e,fd.FERN_IDEMPOTENCY_HEADERS),r=[];for(let i of t??[])r.push({...i,schema:i.type!=null?xfa({fernType:i.type,description:void 0,availability:void 0,generatedName:i.name??i.header,title:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function n6p(e,t){let r=bf(e,fd.SDK_VARIABLES);return r==null?{}:Object.fromEntries(Object.entries(r).map(([i,n])=>{if(n.type==="string")return[i,{nameOverride:void 0,generatedName:s2([i],t),title:n.title,schema:sj.string({default:Sjn(n),pattern:n.pattern,format:n.format,minLength:n.minLength,maxLength:n.maxLength}),description:n.description,availability:void 0,groupName:void 0}];throw new Error(`Variable ${i} has unsupported schema ${JSON.stringify(n)}`)}))}var cED="webhooks";function a6p(e){return bf(e,cED)??{}}function o6p(e){return bf(e,fd.RESOLUTIONS)}function u6p({openapi:e}){let t=o6p(e);if(t==null)return e;let r={};for(let i of t){let n=`#/components/schemas/${i.name}`;for(let a of i.resolutions)e=lED({openapi:e,schemaReference:a,schemaName:i.name}),e=s6p({openapi:e,replaceReference:a,schemaReference:n,replacedReferences:r}),r={...r,...Object.fromEntries(i.resolutions.map(u=>[n,u]))}}return e}function lED({openapi:e,schemaReference:t,schemaName:r}){let i=t.replace("#/","").split("/").map(a=>a.replaceAll("~1","/")),n=e;for(let a of i){let u=n[a];if(u==null)return e;n=u}return e.components==null&&(e.components={}),e.components.schemas==null&&(e.components.schemas={}),e.components.schemas[r]=n,e}function s6p({openapi:e,replaceReference:t,schemaReference:r,replacedReferences:i}){let n=Object.keys(i).filter(d=>t.startsWith(d)).sort((d,s)=>s.length-d.length)[0];if(n!=null){let d=i[n];if(d!=null){let s=r.replace(n,d);return s6p({openapi:e,replaceReference:t,schemaReference:s,replacedReferences:{}})}}let a=t.replace("#/","").split("/").map(d=>d.replaceAll("~1","/")),u=e;for(let d of a.slice(0,-1)){let s=u[d];if(s==null)return e;u=s}let l=a[a.length-1];return l==null||(u[l]={$ref:r}),e}function l6p({openApi:e,taskContext:t,options:r,source:i,namespace:n}){e=u6p({openapi:e});let a=Object.fromEntries(Object.entries(e.components?.securitySchemes??{}).map(([I,U])=>O9s(U,i)==null?[]:[I,O9s(U,i)])),u=new Set(...Object.entries(a).map(([I,U])=>U.type==="basic"||U.type==="bearer"?"Authorization":U.type==="header"?U.headerName:null)),l=n6p(e,r.preserveSchemaIds),d=r6p(e),s=i6p(e),o=r.audiences??[],c=[],b=[],g=new Jqo({document:e,taskContext:t,authHeaders:u,options:r,source:i,namespace:n});g.filter.hasEndpoints()&&t.logger.debug("Endpoint filter applied..."),Object.entries(e.paths??{}).forEach(([I,U])=>{if(U==null)return;t.logger.debug(`Converting path ${I}`);let H=J7p(I,U,e,g);for(let k of H){let K=c6p({operation:k});if(!(o.length>0&&!o.some(te=>K.includes(te))))switch(k.type){case"async":c.push(k.sync),c.push(k.async);break;case"http":c.push(k.value);break;case"streaming":c.push(k.streaming),k.nonStreaming&&c.push(k.nonStreaming);break;case"webhook":b.push(k.value);break;default:Ko(k)}}}),Object.entries(a6p(e)).forEach(([I,U])=>{if(U==null)return;t.logger.debug(`Converting path ${I}`);let H=K7p(I,U,e,g);for(let k of H){let K=c6p({operation:k});o.length>0&&!o.some(te=>K.includes(te))||b.push(k.value)}});let O=Object.fromEntries(Object.entries(e.components?.schemas??{}).map(([I,U])=>{if(!Kd(U)){let H=bf(U,fd.IGNORE);if(H!=null&&H)return[];if(N7p.has(I))return[I,Pb({...U,"x-fern-type-name":`${I}Body`},!1,g,[I],i,n)]}return[I,Pb(U,!1,g,[I],i,n)]}).filter(I=>I.length>0)),m=fED(O,g,i),w=dED(m,g),E={};for(let[I,U]of Object.entries(w)){let H=kD(U);g.isSchemaExcluded(I)||(E[I]=H,t.logger.debug(`Converted schema ${I}`))}let A=new Lli(w,g.nonRequestReferencedSchemas,g),q=b.map(I=>{let H=I.examples;if(!r.disableExamples&&H.length===0){let k=A.buildExample({schema:I.payload,exampleId:void 0,example:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});k!=null&&(H=[{name:void 0,description:void 0,payload:k}])}return{...I,payload:kD(I.payload),examples:H}}),D=new Vqo(w,g),C=c.map(I=>{let U=I.examples,H=U;if(!r.disableExamples&&(U.length===0||U.every(zfa))){let te=D.buildEndpointExample(I);te.length>0&&(H=[...te,...U.filter(fe=>!zfa(fe))])}let k=I.request,K=I.response;return{...I,request:k?.type==="json"?{...k,schema:kD(k.schema)}:k,response:K?.type==="json"?{...K,schema:kD(K.schema)}:K,queryParameters:I.queryParameters.map(te=>({description:te.description,name:te.name,schema:kD(te.schema),parameterNameOverride:te.parameterNameOverride,availability:te.availability,source:te.source})),pathParameters:I.pathParameters.map(te=>({description:te.description,name:te.name,schema:kD(te.schema),parameterNameOverride:te.parameterNameOverride,variableReference:te.variableReference,availability:te.availability,source:te.source})),headers:I.headers.map(te=>({description:te.description,name:te.name,schema:kD(te.schema),parameterNameOverride:te.parameterNameOverride,env:te.env,availability:te.availability,source:te.source})),examples:H,errors:od(I.errors,te=>{let fe=te.fullExamples?.map(me=>{let be=Fli(me.value);if(be!=null)return{name:me.name,description:me.description,example:be}}).filter(u0);if(fe?.length===0){let me=A.buildExample({schema:te.schema,example:void 0,exampleId:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});me!=null&&fe.push({name:void 0,description:void 0,example:me})}return{generatedName:te.generatedName,nameOverride:te.nameOverride,schema:kD(te.schema),description:te.description,source:te.source,examples:fe}})}}),R=e6p({document:e,context:g});return{apiVersion:t6p({context:g,document:e}),basePath:k7p(e),title:e.info.title,description:e.info.description,groups:Object.fromEntries(Object.entries(R??{}).map(([I,U])=>[I,{summary:U.summary??void 0,description:U.description??void 0}])),servers:(e.servers??[]).map(I=>Kqo(I)),websocketServers:[],tags:{tagsById:Object.fromEntries((e.tags??[]).map(I=>[I.name,{id:I.name,description:I.description}])),orderedTagIds:e.tags?.map(I=>I.name)},endpoints:C,webhooks:q,channels:{},groupedSchemas:Mjn(n,E),securitySchemes:a,hasEndpointsMarkedInternal:C.some(I=>I.internal),nonRequestReferencedSchemas:g.getReferencedSchemas(),variables:l,globalHeaders:d,idempotencyHeaders:s}}function fED(e,t,r){let i={};for(let[n,a]of Object.entries(e)){if(a.type!=="object"){i[n]=a;continue}let u={$ref:`#/components/schemas/${n}`},l=t.getReferencesFromDiscriminatedUnion(u);if(l==null){i[n]=a;continue}let d={...a,type:"object",properties:a.properties.filter(o=>!l.discriminants.has(o.key)),allOfPropertyConflicts:a.allOfPropertyConflicts.filter(o=>!l.discriminants.has(o.propertyKey)),source:r};i[n]=d;let s=f6p({schema:a,schemas:e});for(let o of[...new Set(s)]){let c=i[o]??e[o];c==null||c.type!=="object"||(i[o]={...c,type:"object",properties:c.properties.filter(b=>!l.discriminants.has(b.key)),allOfPropertyConflicts:c.allOfPropertyConflicts.filter(b=>!l.discriminants.has(b.propertyKey))})}}return i}function dED(e,t){let r={};for(let[i,n]of Object.entries(e)){if(n.type!=="object"){r[i]=n;continue}let a={$ref:`#/components/schemas/${i}`},u=t.getDiscriminatedUnionMetadata(a);if(u==null){r[i]=n;continue}let l=[];for(let s of n.properties)if(u.discriminants.has(s.key)){let o=u.discriminants.get(s.key);o!=null&&l.push({...s,schema:El.literal({nameOverride:void 0,generatedName:s2([n.generatedName,o],t.options.preserveSchemaIds),title:void 0,value:YB.string(o),groupName:void 0,description:void 0,availability:n.availability})})}else l.push(s);let d={...n,type:"object",properties:l};r[i]=d}return r}function f6p({schema:e,schemas:t}){let r=[];for(let i of e.allOf){r.push(i.schema);let n=t[i.schema];n!=null&&n.type==="object"&&r.push(...f6p({schema:n,schemas:t}))}return r}function c6p({operation:e}){let t=[];switch(e.type){case"async":t=e.async.audiences;break;case"http":t=e.value.audiences;break;case"streaming":t=e.streaming.audiences;break;case"webhook":break;default:Ko(e)}return t}function TIi({context:e,documents:t,options:r}){let i={apiVersion:void 0,title:void 0,description:void 0,basePath:void 0,servers:[],websocketServers:[],tags:{tagsById:{},orderedTagIds:void 0},hasEndpointsMarkedInternal:!1,endpoints:[],webhooks:[],channels:{},groupedSchemas:{rootSchemas:{},namespacedSchemas:{}},variables:{},nonRequestReferencedSchemas:new Set,securitySchemes:{},globalHeaders:[],idempotencyHeaders:[],groups:{}};for(let n of t){let a=n.source!=null?n.source:Kre.openapi({file:"<memory>"});switch(n.type){case"openapi":{let u=l6p({taskContext:e,openApi:n.value,options:a9s({options:n.settings,overrides:r}),source:a,namespace:n.namespace});i=_ED(i,u);break}case"asyncapi":{let u=g7p({document:n.value,taskContext:e,options:a9s({options:n.settings,overrides:r}),source:a,asyncApiOptions:pED({options:n.settings}),namespace:n.namespace});u.servers!=null&&(i.websocketServers=[...i.websocketServers,...u.servers.map(l=>({...l,audiences:void 0,description:void 0}))]),u.channels!=null&&(i.channels={...i.channels,...u.channels}),u.groupedSchemas!=null&&(i.groupedSchemas=d6p(i.groupedSchemas,u.groupedSchemas)),u.basePath!=null&&(i.basePath=u.basePath);break}default:Ko(n)}}return i}function pED({options:e,overrides:t}){return{naming:t?.naming??e?.asyncApiNaming??R3p.naming}}function _ED(e,t){return{apiVersion:e.apiVersion??t.apiVersion,title:e.title??t.title,description:e.description??t.description,basePath:e.basePath??t.basePath,servers:[...e.servers,...t.servers],websocketServers:[...e.websocketServers,...t.websocketServers],tags:{tagsById:{...e.tags.tagsById,...t.tags.tagsById},orderedTagIds:e.tags.orderedTagIds==null&&t.tags.orderedTagIds==null?void 0:[...e.tags.orderedTagIds??[],...t.tags.orderedTagIds??[]]},hasEndpointsMarkedInternal:e.hasEndpointsMarkedInternal||t.hasEndpointsMarkedInternal,endpoints:[...e.endpoints,...t.endpoints],webhooks:[...e.webhooks,...t.webhooks],channels:{...e.channels,...t.channels},groupedSchemas:d6p(e.groupedSchemas,t.groupedSchemas),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},globalHeaders:e.globalHeaders!=null?[...e.globalHeaders,...t.globalHeaders??[]]:void 0,idempotencyHeaders:e.idempotencyHeaders!=null?[...e.idempotencyHeaders,...t.idempotencyHeaders??[]]:void 0,groups:{...e.groups,...t.groups}}}function d6p(e,t){e.rootSchemas={...e.rootSchemas,...t.rootSchemas};for(let[r,i]of Object.entries(t.namespacedSchemas))e.namespacedSchemas[r]!=null?e.namespacedSchemas[r]={...e.namespacedSchemas[r],...i}:e.namespacedSchemas[r]=i;return e}var Xqo={config:new p6p.Config({apis:{},styleguide:{plugins:[n9s],rules:{spec:"warn"}}},void 0),dereference:!1,removeUnusedComponents:!1,keepUrlRefs:!0};function Ffa(e){return e.swagger!=null}function m9s(e){return e.openapi!=null}function Uli(e,t={}){return{...Object.fromEntries(vN(e.namedDefinitionFiles).map(([r,i])=>[r,{...i,defaultUrl:t.defaultURL}])),...vN(e.importedDefinitions).reduce((r,[i,n])=>({...r,...Pkn(Uli(n.definition,{defaultURL:n.url}),(a,u)=>sR(i,ry.of(u)))}),{})}}function Lfa(e,t={}){return{...Object.fromEntries(vN(e.packageMarkers).map(([r,i])=>[r,{...i,defaultUrl:t.defaultURL}])),...vN(e.importedDefinitions).reduce((r,[i,n])=>({...r,...Pkn(Lfa(n.definition,{defaultURL:n.url}),(a,u)=>sR(i,ry.of(u)))}),{})}}function sQr(e){return{...Lfa(e),...Uli(e)}}function aie(e,t){return sQr(e.definition)[t]?.contents}function XN(e,t){for(let[r,i]of vN(sQr(e.definition)))t(r,i.contents,{isPackageMarker:XAi(r)===W1,defaultUrl:i.defaultUrl})}function CIi(e,t){for(let[r,i]of vN(Lfa(e.definition)))t(r,i.contents)}var P5p=vi(m5p(),1);async function Cda(e){return(await(0,P5p.convertObj)(e,{})).openapi}var w5p=require("fs/promises");var j5p=require("fs/promises");async function aCo({absoluteFilePathToOverrides:e,data:t,context:r,allowNullKeys:i}){let n=null;try{let a=(await(0,j5p.readFile)(e,"utf8")).toString();try{n=JSON.parse(a)}catch{n=rp.load(a,{json:!0})}}catch{return r.failAndThrow(`Failed to read overrides from file ${e}`)}return Hus({data:t,overrides:n,allowNullKeys:i})}async function S5p({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let i=(await(0,w5p.readFile)(t)).toString(),n=await rp.load(i);return r!=null?await aCo({absoluteFilePathToOverrides:r,context:e,data:n}):n}var xda=vi(Cqo(),1);var D5p=vi(Cqo(),1),wUs=vi(require("path"),1);var Bda=class extends D5p.BaseResolver{absolutePathToOpenAPIOverrides;constructor(t){super(),this.absolutePathToOpenAPIOverrides=t}resolveExternalRef(t,r){let i=super.resolveExternalRef(t,r);return wHr(Wl.of(i))?i:this.absolutePathToOpenAPIOverrides!=null?wUs.default.resolve(wUs.default.dirname(this.absolutePathToOpenAPIOverrides),r):i}};async function SUs({absolutePathToOpenAPI:e,absolutePathToOpenAPIOverrides:t,parsed:r}){return(r!=null?await(0,xda.bundle)({...Xqo,doc:{source:new xda.Source(e,"<openapi>"),parsed:r},externalRefResolver:new Bda(t)}):await(0,xda.bundle)({...Xqo,ref:e,externalRefResolver:new Bda(t)})).bundle.parsed}var DBD=["examples","example",fd.EXAMPLES,kU.REDOCLY_CODE_SAMPLES_CAMEL,kU.REDOCLY_CODE_SAMPLES_KEBAB];async function Ida({context:e,absolutePathToOpenAPI:t,absolutePathToOpenAPIOverrides:r}){let i=await SUs({absolutePathToOpenAPI:t}),n;if(r!=null?n=r:typeof i=="object"&&i[fd.OPENAPI_OVERIDES_FILEPATH]!=null&&(n=Xu(fp(t),Xa.of(i[fd.OPENAPI_OVERIDES_FILEPATH]))),n!=null){let a=await aCo({absoluteFilePathToOverrides:n,context:e,data:i,allowNullKeys:DBD});return await SUs({absolutePathToOpenAPI:t,absolutePathToOpenAPIOverrides:r,parsed:a})}return i}var e5t=class{absoluteFilePath;constructor(t){this.absoluteFilePath=t}async loadDocuments({context:t,specs:r}){let i=[];for(let n of r){let a=(await(0,E5p.readFile)(n.absoluteFilepath)).toString(),u=Qq(this.absoluteFilePath,n.source.file);n.source.relativePathToDependency!=null&&(u=Xu(n.source.relativePathToDependency,u));let l=n.source.type==="protobuf"?Kre.protobuf({file:u}):Kre.openapi({file:u});if(a.includes("openapi")||a.includes("swagger")){let d=await Ida({absolutePathToOpenAPI:n.absoluteFilepath,context:t,absolutePathToOpenAPIOverrides:n.absoluteFilepathToOverrides});if(m9s(d))i.push({type:"openapi",value:d,source:l,namespace:n.namespace,settings:n.settings});else if(Ffa(d)){let s=await Cda(d);i.push({type:"openapi",value:s,source:l,namespace:n.namespace,settings:n.settings})}}else if(a.includes("asyncapi")){let d=await S5p({context:t,absoluteFilePath:n.absoluteFilepath,absoluteFilePathToOverrides:n.absoluteFilepathToOverrides});i.push({type:"asyncapi",value:d,source:l,namespace:n.namespace,settings:n.settings})}else t.failAndThrow(`${n.absoluteFilepath} is not a valid OpenAPI or AsyncAPI file`)}return i}};var hCo=require("fs/promises"),rLp=vi(fte(),1);var tLp=vi(eLp(),1);async function eG(e,t,r=[],{doNotPipeOutput:i=!1,secrets:n=[],substitutions:a={},...u}={}){let l=n.reduce((o,c)=>({...o,[c]:"<redacted>"}),a),d=[t,...r].join(" ");for(let[o,c]of Object.entries(l))d=d.replaceAll(o,c);e?.debug(`+ ${d}`);let s=(0,tLp.default)(t,r,u);return i||(s.stdout?.pipe(process.stdout),s.stderr?.pipe(process.stderr)),s.then(o=>(o.stdout==null&&(o.stdout=""),o.stderr==null&&(o.stderr=""),o))}function pCo(e,{logger:t,...r}={}){return(i,n)=>eG(t,e,i,{...r,...n})}var gID="buf.gen.yaml",iLp="output",OID=`${iLp}/openapi.yaml`,_Co=class{context;constructor({context:t}){this.context=t}async generate({absoluteFilepathToProtobufRoot:t,absoluteFilepathToProtobufTarget:r,relativeFilepathToProtobufRoot:i,local:n}){return n?this.generateLocal({absoluteFilepathToProtobufRoot:t,absoluteFilepathToProtobufTarget:r,relativeFilepathToProtobufRoot:i}):this.generateRemote()}async generateLocal({absoluteFilepathToProtobufRoot:t,absoluteFilepathToProtobufTarget:r,relativeFilepathToProtobufRoot:i}){let n=await this.setupProtobufGeneratorConfig({absoluteFilepathToProtobufRoot:t,relativeFilepathToProtobufRoot:i}),a=Qq(t,r);return this.doGenerateLocal({cwd:n,target:a})}async setupProtobufGeneratorConfig({absoluteFilepathToProtobufRoot:t,relativeFilepathToProtobufRoot:r}){let i=Wl.of((await rLp.default.dir()).path);return await(0,hCo.cp)(t,i,{recursive:!0}),await(0,hCo.writeFile)(Xu(i,Xa.of(gID)),mID({relativeFilepathToProtobufRoot:r})),i}async doGenerateLocal({cwd:t,target:r}){let i=pCo("which",{cwd:t,logger:this.context.logger});try{await i(["buf"])}catch{this.context.failAndThrow("Missing required dependency; please install 'buf' to continue (e.g. 'brew install buf').")}try{await i(["protoc-gen-openapi"])}catch{this.context.failAndThrow("Missing required dependency; please install 'protoc-gen-openapi' to continue (e.g. 'brew install go && go install github.com/fern-api/protoc-gen-openapi/cmd/protoc-gen-openapi@latest').")}let n=pCo("buf",{cwd:t,logger:this.context.logger});return await n(["config","init"]),await n(["generate",r]),Xu(t,Xa.of(OID))}async generateRemote(){this.context.failAndThrow("Remote Protobuf generation is unimplemented.")}};function mID({relativeFilepathToProtobufRoot:e}){return`
|
|
1937
1937
|
version: v1
|
|
1938
1938
|
plugins:
|
|
1939
1939
|
- plugin: openapi
|
|
@@ -1968,7 +1968,7 @@ ${b}
|
|
|
1968
1968
|
`)}];if(t["base-properties"]!=null){let q=Object.fromEntries(Object.entries(c).filter(([C])=>t["base-properties"]?.[C]!=null)),D=Gzi({typeName:e,typeNameForBreadcrumb:e,rawObject:{properties:t["base-properties"]},file:a,example:q,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:d+1});if(D.length>0)return D}let g=typeof b=="string"?b:b.type;if(typeof g!="string")return mr_(c);let O=i.resolveType({type:g,file:a});if(O==null)return[];if(O._type==="named"&&G1(O.declaration)){let q=Object.fromEntries(Object.entries(c).filter(([D])=>t["base-properties"]?.[D]==null));return Gzi({typeName:e,typeNameForBreadcrumb:e,rawObject:O.declaration,file:O.file,example:q,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:d+1})}let m=typeof b!="string"&&typeof b.key=="string"?b.key:void 0;if(m==null)return[];let{[m]:w,...E}=c,A=[];return w==null?A.push({message:`Missing property "${m}"`}):A.push(...h5({rawTypeReference:g,example:w,typeResolver:i,exampleResolver:n,file:a,workspace:u,breadcrumbs:l,depth:d+1})),A.push(...mr_(E)),A}function mr_(e){return Object.keys(e).map(t=>({severity:"fatal",message:`Unexpected property "${t}"`}))}function pzo({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,example:a,workspace:u,breadcrumbs:l,depth:d}){return xN(t,{alias:s=>_r_({rawAlias:s,file:r,typeResolver:i,exampleResolver:n,example:a,workspace:u,breadcrumbs:l,depth:d}),enum:s=>hr_({rawEnum:s,example:a,breadcrumbs:l}),object:s=>Gzi({typeName:e,typeNameForBreadcrumb:e,rawObject:s,example:a,file:r,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:d}),discriminatedUnion:s=>Pr_({typeName:e,rawUnion:s,example:a,file:r,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:d}),undiscriminatedUnion:s=>yr_({rawUnion:s,example:a,file:r,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:d})})}var Tr_=/^([+-]?\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)?)?)?)?$/,aGD=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,oGD=/^\d{4}-\d{2}-\d{2}$/,uGD=128;function h5({rawTypeReference:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:u,depth:l}){if(l>uGD)return[{message:"Example is too deeply nested. This may indicate a circular reference."}];if(typeof t=="string"&&t.startsWith(NGt)){let d=r.resolveType({type:e,file:n});if(d==null)return[];let s=i.parseExampleReference(t);if(s==null)return[];let o=r.resolveNamedType({referenceToNamedType:s.rawTypeReference,file:n});return o==null?[]:h1n({expected:d,actual:o})?[]:[{message:`Expected example to be: ${e}. Example is ${t}.`}]}return sTi({type:e,_default:void 0,validation:void 0,visitor:{primitive:d=>sGD({primitiveType:d,example:t}),named:d=>{let s=r.getDeclarationOfNamedType({referenceToNamedType:d,file:n});return s==null?[]:pzo({typeName:s.typeName,typeDeclaration:s.declaration,file:s.file,example:t,typeResolver:r,exampleResolver:i,workspace:a,breadcrumbs:u,depth:l+1})},map:({keyType:d,valueType:s})=>Hj(t)?Object.entries(t).flatMap(([o,c])=>[...h5({rawTypeReference:d,example:o,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,o],depth:l+1}),...h5({rawTypeReference:s,example:c,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,o],depth:l+1})]):tze(t,"a map"),list:d=>Array.isArray(t)?t.flatMap((s,o)=>h5({rawTypeReference:d,example:s,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,`${o}`],depth:l+1})):tze(t,"a list"),set:d=>{if(!Array.isArray(t))return tze(t,"a list");let s=Ous(t);return s.length>0?[{severity:"fatal",message:`Set has duplicate elements:
|
|
1969
1969
|
`+s.map(o=>` - ${JSON.stringify(o)}`).join(`
|
|
1970
1970
|
`)}]:t.flatMap((o,c)=>h5({rawTypeReference:d,example:o,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,`${c}`],depth:l+1}))},optional:d=>t==null?[]:h5({rawTypeReference:d,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:u,depth:l+1}),nullable:d=>t==null?[]:h5({rawTypeReference:d,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:u,depth:l+1}),unknown:()=>[],literal:d=>{switch(d.type){case"boolean":return jSe(s=>s===d.boolean,d.boolean.toString())(t);case"string":return jSe(s=>s===d.string,`"${d.string}"`)(t);default:Ko(d)}}}})}function sGD({primitiveType:e,example:t}){return e.v2!=null?Tv._visit(e.v2,{integer:r=>cGD({example:t,rules:r.validation}),long:()=>Dr_(t),uint:()=>jr_(t),uint64:()=>wr_(t),double:r=>lGD({example:t,rules:r.validation}),float:()=>Sr_(t),boolean:()=>Er_(t),string:r=>fGD({example:t,rules:r.validation}),uuid:()=>Mr_(t),date:()=>qr_(t),dateTime:()=>Ar_(t),base64:()=>_1n(t),bigInteger:()=>_1n(t),_other:()=>{throw new Error("Unknown primitive type v2: "+e.v2)}}):l0._visit(e.v1,{integer:()=>Cr_(t),long:()=>Dr_(t),uint:()=>jr_(t),uint64:()=>wr_(t),double:()=>Br_(t),float:()=>Sr_(t),boolean:()=>Er_(t),string:()=>_1n(t),uuid:()=>Mr_(t),dateTime:()=>Ar_(t),date:()=>qr_(t),base64:()=>_1n(t),bigInteger:()=>_1n(t),_other:()=>{throw new Error("Unknown primitive type: "+e.v1)}})}function cGD({example:e,rules:t}){let r=Cr_(e);if(r.length>0||t==null)return r;let i=e;return t.min!=null&&(t.exclusiveMin&&i<=t.min||!t.exclusiveMin&&i<t.min)?[{message:`Expected integer to be greater than or equal to ${t.min}. Example is ${e}.`}]:t.max!=null&&(t.exclusiveMax&&i>=t.max||!t.exclusiveMax&&i>t.max)?[{message:`Expected integer to be less than or equal to ${t.max}. Example is ${e}.`}]:t.multipleOf!=null&&i%t.multipleOf!==0?[{message:`Expected integer to be a multiple of ${t.multipleOf}. Example is ${e}.`}]:[]}function lGD({example:e,rules:t}){let r=Br_(e);if(r.length>0||t==null)return r;let i=e;return t.min!=null&&(t.exclusiveMin&&i<=t.min||!t.exclusiveMin&&i<t.min)?[{message:`Expected double to be greater than or equal to ${t.min}. Example is ${e}.`}]:t.max!=null&&(t.exclusiveMax&&i>=t.max||!t.exclusiveMax&&i>t.max)?[{message:`Expected double to be less than or equal to ${t.max}. Example is ${e}.`}]:t.multipleOf!=null&&i%t.multipleOf!==0?[{message:`Expected double to be a multiple of ${t.multipleOf}. Example is ${e}.`}]:[]}function fGD({example:e,rules:t}){let r=_1n(e);if(r.length>0||t==null)return r;let i=e;return t.minLength!=null&&i.length<t.minLength?[{message:`Expected string length to be greater than or equal to ${t.minLength}. Example is ${e}, which is of length ${i.length}.`}]:t.maxLength!=null&&i.length>t.maxLength?[{message:`Expected string length to be less than or equal to ${t.maxLength}. Example is ${e}, which is of length ${i.length}.`}]:t.pattern!=null&&!new RegExp(t.pattern).test(i)?[{message:`Expected string to match pattern ${t.pattern}. Example is ${e}.`}]:[]}var _1n=jSe(e=>typeof e=="string","a string"),Cr_=jSe(e=>Number.isInteger(e),"an integer"),jr_=jSe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint"),wr_=jSe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint64"),Sr_=jSe(e=>typeof e=="number","a float"),Br_=jSe(e=>typeof e=="number","a double"),Dr_=jSe(e=>Number.isInteger(e),"an integer"),Er_=jSe(e=>typeof e=="boolean","a boolean"),Mr_=jSe(e=>typeof e=="string"&&aGD.test(e),"a UUID"),Ar_=jSe(e=>typeof e=="string"&&Tr_.test(e),"an ISO 8601 timestamp"),qr_=jSe(e=>typeof e=="string"&&oGD.test(e)&&Tr_.test(e),"a date");function jSe(e,t){return r=>e(r)?[]:tze(r,t)}function h1n({expected:e,actual:t}){if(e._type==="unknown")return!0;if(e._type==="primitive")return t._type==="primitive"&&e.primitive.v1===t.primitive.v1;if(e._type==="container")switch(e.container._type){case"list":case"set":return t._type==="container"&&t.container._type===e.container._type&&h1n({expected:e.container.itemType,actual:t.container.itemType});case"optional":return h1n({expected:e.container.itemType,actual:t._type==="container"&&t.container._type==="optional"?t.container.itemType:t});case"nullable":return h1n({expected:e.container.itemType,actual:t._type==="container"&&t.container._type==="nullable"?t.container.itemType:t});case"map":return t._type==="container"&&t.container._type===e.container._type&&h1n({expected:e.container.keyType,actual:t.container.keyType})&&h1n({expected:e.container.valueType,actual:t.container.valueType});case"literal":return t._type!=="container"||t.container._type!==e.container._type?!1:dGD({expected:e.container.literal,actual:t.container.literal});default:Ko(e.container)}if(e._type==="named")return t._type==="named"&&t.filepath===e.filepath&&t.rawName===e.rawName;Ko(e)}function dGD({expected:e,actual:t}){switch(e.type){case"boolean":return t.type==="boolean"?e.boolean===t.boolean:!1;case"string":return t.type==="string"?e.string===t.string:!1;default:Ko(e)}}function _zo({_enum:e,file:t}){let r=e.enum.map(n=>({...uG(n),name:t.casingsGenerator.generateNameAndWireValue({wireValue:typeof n=="string"?n:n.value,name:y1n(n).name,opts:{casingOverrides:typeof n!="string"?n.casing:void 0}})})),i;if(e.default!=null&&(i=r.find(n=>n.name.wireValue===e.default),i==null))throw new Error(`Default value ${e.default} not found in enum values`);return{default:i,values:r}}function xr_(e,t){let r=t.enum.find(i=>typeof i=="string"?!1:i.value===e);return{name:typeof r=="string"?e:r?.name??e,wasExplicitlySet:!1}}function y1n(e){return typeof e=="string"?{name:e,wasExplicitlySet:!1}:e.name==null?{name:e.value,wasExplicitlySet:!1}:{name:e.name,wasExplicitlySet:!0}}function iKs({typeName:e,typeDeclaration:t,example:r,typeResolver:i,exampleResolver:n,fileContainingType:a,fileContainingExample:u,workspace:l}){return xN(t,{alias:d=>Qj.alias({value:rE({example:r,rawTypeBeingExemplified:typeof d=="string"?d:d.type,fileContainingRawTypeReference:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,workspace:l})}),object:d=>Ir_({typeName:e,rawObject:d,example:r,fileContainingType:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,workspace:l}),discriminatedUnion:d=>{let s=Qzi(d);if(!Hj(r))throw new Error("Example is not an object");let o=r[s];if(o==null)throw new Error("Example is missing discriminant: "+s);if(typeof o!="string")throw new Error("Discriminant value is not a string");let c=d.union[o];if(c==null)throw new Error(`${o} is not one of the specified discriminant values.`);let b=typeof c=="string"?c:typeof c.type=="string"?c.type:void 0;return Qj.union({discriminant:u.casingsGenerator.generateNameAndWireValue({name:Gfi(d).name,wireValue:s}),singleUnionType:_GD({rawValueType:b,rawSingleUnionType:c,fileContainingType:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,example:r,discriminant:s,discriminantValueForExample:o,workspace:l})})},enum:d=>{if(typeof r!="string"){let s=d.enum.map(o=>typeof o=="string"?o:o.value).join(", ");throw new Error(`Expected one of ${s}. Received ${r}`)}return Qj.enum({value:u.casingsGenerator.generateNameAndWireValue({name:xr_(r,d).name,wireValue:r})})},undiscriminatedUnion:d=>{for(let[c,b]of d.union.entries())if(h5({rawTypeReference:typeof b=="string"?b:b.type,example:r,typeResolver:i,exampleResolver:n,file:a,workspace:l,breadcrumbs:[],depth:0}).length===0)return Qj.undiscriminatedUnion({index:c,singleUnionType:rE({example:r,rawTypeBeingExemplified:typeof b=="string"?b:b.type,fileContainingRawTypeReference:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,workspace:l})});let o=d.union.map(c=>typeof c=="string"?c:c.type).join(", ");throw new Error(`Expected one of ${o}. Received ${r}`)}})}function rE({example:e,fileContainingExample:t,rawTypeBeingExemplified:r,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}){let{resolvedExample:l,file:d}=a.resolveExampleOrThrow({example:e,file:t}),s=a.resolveAllReferencesInExampleOrThrow({example:e,file:t}).resolvedExample;return{shape:sTi({type:r,_default:void 0,validation:void 0,visitor:{primitive:c=>pGD({example:l,typeBeingExemplified:c.v1}),map:({keyType:c,valueType:b})=>{if(!Hj(l))throw new Error("Example is not an object");return mb.container(NO.map({map:Object.entries(l).map(([g,O])=>({key:rE({example:g,fileContainingExample:d,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}),value:rE({example:O,fileContainingExample:d,rawTypeBeingExemplified:b,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u})})),keyType:i.parseTypeReference(c),valueType:i.parseTypeReference(b)}))},list:c=>{if(!Array.isArray(l))throw new Error("Example is not a list");return mb.container(NO.list({list:l.map(b=>rE({example:b,fileContainingExample:d,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u})),itemType:i.parseTypeReference(c)}))},set:c=>{if(!Array.isArray(l))throw new Error("Example is not a list");return mb.container(NO.set({set:l.map(b=>rE({example:b,fileContainingExample:d,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u})),itemType:i.parseTypeReference(c)}))},optional:c=>mb.container(NO.optional({optional:l!=null?rE({example:l,fileContainingExample:d,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}):void 0,valueType:i.parseTypeReference(c)})),nullable:c=>mb.container(NO.nullable({nullable:l!=null?rE({example:l,fileContainingExample:d,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}):void 0,valueType:i.parseTypeReference(c)})),literal:c=>{switch(c.type){case"boolean":return mb.container(NO.literal({literal:e_.boolean(c.boolean)}));case"string":return mb.container(NO.literal({literal:e_.string({original:c.string})}));default:Ko(c)}},named:c=>{let b=n.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:r,file:i}),g=i.parseTypeReference(c);if(g.type!=="named")throw new Error("Type reference is not to a named type.");let O={typeId:g.typeId,fernFilepath:g.fernFilepath,name:g.name};return mb.named({typeName:O,shape:iKs({typeName:O,typeDeclaration:b.declaration,fileContainingType:b.file,fileContainingExample:d,example:l,typeResolver:n,exampleResolver:a,workspace:u})})},unknown:()=>mb.unknown(s)}}),jsonExample:s}}function pGD({example:e,typeBeingExemplified:t}){return l0._visit(t,{string:()=>{if(typeof e!="string")throw new Error(`Expected string. Received ${e}`);return mb.primitive(e_.string({original:e}))},dateTime:()=>{if(typeof e!="string")throw new Error(`Expected ISO datetime. Received ${e}`);return mb.primitive(e_.datetime({datetime:new Date(e),raw:e}))},date:()=>{if(typeof e!="string")throw new Error(`Expected ISO date. Received ${e}`);return mb.primitive(e_.date(e))},base64:()=>{if(typeof e!="string")throw new Error(`Expected base64 encoded string. Received ${e}`);return mb.primitive(e_.string({original:e}))},uint:()=>{if(typeof e!="number")throw new Error(`Expected unsigned integer. Received ${e}`);return mb.primitive(e_.uint(e))},uint64:()=>{if(typeof e!="number")throw new Error(`Expected unsigned 64-bit integer. Received ${e}`);return mb.primitive(e_.uint64(e))},integer:()=>{if(typeof e!="number")throw new Error(`Expected integer. Received ${e}`);return mb.primitive(e_.integer(e))},float:()=>{if(typeof e!="number")throw new Error(`Expected float. Received ${e}`);return mb.primitive(e_.float(e))},double:()=>{if(typeof e!="number")throw new Error(`Expected double. Received ${e}`);return mb.primitive(e_.double(e))},long:()=>{if(typeof e!="number")throw new Error(`Expected long. Received ${e}`);return mb.primitive(e_.long(e))},boolean:()=>{if(typeof e!="boolean")throw new Error(`Expected boolean. Received ${e}`);return mb.primitive(e_.boolean(e))},uuid:()=>{if(typeof e!="string")throw new Error(`Expected uuid. Received ${e}`);return mb.primitive(e_.uuid(e))},bigInteger:()=>{if(typeof e!="string")throw new Error(`Expected big integer. Received ${e}`);return mb.primitive(e_.string({original:e}))},_other:()=>{throw new Error("Unknown primitive type: "+t)}})}function Ir_({typeName:e,rawObject:t,example:r,fileContainingType:i,fileContainingExample:n,typeResolver:a,exampleResolver:u,workspace:l}){if(!Hj(r))throw new Error(`Example is not an object. Got: ${JSON.stringify(r)}`);return Qj.object({properties:t.properties!=null||t.extends!=null?Object.entries(r).reduce((d,[s,o])=>{let c=zr_({typeName:e,wirePropertyKey:s,rawObject:t,typeResolver:a,file:i});if(c==null)return d;let b=rE({example:o,fileContainingExample:n,rawTypeBeingExemplified:typeof c.rawPropertyType=="string"?c.rawPropertyType:c.rawPropertyType.type,fileContainingRawTypeReference:c.file,typeResolver:a,exampleResolver:u,workspace:l});return d.push({name:n.casingsGenerator.generateNameAndWireValue({name:uV({propertyKey:s,property:c.rawPropertyType}).name,wireValue:s}),value:b,originalTypeDeclaration:c.typeName}),d},[]):[]})}function zr_({typeName:e,wirePropertyKey:t,rawObject:r,typeResolver:i,file:n}){let a=r.properties?.[t];return a!=null?{typeName:e,rawPropertyType:a,file:n}:N_a({wirePropertyKey:t,extends_:r.extends,typeResolver:i,file:n})}function N_a({wirePropertyKey:e,extends_:t,typeResolver:r,file:i}){if(t!=null){let n=typeof t=="string"?[t]:t;for(let a of n){let u=r.resolveNamedTypeOrThrow({referenceToNamedType:a,file:i});if(u._type!=="named"||!G1(u.declaration))throw new Error("Extension is not of a named object");let l=zr_({wirePropertyKey:e,rawObject:u.declaration,typeResolver:r,typeName:u.name,file:u.file});if(l!=null)return l}}}function _GD({rawValueType:e,rawSingleUnionType:t,fileContainingType:r,fileContainingExample:i,typeResolver:n,exampleResolver:a,example:u,discriminant:l,discriminantValueForExample:d,workspace:s}){let o=i.casingsGenerator.generateNameAndWireValue({name:p1n({unionKey:d,rawSingleUnionType:t}).name,wireValue:d});if(e==null)return{wireDiscriminantValue:o,shape:CN.noProperties()};let c=rKs({rawSingleUnionType:t,rawValueType:e,parsedValueType:r.parseTypeReference(e),file:r,typeResolver:n});switch(c.propertiesType){case"singleProperty":{if(!Hj(u))throw new Error("Example is not an object");return{wireDiscriminantValue:o,shape:CN.singleProperty(rE({example:u[c.name.wireValue],rawTypeBeingExemplified:e,typeResolver:n,exampleResolver:a,fileContainingRawTypeReference:r,fileContainingExample:i,workspace:s}))}}case"samePropertiesAsObject":{if(!Hj(u))throw new Error("Example is not an object");let{[l]:b,...g}=u,O=n.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:e,file:r});for(;Foi(O.declaration);)O=n.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:typeof O.declaration=="string"?O.declaration:O.declaration.type,file:r});if(!G1(O.declaration))throw new Error(`${e} is not an object`);let m={typeId:c.typeId,fernFilepath:c.fernFilepath,name:c.name};return{wireDiscriminantValue:o,shape:CN.samePropertiesAsObject({typeId:Ng.generateTypeId(m),object:Ir_({rawObject:O.declaration,example:g,fileContainingType:O.file,fileContainingExample:i,typeResolver:n,exampleResolver:a,typeName:m,workspace:s})})}}default:Ko(c)}}function hzo({file:e,queryParameterKey:t,queryParameter:r}){let{name:i}=FQr({queryParameterKey:t,queryParameter:r}),n=e.parseTypeReference(r);return{...uG(r),name:e.casingsGenerator.generateNameAndWireValue({wireValue:t,name:i}),valueType:n,allowMultiple:typeof r!="string"&&r["allow-multiple"]!=null?r["allow-multiple"]:!1}}function FQr({queryParameterKey:e,queryParameter:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function Rr_({service:e,endpoint:t,example:r,typeResolver:i,errorResolver:n,exampleResolver:a,variableResolver:u,file:l,workspace:d}){let s=yGD({service:e,endpoint:t,example:r,typeResolver:i,exampleResolver:a,variableResolver:u,file:l,workspace:d});return{id:r.name??cpa(r),name:r.name!=null?l.casingsGenerator.generateName(r.name):void 0,docs:r.docs,url:mGD({file:l,service:e,endpoint:t,example:r,pathParams:s}),...s,...vGD({service:e,endpoint:t,example:r,typeResolver:i,exampleResolver:a,file:l,workspace:d}),queryParameters:r["query-parameters"]!=null?Object.entries(r["query-parameters"]).map(([o,c])=>{let b=typeof t.request!="string"?t.request?.["query-parameters"]?.[o]:void 0;if(b==null)throw new Error(`Query parameter ${o} does not exist`);return{name:l.casingsGenerator.generateNameAndWireValue({name:FQr({queryParameterKey:o,queryParameter:b}).name,wireValue:o}),value:rE({example:c,rawTypeBeingExemplified:typeof b=="string"?b:b.type,typeResolver:i,exampleResolver:a,fileContainingRawTypeReference:l,fileContainingExample:l,workspace:d}),shape:hGD({queryParameter:b})}}):[],request:bGD({endpoint:t,example:r,typeResolver:i,exampleResolver:a,file:l,workspace:d}),response:gGD({endpoint:t,example:r,typeResolver:i,errorResolver:n,exampleResolver:a,file:l,workspace:d})}}function hGD({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?Q6.exploded():Q6.single()}function yGD({service:e,endpoint:t,example:r,typeResolver:i,exampleResolver:n,variableResolver:a,file:u,workspace:l}){let d=[],s=[],o=[],c=({name:b,pathParameterDeclaration:g,examplePathParameter:O})=>{let m=F_a({parameter:g,variableResolver:a,file:u});return{name:b,value:rE({example:O,rawTypeBeingExemplified:m.rawType,typeResolver:i,exampleResolver:n,fileContainingRawTypeReference:m.file,fileContainingExample:u,workspace:l})}};if(r["path-parameters"]!=null){let b=_5t(t);for(let[g,O]of Object.entries(r["path-parameters"])){let m=u.rootApiFile["path-parameters"]?.[g],w=e["path-parameters"]?.[g],E=b[g];if(m!=null)d.push(c({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:m,examplePathParameter:O}));else if(E!=null)o.push(c({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:E,examplePathParameter:O}));else if(w!=null)s.push(c({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:w,examplePathParameter:O}));else throw new Error(`Path parameter ${g} does not exist`)}}return{rootPathParameters:d,endpointPathParameters:o,servicePathParameters:s}}function vGD({service:e,endpoint:t,example:r,typeResolver:i,exampleResolver:n,file:a,workspace:u}){let l=[],d=[];if(r.headers!=null)for(let[s,o]of Object.entries(r.headers)){let c=typeof t.request!="string"?t.request?.headers?.[s]:void 0,b=e.headers?.[s];if(c!=null)d.push({name:a.casingsGenerator.generateNameAndWireValue({name:nXt({headerKey:s,header:c}).name,wireValue:s}),value:rE({example:o,rawTypeBeingExemplified:typeof c=="string"?c:c.type,typeResolver:i,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})});else if(b!=null)l.push({name:a.casingsGenerator.generateNameAndWireValue({name:nXt({headerKey:s,header:b}).name,wireValue:s}),value:rE({example:o,rawTypeBeingExemplified:typeof b=="string"?b:b.type,typeResolver:i,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})});else throw new Error(`Header ${s} does not exist`)}return{endpointHeaders:d,serviceHeaders:l}}function bGD({endpoint:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){let u=typeof e.request!="string"?e.request?.body:e.request;if(u==null||typeof u=="string"&&fra(u)!=null)return;if(!zT(u))return y$.reference(rE({example:t.request,rawTypeBeingExemplified:typeof u!="string"?u.type:u,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}));if(!t.request)return;if(!Hj(t.request))throw new Error(`Example is not an object. Got: ${JSON.stringify(t.request)}`);let l=[];for(let[d,s]of Object.entries(t.request)){let o=u.properties?.[d],c=typeof o=="string"?o:o?.type;if(!(c!=null&&EBe(c)!=null))if(o!=null)l.push({name:n.casingsGenerator.generateNameAndWireValue({name:uV({propertyKey:d,property:o}).name,wireValue:d}),value:rE({example:s,rawTypeBeingExemplified:typeof o!="string"?o.type:o,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),originalTypeDeclaration:void 0});else{let b=N_a({extends_:u.extends,wirePropertyKey:d,typeResolver:r,file:n});if(b==null)throw new Error("Could not find original type declaration for property: "+d);l.push({name:n.casingsGenerator.generateNameAndWireValue({name:uV({propertyKey:d,property:b.rawPropertyType}).name,wireValue:d}),value:rE({example:s,rawTypeBeingExemplified:typeof b.rawPropertyType=="string"?b.rawPropertyType:b.rawPropertyType.type,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:b.file,fileContainingExample:n,workspace:a}),originalTypeDeclaration:b.typeName})}}return y$.inlinedRequestBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t.request,file:n}).resolvedExample,properties:l})}function gGD({endpoint:e,example:t,typeResolver:r,errorResolver:i,exampleResolver:n,file:a,workspace:u}){return t.response==null?mq.ok(RT.body(void 0)):lTi(e,t.response,{body:l=>{if(l.error!=null){let d=i.getDeclarationOrThrow(l.error,a);return mq.error({error:Hfi({errorName:l.error,file:a}),body:d.declaration.type!=null?rE({example:l.body,rawTypeBeingExemplified:d.declaration.type,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:d.file,fileContainingExample:a,workspace:u}):void 0})}return mq.ok(RT.body(OGD({endpoint:e,example:l,typeResolver:r,exampleResolver:n,file:a,workspace:u})))},stream:l=>{let d=typeof e["response-stream"]=="string"?e["response-stream"]:e["response-stream"]?.type;return mq.ok(RT.stream(l.stream.map(s=>{if(d!=null)return rE({example:s,rawTypeBeingExemplified:d,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})}).filter(u0)))},events:l=>{let d=typeof e["response-stream"]=="string"?e["response-stream"]:e["response-stream"]?.type;return mq.ok(RT.sse(l.stream.map(({event:s,data:o})=>{if(d==null)return;let c=rE({example:o,rawTypeBeingExemplified:d,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u});return{event:s,data:c}}).filter(u0)))}})}function OGD({endpoint:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){let u=typeof e.response!="string"?e.response?.type:e.response;if(u!=null&&t.body!=null)return rE({example:t.body,rawTypeBeingExemplified:u,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a})}function mGD({file:e,service:t,endpoint:r,example:i,pathParams:n}){let a=Cv(e.rootApiFile["base-path"]??"",t["base-path"],r.path);if(i["path-parameters"]!=null)for(let u of[...n.endpointPathParameters,...n.servicePathParameters,...n.rootPathParameters])a=a.replaceAll(`{${u.name.originalName}}`,`${u.value.jsonExample}`);return a=a.replaceAll("//","/"),a.startsWith("/")||(a=`/${a}`),a}function Nr_({endpoint:e,file:t,typeResolver:r}){return{body:PGD({endpoint:e,file:t,typeResolver:r}),statusCode:typeof e.response!="string"?e.response?.["status-code"]:void 0}}function PGD({endpoint:e,file:t,typeResolver:r}){let i=jGD({endpoint:e,file:t,typeResolver:r}),n=wGD({endpoint:e,file:t,typeResolver:r});if(i!=null&&n!=null){let a;switch(i.type){case"fileDownload":{a=pU.fileDownload({...i});break}case"json":{a=pU.json({...i.value});break}case"text":{a=pU.text({...i});break}case"bytes":{a=pU.bytes({...i});break}default:Ko(i)}return Xq.streamParameter({nonStreamResponse:a,streamResponse:n})}else{if(i!=null)return i;if(n!=null)return Xq.streaming(n)}}function jGD({endpoint:e,file:t,typeResolver:r}){let{response:i}=e;if(i!=null){let n=typeof i!="string"?i.docs:void 0,a=typeof i=="string"?i:i.type;if(a!=null)return EBe(a)!=null?Xq.fileDownload({docs:n}):dra(a)!=null?Xq.text({docs:n}):KGt(a)!=null?Xq.bytes({docs:n}):SGD(i,n,t,r)}}function wGD({endpoint:e,file:t,typeResolver:r}){let{["response-stream"]:i}=e;if(i!=null){let n=typeof i!="string"?i.docs:void 0,a=typeof i=="string"?i:i.type,u=typeof i=="string"?"json":i.format??"json";return C_n(a)?Jte.text({docs:n}):typeof i!="string"&&u==="sse"?Jte.sse({docs:n,payload:t.parseTypeReference(a),terminator:typeof i!="string"?i.terminator:void 0}):Jte.json({docs:n,payload:t.parseTypeReference(a),terminator:typeof i!="string"?i.terminator:void 0})}}function SGD(e,t,r,i){let n=typeof e!="string"?e.type:e;if(n==null)return;let a=r.parseTypeReference(typeof e=="string"?e:{...e,type:n}),u=i.resolveTypeOrThrow({type:n,file:r}),l=typeof e!="string"?e.property:void 0;return l!=null?Xq.json(T1e.nestedPropertyAsResponse({docs:t,responseBodyType:a,responseProperty:x_a({typeResolver:i,file:r,resolvedType:u,property:l})})):Xq.json(T1e.response({docs:t,responseBodyType:a}))}function Fr_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:n}){return h$.cursor({page:e.resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:n.cursor}),next:e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:n.next_cursor}),results:e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:n.results})})}function Lr_({propertyResolver:e,file:t,endpointName:r,paginationPropertyComponents:i}){return h$.custom({results:e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i.results})})}function Ur_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:n}){return h$.offset({page:e.resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:n.offset}),results:e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:n.results}),step:n.step!=null?e.resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:n.step}):void 0,hasNextPage:n.hasNextPage!=null?e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:n.hasNextPage}):void 0})}function Vr_(e){if(EGD(e))return{type:"offset",offset:p5t(e.offset),results:iXt(e.results),step:e.step!=null?p5t(e.step):void 0,hasNextPage:e["has-next-page"]!=null?iXt(e["has-next-page"]):void 0};if(DGD(e))return{type:"cursor",cursor:p5t(e.cursor),next_cursor:iXt(e.next_cursor),results:iXt(e.results)};if(MGD(e))return{type:"custom",results:iXt(e.results)};throw new Error("Invalid pagination schema")}function DGD(e){return e.cursor!=null}function EGD(e){return e.offset!=null&&e.results!=null}function MGD(e){return"type"in e&&e.type==="custom"}function Wr_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i}){let n=typeof i.pagination=="boolean"?t.rootApiFile.pagination:i.pagination;if(!n)return;let a=Vr_(n);switch(a.type){case"cursor":return Fr_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:a});case"offset":return Ur_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:a});case"custom":return Lr_({propertyResolver:e,file:t,endpointName:r,paginationPropertyComponents:a});default:Ko(a)}}function Hr_({errors:e,file:t}){return e==null?[]:Object.values(e).map(r=>{let i=typeof r=="string"?r:r.error,n=Hfi({errorName:i,file:t});return{docs:typeof r!="string"?r.docs:void 0,error:n}})}function yzo({source:e}){return{filepath:e.relativeFilePath,packageName:e.packageName,options:e.csharpNamespace!=null?{csharp:{namespace:e.csharpNamespace}}:void 0}}function $r_({source:e,serviceNameOverride:t}){let r=t??e.serviceName;if(r!=null)return{file:yzo({source:e}),name:$fi.generateName(r)}}function Gr_({file:e,serviceDeclaration:t,sourceResolver:r}){return UGt(t.source)?Jr_(e,t.source,r,t.transport?.grpc?.["service-name"]):mBe.http()}function Qr_({file:e,serviceTransport:t,endpointDeclaration:r,sourceResolver:i}){let n=t.type==="grpc",a=t.type==="http",u=UGt(r.source),l=!u;if(n){if(a&&u)throw new Error("Cannot have a grpc endpoint on an http service");if(n&&l)return mBe.http();if(n&&u){let d=r.source,s=r.transport?.grpc?.["service-name"];return s?Jr_(e,d,i,s):void 0}throw new Error(`Internal error; failed to determine endpoint transport for
|
|
1971
|
-
${JSON.stringify(r)}"`)}}function Jr_(e,t,r,i){let n=r.resolveSourceOrThrow({source:t,relativeFilepath:e.relativeFilepath});if(n==null||n.type!=="protobuf")throw new Error(`Expected a protobuf source for ${t.proto}.`);let a=$r_({source:n,serviceNameOverride:i});if(a==null)throw new Error(`Failed to resolve service name from ${n.relativeFilePath}.`);return mBe.grpc({service:a})}function Kr_({rootDefaultUrl:e,rootPathParameters:t,serviceDefinition:r,file:i,errorResolver:n,typeResolver:a,propertyResolver:u,exampleResolver:l,variableResolver:d,sourceResolver:s,globalErrors:o,workspace:c}){let b=v1n({pathParameters:r["path-parameters"],location:PBe.Service,file:i,variableResolver:d}),g=Gr_({file:i,serviceDeclaration:r,sourceResolver:s}),O={fernFilepath:i.fernFilepath};return{availability:hie(r.availability),name:O,displayName:r["display-name"]??void 0,basePath:iV(r["base-path"]),headers:r.headers!=null?Object.entries(r.headers).map(([w,E])=>rze({headerKey:w,header:E,file:i})):[],pathParameters:b,encoding:CGD(g,r),transport:g,endpoints:Object.entries(r.endpoints).map(([w,E])=>{let A=v1n({pathParameters:_5t(E),location:PBe.Endpoint,file:i,variableResolver:d}),q={...uG(E),id:"",name:i.casingsGenerator.generateName(w),displayName:E["display-name"],auth:E.auth??r.auth,idempotent:E.idempotent??r.idempotent??!1,baseUrl:E.url??r.url??e,method:E.method!=null?TGD(E.method):W3.Post,basePath:E["base-path"]!=null?iV(E["base-path"]):void 0,path:iV(E.path),fullPath:iV(E["base-path"]!=null?Cv(E["base-path"],E.path):i.rootApiFile["base-path"]!=null?Cv(i.rootApiFile["base-path"],r["base-path"],E.path):Cv(r["base-path"],E.path)),pathParameters:A,allPathParameters:E["base-path"]!=null?A:[...t,...b,...A],queryParameters:typeof E.request!="string"&&E.request?.["query-parameters"]!=null?Object.entries(E.request["query-parameters"]).map(([D,C])=>hzo({file:i,queryParameterKey:D,queryParameter:C})):[],headers:typeof E.request!="string"&&E.request?.headers!=null?Object.entries(E.request.headers).map(([D,C])=>rze({headerKey:D,header:C,file:i})):[],requestBody:ur_({request:E.request,file:i}),sdkRequest:dr_({service:r,request:E.request,endpoint:E,endpointKey:w,file:i,typeResolver:a,propertyResolver:u}),response:Nr_({endpoint:E,file:i,typeResolver:a}),errors:[...Hr_({errors:E.errors,file:i}),...o],userSpecifiedExamples:E.examples!=null?E.examples.map(D=>({example:Rr_({service:r,endpoint:E,example:D,typeResolver:a,errorResolver:n,exampleResolver:l,variableResolver:d,file:i,workspace:c}),codeSamples:D["code-samples"]?.map(C=>pr_({codeSample:C,file:i}))})):[],autogeneratedExamples:[],pagination:Wr_({propertyResolver:u,file:i,endpointName:w,endpointSchema:E}),transport:Qr_({file:i,serviceTransport:g,endpointDeclaration:E,sourceResolver:s})};return q.id=Ng.generateEndpointId(O,q),q})}}function v1n({pathParameters:e,location:t,file:r,variableResolver:i}){return e==null?[]:Object.entries(e).map(([n,a])=>AGD({parameterName:n,parameter:a,location:t,file:r,variableResolver:i}))}function AGD({parameterName:e,parameter:t,location:r,file:i,variableResolver:n}){return{...uG(t),name:i.casingsGenerator.generateName(e),valueType:qGD({parameter:t,variableResolver:n,file:i}),location:r,variable:Ehn(t)?n.getVariableIdOrThrow(typeof t=="string"?t:t.variable):void 0}}function qGD({parameter:e,variableResolver:t,file:r}){let i=F_a({parameter:e,variableResolver:t,file:r});return i.file.parseTypeReference(i.rawType)}function F_a({parameter:e,variableResolver:t,file:r}){let i=vzo({parameter:e,variableResolver:t,file:r});if(i==null)throw new Error("Cannot resolve path parameter");return i}function vzo({parameter:e,variableResolver:t,file:r}){if(Ehn(e)){let i=typeof e=="string"?e:e.variable,n=t.getDeclaration(i,r);return n==null?void 0:{rawType:typeof n.declaration=="string"?n.declaration:n.declaration.type,file:n.file}}else return{file:r,rawType:typeof e=="string"?e:e.type}}function TGD(e){switch(e){case"GET":return W3.Get;case"POST":return W3.Post;case"PUT":return W3.Put;case"PATCH":return W3.Patch;case"DELETE":return W3.Delete;default:Ko(e)}}function rze({headerKey:e,header:t,file:r}){let{name:i}=nXt({headerKey:e,header:t});return{...uG(t),name:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:i}),valueType:r.parseTypeReference(t),env:typeof t=="string"?void 0:t.env}}function nXt({headerKey:e,header:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function CGD(e,t){switch(e.type){case"http":return{json:{},proto:void 0};case"grpc":return{json:void 0,proto:{}};default:Ko(e)}}var Yr_="1.0.0";var bzo=class{ir;auth;authValues;constructor(t){this.ir=t,this.auth=this.convertAuth(t.auth),this.authValues=this.getAuthValues(t.auth)}convert({includeExamples:t}){return{version:Yr_,types:this.convertNamedTypes(),headers:this.convertHeaders(),endpoints:this.convertEndpoints({includeExamples:t}),environments:this.ir.environments}}convertNamedTypes(){return Object.fromEntries(Object.entries(this.ir.types).map(([t,r])=>[t,this.convertTypeDeclaration(r)]))}convertHeaders(){return this.convertWireValueParameters({wireValueParameters:this.ir.headers})}convertEndpoints({includeExamples:t}){let r=this.getAllHttpEndpoints();return Object.fromEntries(r.map(i=>[i.id,this.convertEndpoint({endpoint:i,includeExamples:t})]))}convertEndpoint({endpoint:t,includeExamples:r}){let i=this.convertEndpointLocation({endpoint:t});return{auth:this.auth,declaration:this.convertDeclaration({name:t.name,fernFilepath:t.fernFilepath}),location:i,request:this.convertRequest({endpoint:t}),response:Ic.Response.json(),examples:r?this.getEndpointSnippetRequests({endpoint:t,location:i}):void 0}}convertRequest({endpoint:t}){let r=this.convertPathParameters({pathParameters:t.allPathParameters});if(t.sdkRequest==null&&t.requestBody==null)return Ic.Request.body({pathParameters:r,body:void 0});if(t.sdkRequest==null)throw new Error(`Internal error; endpoint "${t.id}" has a request body but no SDK request`);switch(t.sdkRequest.shape.type){case"justRequestBody":return Ic.Request.body({pathParameters:r,body:this.convertReferencedRequestBodyType({body:t.sdkRequest.shape.value})});case"wrapper":return this.convertInlinedRequest({fernFilepath:t.fernFilepath,wrapper:t.sdkRequest.shape,pathParameters:r,queryParameters:this.convertQueryParameters({queryParameters:t.queryParameters}),headers:this.convertWireValueParameters({wireValueParameters:[...t.serviceHeaders,...t.headers]}),body:t.requestBody});default:Ko(t.sdkRequest.shape)}}convertReferencedRequestBodyType({body:t}){switch(t.type){case"bytes":return Ic.ReferencedRequestBodyType.bytes();case"typeReference":return Ic.ReferencedRequestBodyType.typeReference(this.convertTypeReference(t.requestBodyType));default:Ko(t)}}convertInlinedRequest({fernFilepath:t,wrapper:r,pathParameters:i,queryParameters:n,headers:a,body:u}){return Ic.Request.inlined({declaration:this.convertDeclaration({name:r.wrapperName,fernFilepath:t}),pathParameters:i,queryParameters:n,headers:a,body:u!=null?this.convertInlinedRequestBody({wrapper:r,body:u}):void 0,metadata:this.convertInlinedRequestMetadata({wrapper:r})})}convertInlinedRequestMetadata({wrapper:t}){return{includePathParameters:t.includePathParameters??!1,onlyPathParameters:t.onlyPathParameters??!1}}convertInlinedRequestBody({wrapper:t,body:r}){switch(r.type){case"inlinedRequestBody":{let i=[...r.extendedProperties??[],...r.properties];return Ic.InlinedRequestBody.properties(this.convertWireValueParameters({wireValueParameters:i}))}case"reference":return Ic.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:Ic.ReferencedRequestBodyType.typeReference(this.convertTypeReference(r.requestBodyType))});case"bytes":return Ic.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:Ic.ReferencedRequestBodyType.bytes()});case"fileUpload":return this.convertFileUploadRequestBody({properties:r.properties});default:Ko(r)}}convertFileUploadRequestBody({properties:t}){return Ic.InlinedRequestBody.fileUpload({properties:this.convertFileUploadRequestBodyProperties({properties:t})})}convertFileUploadRequestBodyProperties({properties:t}){return t.map(r=>{switch(r.type){case"file":return this.convertFileUploadRequestBodyFileProperty({fileProperty:r.value});case"bodyProperty":return Ic.FileUploadRequestBodyProperty.bodyProperty({name:r.name,typeReference:this.convertTypeReference(r.valueType)});default:Ko(r)}})}convertFileUploadRequestBodyFileProperty({fileProperty:t}){switch(t.type){case"file":return Ic.FileUploadRequestBodyProperty.file(t.key);case"fileArray":return Ic.FileUploadRequestBodyProperty.fileArray(t.key);default:Ko(t)}}convertPathParameters({pathParameters:t}){return t.map(r=>({name:{name:r.name,wireValue:r.name.originalName},typeReference:this.convertTypeReference(r.valueType)}))}convertWireValueParameters({wireValueParameters:t}){return t.map(r=>({name:{name:r.name.name,wireValue:r.name.wireValue},typeReference:this.convertTypeReference(r.valueType)}))}convertQueryParameters({queryParameters:t}){let r=[];for(let i of t){let n=this.convertTypeReference(i.valueType);i.allowMultiple&&(n=Ic.TypeReference.list(n)),r.push({name:{name:i.name.name,wireValue:i.name.wireValue},typeReference:n})}return r}convertTypeReference(t){switch(t.type){case"container":return this.convertContainerType(t.container);case"named":return this.convertNamedType(t);case"primitive":return this.convertPrimitiveType(t.primitive);case"unknown":return this.convertUnknownType();default:Ko(t)}}convertContainerType(t){switch(t.type){case"list":return Ic.TypeReference.list(this.convertTypeReference(t.list));case"map":return Ic.TypeReference.map({key:this.convertTypeReference(t.keyType),value:this.convertTypeReference(t.valueType)});case"optional":return Ic.TypeReference.optional(this.convertTypeReference(t.optional));case"nullable":return Ic.TypeReference.nullable(this.convertTypeReference(t.nullable));case"set":return Ic.TypeReference.set(this.convertTypeReference(t.set));case"literal":return Ic.TypeReference.literal(this.convertLiteral(t.literal));default:Ko(t)}}convertNamedType(t){return Ic.TypeReference.named(t.typeId)}convertTypeDeclaration(t){let r=this.convertDeclaration(t.name);switch(t.shape.type){case"alias":return this.convertAlias({declaration:r,alias:t.shape});case"enum":return this.convertEnum({declaration:r,enum_:t.shape});case"object":return this.convertObject({declaration:r,object:t.shape});case"union":return this.convertDiscriminatedUnion({declaration:r,union:t.shape});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({declaration:r,union:t.shape});default:Ko(t.shape)}}convertAlias({declaration:t,alias:r}){return Ic.NamedType.alias({declaration:t,typeReference:this.convertTypeReference(r.aliasOf)})}convertEnum({declaration:t,enum_:r}){return Ic.NamedType.enum({declaration:t,values:r.values.map(i=>i.name)})}convertObject({declaration:t,object:r}){let i=[...r.extendedProperties??[],...r.properties];return this.convertObjectProperties({declaration:t,properties:i})}convertObjectProperties({declaration:t,properties:r}){return Ic.NamedType.object({declaration:t,properties:this.convertWireValueParameters({wireValueParameters:r})})}convertDiscriminatedUnion({declaration:t,union:r}){let i=[...this.resolveProperties(r.extends),...r.baseProperties];return Ic.NamedType.discriminatedUnion({declaration:t,discriminant:r.discriminant,types:Object.fromEntries(r.types.map(n=>[n.discriminantValue.wireValue,this.convertDiscriminatedUnionType({inheritedProperties:i,discriminantValue:n.discriminantValue,singleUnionTypeProperties:n.shape})]))})}convertDiscriminatedUnionType({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperties:i}){switch(i.propertiesType){case"samePropertiesAsObject":return this.convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:i});case"singleProperty":return this.convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:i});case"noProperties":return this.convertDiscriminatedUnionTypeNoProperties({inheritedProperties:t,discriminantValue:r});default:Ko(i)}}convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:i}){return Ic.SingleDiscriminatedUnionType.samePropertiesAsObject({typeId:i.typeId,discriminantValue:r,properties:this.convertWireValueParameters({wireValueParameters:t})})}convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:i}){return Ic.SingleDiscriminatedUnionType.singleProperty({typeReference:this.convertTypeReference(i.type),discriminantValue:r,properties:t.length>0?this.convertWireValueParameters({wireValueParameters:t}):void 0})}convertDiscriminatedUnionTypeNoProperties({inheritedProperties:t,discriminantValue:r}){return Ic.SingleDiscriminatedUnionType.noProperties({discriminantValue:r,properties:t.length>0?this.convertWireValueParameters({wireValueParameters:t}):void 0})}convertUndiscriminatedUnion({declaration:t,union:r}){return Ic.NamedType.undiscriminatedUnion({declaration:t,types:r.members.map(i=>this.convertTypeReference(i.type))})}convertLiteral(t){switch(t.type){case"boolean":return Ic.LiteralType.boolean(t.boolean);case"string":return Ic.LiteralType.string(t.string);default:Ko(t)}}convertPrimitiveType(t){return Ic.TypeReference.primitive(t.v1)}convertUnknownType(){return Ic.TypeReference.unknown()}convertAuth(t){if(t.schemes[0]==null)return;let r=t.schemes[0];switch(r.type){case"basic":return Ic.Auth.basic(r);case"bearer":return Ic.Auth.bearer(r);case"header":return Ic.Auth.header({header:{name:r.name,typeReference:this.convertTypeReference(r.valueType)}});case"oauth":return;default:Ko(r)}}getAuthValues(t){let r=t.schemes[0];if(r!=null)switch(r.type){case"bearer":return Ic.AuthValues.bearer({token:"<token>"});case"basic":return Ic.AuthValues.basic({username:"<username>",password:"<password>"});case"header":return Ic.AuthValues.header({value:"<value>"});case"oauth":return;default:Ko(r)}}convertDeclaration({name:t,fernFilepath:r}){return{name:t,fernFilepath:r}}convertEndpointLocation({endpoint:t}){return{method:t.method,path:this.getFullPathForEndpoint(t)}}getAllHttpEndpoints(){return Object.values(this.ir.services).flatMap(t=>t.endpoints.map(r=>({...r,serviceHeaders:t.headers,fernFilepath:t.name.fernFilepath})))}resolveProperties(t){let r=[];for(let i of t){let n=this.resolveObjectTypeOrThrow(i.typeId);r.push(...this.resolveProperties(n.extends)),r.push(...n.properties)}return Object.values(r)}resolveObjectTypeOrThrow(t){let r=this.ir.types[t];if(r==null)throw new Error(`Internal error; type "${t}" not found`);if(r.shape.type!=="object")throw new Error(`Internal error; type "${t}" is not an object`);return r.shape}getFullPathForEndpoint(t){let r="";t.fullPath.head.length>0&&(r=Cv(r,t.fullPath.head));for(let i of t.fullPath.parts)r=Cv(r,"{"+i.pathParameter+"}"),i.tail.length>0&&(r=Cv(r,i.tail));return r.startsWith("/")?r:`/${r}`}getEndpointSnippetRequests({endpoint:t,location:r}){let i=[];for(let n of[...t.userSpecifiedExamples,...t.autogeneratedExamples])i.push({id:n?.example?.id??zre(),name:n?.example?.name?.originalName,endpoint:r,baseUrl:void 0,environment:void 0,auth:this.authValues,headers:Object.fromEntries([...n.example?.serviceHeaders??[],...n.example?.endpointHeaders??[]].map(a=>[a.name.wireValue,a.value.jsonExample])),pathParameters:Object.fromEntries([...n.example?.rootPathParameters??[],...n.example?.servicePathParameters??[],...n.example?.endpointPathParameters??[]].map(a=>[a.name.originalName,a.value.jsonExample])),queryParameters:Object.fromEntries([...n.example?.queryParameters??[]].map(a=>[a.name.wireValue,a.value.jsonExample])),requestBody:n.example?.request?.jsonExample});return i}};function Xr_({ir:e,includeExamples:t}){return new bzo(e).convert({includeExamples:t})}var sG={};Io(sG,{validateObjectExample:()=>Gzi,validateTypeExample:()=>pzo,validateTypeReferenceExample:()=>h5});var gzo=class{subpackages={};rootPackage={docs:void 0,fernFilepath:{allParts:[],packagePath:[],file:void 0},websocket:void 0,service:void 0,types:[],errors:[],subpackages:[],webhooks:void 0,navigationConfig:void 0};addPackageRedirection({from:t,to:r}){let i=this.getPackageForFernFilepath(t);if(i.navigationConfig!=null)throw new Error("Found duplicate navigationConfig for package");i.navigationConfig={pointsTo:Ng.generateSubpackageId(r)}}addDocs(t,r){let i=this.getPackageForFernFilepath(t);if(i.docs!=null)throw new Error("Found duplicate docs for package");i.docs=r}addSubpackage(t){this.getPackageForFernFilepath(t)}addType(t,r){this.getPackageForFernFilepath(r.name.fernFilepath).types.push(t)}addError(t,r){this.getPackageForFernFilepath(r.name.fernFilepath).errors.push(t)}addService(t,r){let i=this.getPackageForFernFilepath(r.name.fernFilepath);if(i.service!=null)throw new Error("Found duplicate service for "+t);i.service=t}addWebhookGroup(t,r){let i=this.getPackageForFernFilepath(r);if(i.webhooks!=null)throw new Error("Found duplicate webhook group for "+t);i.webhooks=t}addWebSocketChannel(t,r){let i=this.getPackageForFernFilepath(r);if(i.webhooks!=null)throw new Error("Found duplicate webhook group for "+t);i.websocket=t}build(t){t!=null&&(Object.entries(this.subpackages).forEach(([i,n])=>{t.hasSubpackageId(i)?this.subpackages[i]={...n,types:n.types.filter(a=>t.hasTypeId(a)),errors:n.errors.filter(a=>t.hasErrorId(a)),service:n.service!=null&&t.hasServiceId(n.service)?n.service:void 0,subpackages:n.subpackages.filter(a=>t.hasSubpackageId(a))}:delete this.subpackages[i]}),this.rootPackage={...this.rootPackage,types:this.rootPackage.types.filter(i=>t.hasTypeId(i)),errors:this.rootPackage.errors.filter(i=>t.hasErrorId(i)),service:this.rootPackage.service!=null&&t.hasServiceId(this.rootPackage.service)?this.rootPackage.service:void 0,subpackages:this.rootPackage.subpackages.filter(i=>t.hasSubpackageId(i)),webhooks:this.rootPackage.webhooks!=null?this.rootPackage.webhooks:void 0});let r=new Set(this.getAllChildrenWithEndpoints(this.rootPackage));return{subpackages:od(this.subpackages,(i,n)=>({...i,hasEndpointsInTree:r.has(n)})),rootPackage:{...this.rootPackage,hasEndpointsInTree:r.size>0||this.rootPackage.service!=null}}}sortRootPackage(t){if(!Zr_(this.rootPackage.subpackages,t))throw new Error("Sorted subpackages differ from unsorted packages in root");this.rootPackage.subpackages=t}sortSubpackage(t,r){let i=this.subpackages[t];if(i==null)throw new Error("Subpackage does not exist: "+t);if(!Zr_(i.subpackages,r))throw new Error("Sorted subpackages differ from unsorted packages");i.subpackages=r}getAllSubpackagesWithEndpoints(t){let r=this.subpackages[t];if(r==null)throw new Error("Subpackage does not exist: "+t);let i=this.getAllChildrenWithEndpoints(r);return(i.length>0||r.service!=null)&&i.push(t),i}getAllChildrenWithEndpoints(t){return t.subpackages.flatMap(r=>[...this.getAllSubpackagesWithEndpoints(r)])}getPackageForFernFilepath(t,r=0,i=this.rootPackage){let n=t.allParts[r];if(n==null)return i;let a=i.subpackages.map(s=>{let o=this.subpackages[s];if(o==null)throw new Error("Subpackage ID is invalid: "+s);return o}),u=r+1,l={allParts:t.allParts.slice(0,u),packagePath:t.packagePath.slice(0,u),file:u===t.allParts.length?t.file:void 0},d=a.find(s=>s.name.originalName===n.originalName);if(d==null){let s=Ng.generateSubpackageId(l),o={docs:void 0,fernFilepath:l,name:n,service:void 0,types:[],errors:[],subpackages:[],navigationConfig:void 0,webhooks:void 0,websocket:void 0};this.subpackages[s]=o,i.subpackages.push(s),d=o}return this.getPackageForFernFilepath(t,u,d)}};function Zr_(e,t){if(e.length!==t.length)return!1;let r=new Set(e);for(let i of t)if(!r.has(i))return!1;return!0}function kr_(e){return{errorInstanceIdKey:e.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}}function Ozo({fernFilePath:e}){return e.packagePath.length===0&&e.file==null}function ei_({endpointResolver:e,propertyResolver:t,file:r,refreshTokenEndpoint:i}){let n=e.resolveEndpointOrThrow({endpoint:i.endpoint,file:r});return{endpointReference:{endpointId:Ng.generateEndpointIdFromResolvedEndpoint(n),serviceId:Ng.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:Ozo({fernFilePath:n.file.fernFilepath})?void 0:Ng.generateSubpackageId(n.file.fernFilepath)},requestProperties:{refreshToken:t.resolveRequestPropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.requestProperties.refresh_token})},responseProperties:{accessToken:t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.access_token}),expiresIn:i.responseProperties.expires_in!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.expires_in}):void 0,refreshToken:i.responseProperties.refresh_token!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.refresh_token}):void 0}}}function ti_({endpointResolver:e,propertyResolver:t,file:r,tokenEndpoint:i}){let n=e.resolveEndpointOrThrow({endpoint:i.endpoint,file:r}),a=typeof n.endpoint.request=="object"&&n.endpoint.request.body!=null&&typeof n.endpoint.request.body=="object"&&"properties"in n.endpoint.request.body?n.endpoint.request.body.properties??{}:{};return{endpointReference:{endpointId:Ng.generateEndpointIdFromResolvedEndpoint(n),serviceId:Ng.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:Ozo({fernFilePath:n.file.fernFilepath})?void 0:Ng.generateSubpackageId(n.file.fernFilepath)},requestProperties:{clientId:t.resolveRequestPropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.requestProperties.client_id}),clientSecret:t.resolveRequestPropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.requestProperties.client_secret}),scopes:i.requestProperties.scopes!=null?t.resolveRequestPropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.requestProperties.scopes}):void 0,customProperties:BGD({requestBodyProperties:a,tokenEndpoint:i,file:r,propertyResolver:t})},responseProperties:{accessToken:t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.access_token}),expiresIn:i.responseProperties.expires_in!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.expires_in}):void 0,refreshToken:i.responseProperties.refresh_token!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.refresh_token}):void 0}}}var BGD=({requestBodyProperties:e,tokenEndpoint:t,file:r,propertyResolver:i})=>{let n=Object.keys(e).filter(a=>!t.requestProperties.client_id.includes(a)&&!t.requestProperties.client_secret.includes(a)&&(t.requestProperties.scopes==null||!t.requestProperties.scopes.includes(a)));return n.length>0?n.map(a=>i.resolveRequestPropertyOrThrow({file:r,endpoint:t.endpoint,propertyComponents:[a]})):void 0};function ri_({propertyResolver:e,endpointResolver:t,file:r,oauthScheme:i,tokenEndpoint:n,refreshTokenEndpoint:a}){let u=ti_({propertyResolver:e,endpointResolver:t,file:r,tokenEndpoint:n});if(u==null)throw new Error("Failed to convert OAuth token endpoint.");let l=a!=null?ei_({propertyResolver:e,endpointResolver:t,file:r,refreshTokenEndpoint:a}):void 0;return{clientIdEnvVar:i["client-id-env"],clientSecretEnvVar:i["client-secret-env"],tokenPrefix:i["token-prefix"],tokenHeader:i["token-header"],scopes:i.scopes,tokenEndpoint:u,refreshEndpoint:l}}var L_a={requestProperties:{type:"access_token",client_id:["client_id"],client_secret:["client_secret"],scopes:void 0},responseProperties:{type:"access_token",access_token:["access_token"],expires_in:void 0,refresh_token:void 0}},nKs={requestProperties:{type:"refresh_token",refresh_token:["refresh_token"]},responseProperties:{type:"access_token",access_token:["access_token"],refresh_token:void 0,expires_in:void 0}};function ii_(e){return{endpoint:e["get-token"].endpoint,requestProperties:xGD({requestProperties:e["get-token"]?.["request-properties"]}),responseProperties:IGD({responseProperties:e["get-token"]?.["response-properties"]})}}function ni_(e){if(e["refresh-token"]!=null)return{endpoint:e["refresh-token"].endpoint,requestProperties:zGD({requestProperties:e["refresh-token"]?.["request-properties"]}),responseProperties:RGD({responseProperties:e["refresh-token"]?.["response-properties"]})}}function xGD({requestProperties:e}){if(e==null)return L_a.requestProperties;let t=e["client-id"],r=e["client-secret"],i=e.scopes;return{type:"access_token",client_id:t!=null?p5t(t):L_a.requestProperties.client_id,client_secret:r!=null?p5t(r):L_a.requestProperties.client_secret,scopes:i!=null?p5t(i):L_a.requestProperties.scopes}}function IGD({responseProperties:e}){return ai_({responseProperties:e,defaultValue:L_a.responseProperties})}function zGD({requestProperties:e}){if(e==null)return nKs.requestProperties;let t=e["refresh-token"];return{type:"refresh_token",refresh_token:t!=null?p5t(t):nKs.requestProperties.refresh_token}}function RGD({responseProperties:e}){return ai_({responseProperties:e,defaultValue:nKs.responseProperties})}function ai_({responseProperties:e,defaultValue:t}){if(e==null)return t;let r=e["access-token"],i=e["expires-in"],n=e["refresh-token"];return{type:"access_token",access_token:r!=null?iXt(r):t.access_token,expires_in:i!=null?iXt(i):t.expires_in,refresh_token:n!=null?iXt(n):t.refresh_token}}function li_({rawApiFileSchema:e,file:t,propertyResolver:r,endpointResolver:i}){if(e.auth==null)return{docs:void 0,requirement:Doi.All,schemes:[]};let n=typeof e.auth!="string"?e.auth.docs:void 0;return pra(e.auth,{single:a=>{let u=oi_({reference:a,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i});return{docs:n,requirement:Doi.All,schemes:[u]}},any:({any:a})=>({docs:n,requirement:Doi.Any,schemes:a.map(u=>oi_({reference:u,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i}))})})}function oi_({reference:e,authSchemeDeclarations:t,file:r,propertyResolver:i,endpointResolver:n}){let a=(l,d)=>{let s=t?.[l];if(s==null)throw new Error("Unknown auth scheme: "+l);return Hvs(s,{header:o=>dR.header({docs:d,name:r.casingsGenerator.generateNameAndWireValue({name:o.name??l,wireValue:o.header}),valueType:r.parseTypeReference(o.type??"string"),prefix:o.prefix,headerEnvVar:o.env}),basic:o=>si_({file:r,docs:d,rawScheme:o}),bearer:o=>ui_({file:r,docs:d,rawScheme:o}),oauth:o=>ci_({file:r,docs:d,rawScheme:o,propertyResolver:i,endpointResolver:n})})},u=typeof e=="string"?e:e.scheme;switch(u){case"bearer":return ui_({file:r,docs:void 0,rawScheme:void 0});case"basic":return si_({file:r,docs:void 0,rawScheme:void 0});case"oauth":return ci_({file:r,docs:void 0,rawScheme:void 0,propertyResolver:i,endpointResolver:n});default:return a(u,typeof e!="string"?e.docs:void 0)}}function ui_({file:e,docs:t,rawScheme:r}){return dR.bearer({docs:t,token:e.casingsGenerator.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function si_({file:e,docs:t,rawScheme:r}){return dR.basic({docs:t,username:e.casingsGenerator.generateName(r?.username?.name??"username"),usernameEnvVar:r?.username?.env,password:e.casingsGenerator.generateName(r?.password?.name??"password"),passwordEnvVar:r?.password?.env})}function ci_({file:e,docs:t,rawScheme:r,propertyResolver:i,endpointResolver:n}){switch(r?.type){case"client-credentials":return dR.oauth({docs:t,configuration:Eoi.clientCredentials(ri_({propertyResolver:i,endpointResolver:n,file:e,oauthScheme:r,tokenEndpoint:ii_(r),refreshTokenEndpoint:ni_(r)}))});default:throw new Error(`Unknown OAuth type: '${r?.type}'`)}}function fi_({file:e,rawApiFileSchema:t}){if(t.version!=null)return Aoi.header({header:NGD({file:e,header:t.version.header}),value:FGD({file:e,versionDeclaration:t.version})})}function NGD({file:e,header:t}){return typeof t=="string"?rze({file:e,headerKey:t,header:{type:"string"}}):rze({file:e,headerKey:t.value,header:{type:"string",name:t.name,env:t.env}})}function FGD({file:e,versionDeclaration:t}){return _zo({_enum:{default:t.default,enum:t.values},file:e})}function di_({channel:e,typeResolver:t,exampleResolver:r,variableResolver:i,file:n,workspace:a}){let u=[];for(let[l,d]of Object.entries(e.messages??{}))u.push({type:l,availability:hie(d.availability),docs:d.docs,origin:d.origin,body:VGD({body:d.body,file:n}),displayName:d["display-name"]});return{availability:hie(e.availability),path:iV(e.path),baseUrl:e.url,auth:e.auth,name:n.fernFilepath.file??n.casingsGenerator.generateName(e["display-name"]??e.path),displayName:e["display-name"],headers:e.headers!=null?Object.entries(e.headers).map(([l,d])=>rze({headerKey:l,header:d,file:n})):[],docs:e.docs,pathParameters:e["path-parameters"]!=null?v1n({pathParameters:e["path-parameters"],location:PBe.Endpoint,file:n,variableResolver:i}):[],queryParameters:e["query-parameters"]!=null?Object.entries(e["query-parameters"]).map(([l,d])=>{let{name:s}=FQr({queryParameterKey:l,queryParameter:d}),o=n.parseTypeReference(d);return{...uG(d),name:n.casingsGenerator.generateNameAndWireValue({wireValue:l,name:s}),valueType:o,allowMultiple:typeof d!="string"&&d["allow-multiple"]!=null?d["allow-multiple"]:!1}}):[],messages:Object.values(u),examples:(e.examples??[]).map(l=>{let d=HGD({channel:e,example:l,typeResolver:t,exampleResolver:r,variableResolver:i,file:n,workspace:a});return{name:l.name!=null?n.casingsGenerator.generateName(l.name):void 0,docs:l.docs,url:GGD({channel:e,example:l,pathParams:d}),...d,...$GD({channel:e,example:l,typeResolver:t,exampleResolver:r,file:n,workspace:a}),queryParameters:l["query-parameters"]!=null?Object.entries(l["query-parameters"]).map(([s,o])=>{let c=e["query-parameters"]?.[s];if(c==null)throw new Error(`Query parameter ${s} does not exist`);return{name:n.casingsGenerator.generateNameAndWireValue({name:FQr({queryParameterKey:s,queryParameter:c}).name,wireValue:s}),value:rE({example:o,rawTypeBeingExemplified:typeof c=="string"?c:c.type,typeResolver:t,exampleResolver:r,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),shape:LGD({queryParameter:c})}}):[],messages:l.messages.map(s=>{let o=e.messages?.[s.type];if(o==null)throw new Error(`Message ${s.type} does not exist`);return{type:s.type,body:UGD({message:o,example:s.body,typeResolver:t,exampleResolver:r,file:n,workspace:a})}})}})}}function LGD({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?Q6.exploded():Q6.single()}function UGD({message:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){if(!QGD(e.body))return w4t.reference(rE({example:t,rawTypeBeingExemplified:typeof e.body!="string"?e.body.type:e.body,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}));if(!Hj(t))throw new Error("Example must be an object");let u=[];for(let[l,d]of Object.entries(t)){let s=e.body.properties?.[l];if(s!=null)u.push({name:n.casingsGenerator.generateNameAndWireValue({name:uV({propertyKey:l,property:s}).name,wireValue:l}),value:rE({example:d,rawTypeBeingExemplified:typeof s!="string"?s.type:s,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),originalTypeDeclaration:void 0});else{let o=N_a({extends_:e.body.extends,wirePropertyKey:l,typeResolver:r,file:n});if(o==null)throw new Error("Could not find original type declaration for property: "+l);u.push({name:n.casingsGenerator.generateNameAndWireValue({name:uV({propertyKey:l,property:o.rawPropertyType}).name,wireValue:l}),value:rE({example:d,rawTypeBeingExemplified:typeof o.rawPropertyType=="string"?o.rawPropertyType:o.rawPropertyType.type,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:o.file,fileContainingExample:n,workspace:a}),originalTypeDeclaration:o.typeName})}}return w4t.inlinedBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t,file:n}).resolvedExample,properties:u})}function VGD({body:e,file:t}){return typeof e=="string"?Xte.reference({docs:void 0,bodyType:t.parseTypeReference(e)}):WGD(e)?Xte.reference({docs:void 0,bodyType:t.parseTypeReference(e.type)}):Xte.inlinedBody({name:t.casingsGenerator.generateName(e.name),extends:d5t(e.extends??[]).map(r=>_5({typeName:r,file:t})),properties:[]})}function WGD(e){return e.type!=null}function HGD({channel:e,example:t,typeResolver:r,exampleResolver:i,variableResolver:n,file:a,workspace:u}){let l=[],d=({name:s,pathParameterDeclaration:o,examplePathParameter:c})=>{let b=F_a({parameter:o,variableResolver:n,file:a});return{name:s,value:rE({example:c,rawTypeBeingExemplified:b.rawType,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:b.file,fileContainingExample:a,workspace:u})}};if(t["path-parameters"]!=null){let s=_5t(e);for(let[o,c]of Object.entries(t["path-parameters"])){let b=s[o];if(b!=null)l.push(d({name:a.casingsGenerator.generateName(o),pathParameterDeclaration:b,examplePathParameter:c}));else throw new Error(`Path parameter ${o} does not exist`)}}return{pathParameters:l}}function $GD({channel:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){let u=[];if(t.headers!=null)for(let[l,d]of Object.entries(t.headers)){let s=e.headers?.[l];if(s!=null)u.push({name:n.casingsGenerator.generateNameAndWireValue({name:nXt({headerKey:l,header:s}).name,wireValue:l}),value:rE({example:d,rawTypeBeingExemplified:typeof s=="string"?s:s.type,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a})});else throw new Error(`Heder ${l} does not exist`)}return{headers:u}}function GGD({channel:e,example:t,pathParams:r}){let i=e.path;if(t["path-parameters"]!=null)for(let n of[...r.pathParameters])i=i.replaceAll(`{${n.name.originalName}}`,`${n.value.jsonExample}`);return i}function QGD(e){return typeof e=="string"?!1:e.extends!=null||e.properties!=null}function aKs({rawApiFileSchema:{"default-environment":e,environments:t},casingsGenerator:r}){if(t==null)return;let i=Object.values(t)[0];if(i!=null)return{defaultEnvironment:e??void 0,environments:o$r(i,{singleBaseUrl:()=>q1e.singleBaseUrl(JGD({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>q1e.multipleBaseUrls(KGD({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})}}function JGD({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>o$r(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:pi_(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function KGD({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>o$r(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:od(a.urls,u=>pi_(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function pi_(e){return e.endsWith("/")?e.slice(0,-1):e}function _i_({errorName:e,errorDeclaration:t,file:r,typeResolver:i,exampleResolver:n,workspace:a}){let u=[];if(t.type!=null&&t.examples!=null)for(let l of t.examples)u.push({name:l.name!=null?r.casingsGenerator.generateName(l.name):void 0,docs:l.docs,jsonExample:n.resolveAllReferencesInExampleOrThrow({example:l.value,file:r}).resolvedExample,shape:rE({example:l.value,rawTypeBeingExemplified:t.type,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})});return{name:Hfi({errorName:e,file:r}),discriminantValue:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:e}),docs:typeof t!="string"?t.docs:void 0,statusCode:t["status-code"],type:t.type!=null?r.parseTypeReference(t.type):void 0,examples:u}}var hi_="content";function yi_(e,t){if(e==null||e.strategy==="status-code")return P4t.statusCode();switch(e.strategy){case"property":return P4t.property({discriminant:t.casingsGenerator.generateNameAndWireValue({name:e["property-name"],wireValue:e["property-name"]}),contentProperty:t.casingsGenerator.generateNameAndWireValue({name:hi_,wireValue:hi_})});default:Ko(e)}}function vi_({readme:e,services:t}){let r=new oKs(t);return{apiReferenceLink:e.apiReferenceLink,bannerLink:e.bannerLink,introduction:e.introduction,defaultEndpoint:e.defaultEndpoint!=null?r.getEndpointForReadmeOrThrow(e.defaultEndpoint).id:void 0,features:e.features!=null?Object.fromEntries(Object.entries(e.features).map(([i,n])=>[i,n.map(a=>r.getEndpointForReadmeOrThrow(a).id)])):void 0}}var oKs=class{endpoints={};constructor(t){this.endpoints=this.buildEndpoints(t)}getEndpointForReadme(t){let r=XGD({endpoint:t}),i=this.getEndpointKeyForReadmeEndpoint(r);return this.endpoints[i]}getEndpointForReadmeOrThrow(t){let r=this.getEndpointForReadme(t);if(r==null)throw new Error(`Endpoint not found for ${JSON.stringify(t)}`);return r}buildEndpoints(t){let r={};for(let i of Object.values(t))for(let n of i.endpoints)r[this.getEndpointKeyForHttpEndpoint(n)]=n;return r}getEndpointKeyForReadmeEndpoint(t){return this.getEndpointKey({method:t.method,path:t.path,stream:t.stream??!1})}getEndpointKeyForHttpEndpoint(t){return this.getEndpointKey({method:t.method,path:YGD(t),stream:t.response?.body?.type==="streaming"})}getEndpointKey({method:t,path:r,stream:i}){return`${t}|${r}|${i}`}};function YGD(e){let t="";e.fullPath.head.length>0&&(t=Cv(t,e.fullPath.head));for(let r of e.fullPath.parts)t=Cv(t,"{"+r.pathParameter+"}"),r.tail.length>0&&(t=Cv(t,r.tail));return t.startsWith("/")?t:`/${t}`}function XGD({endpoint:e}){if(typeof e=="string"){let t=e.split(" ");if(t.length!==2||t[0]==null||t[1]==null)throw new Error(`invalid endpoint string: ${e}`);return{method:t[0],path:t[1]}}return e}function bi_({webhooks:e,file:t,typeResolver:r,exampleResolver:i,workspace:n}){let a=[];for(let[u,l]of Object.entries(e))a.push({id:Ng.generateWebhookId(t.fernFilepath,u),availability:hie(l.availability),displayName:l["display-name"],docs:l.docs,method:l.method,name:t.casingsGenerator.generateName(u),headers:l.headers!=null?Object.entries(l.headers).map(([d,s])=>rze({headerKey:d,header:s,file:t})):[],payload:ZGD({payload:l.payload,file:t}),examples:l.examples!=null?eQD({webhook:l,examples:l.examples,file:t,typeResolver:r,exampleResolver:i,workspace:n}):void 0});return a}function ZGD({payload:e,file:t}){return typeof e=="string"?hU.reference({docs:void 0,payloadType:t.parseTypeReference(e)}):mzo(e)?hU.reference({docs:void 0,payloadType:t.parseTypeReference(e.type)}):hU.inlinedPayload({name:t.casingsGenerator.generateName(e.name),extends:d5t(e.extends).map(r=>_5({typeName:r,file:t})),properties:e.properties!=null?Object.entries(e.properties).map(([r,i])=>kGD({propertyKey:r,propertyDefinition:i,docs:typeof i!="string"?i.docs:void 0,availability:typeof i!="string"?hie(i.availability):void 0,file:t})):[]})}function kGD({propertyKey:e,propertyDefinition:t,docs:r,availability:i,file:n}){return{docs:r,availability:i,name:n.casingsGenerator.generateNameAndWireValue({wireValue:e,name:uV({propertyKey:e,property:t}).name}),valueType:n.parseTypeReference(t)}}function eQD({webhook:e,examples:t,file:r,typeResolver:i,exampleResolver:n,workspace:a}){let u=typeof e.payload=="string"?e.payload:mzo(e.payload)?e.payload.type:void 0;if(u!=null)return t.map(l=>({docs:e.docs,name:l.name!=null?r.casingsGenerator.generateName(l.name):void 0,payload:rE({example:l.payload,rawTypeBeingExemplified:u,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}));if(!Hj(e.payload))throw new Error(`Example webhook payload is not an object. Got: ${JSON.stringify(e.payload)}`);return t.map(l=>({docs:e.docs,name:l.name!=null?r.casingsGenerator.generateName(l.name):void 0,payload:rE({example:l.payload,rawTypeBeingExemplified:"map<string, unknown>",fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}))}function mzo(e){return e.type!=null}function b1n(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}function gi_({name:e,source:t}){return oj.userDefined({file:yzo({source:t}),name:$fi.generateName(e)})}function Oi_({encoding:e}){if(e.proto!=null&&e.proto.type!=null){let t=tQD({type:e.proto.type});if(t!=null)return t}}function tQD({type:e}){switch(e){case"google.protobuf.Any":return oj.wellKnown(Xf.any());case"google.protobuf.Api":return oj.wellKnown(Xf.api());case"google.protobuf.BoolValue":return oj.wellKnown(Xf.boolValue());case"google.protobuf.BytesValue":return oj.wellKnown(Xf.bytesValue());case"google.protobuf.DoubleValue":return oj.wellKnown(Xf.doubleValue());case"google.protobuf.Duration":return oj.wellKnown(Xf.duration());case"google.protobuf.Empty":return oj.wellKnown(Xf.empty());case"google.protobuf.Enum":return oj.wellKnown(Xf.enum());case"google.protobuf.EnumValue":return oj.wellKnown(Xf.enumValue());case"google.protobuf.Field":return oj.wellKnown(Xf.field());case"google.protobuf.FieldCardinality":return oj.wellKnown(Xf.fieldCardinality());case"google.protobuf.FieldKind":return oj.wellKnown(Xf.fieldKind());case"google.protobuf.FieldMask":return oj.wellKnown(Xf.fieldMask());case"google.protobuf.FloatVlaue":return oj.wellKnown(Xf.floatValue());case"google.protobuf.Int32Value":return oj.wellKnown(Xf.int32Value());case"google.protobuf.Int64Value":return oj.wellKnown(Xf.int64Value());case"google.protobuf.ListValue":return oj.wellKnown(Xf.listValue());case"google.protobuf.Method":return oj.wellKnown(Xf.method());case"google.protobuf.Mixin":return oj.wellKnown(Xf.mixin());case"google.protobuf.NullValue":return oj.wellKnown(Xf.nullValue());case"google.protobuf.Option":return oj.wellKnown(Xf.option());case"google.protobuf.SourceContext":return oj.wellKnown(Xf.sourceContext());case"google.protobuf.StringValue":return oj.wellKnown(Xf.stringValue());case"google.protobuf.Struct":return oj.wellKnown(Xf.struct());case"google.protobuf.Syntax":return oj.wellKnown(Xf.syntax());case"google.protobuf.Timestamp":return oj.wellKnown(Xf.timestamp());case"google.protobuf.Type":return oj.wellKnown(Xf.type());case"google.protobuf.Uint32Value":return oj.wellKnown(Xf.uint32Value());case"google.protobuf.Uint64Value":return oj.wellKnown(Xf.uint64Value());case"google.protobuf.Value":return oj.wellKnown(Xf.value())}}function mi_({generic:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type,n=RI(i);if(n==null)throw new Error(`Invalid generic type definition: ${i}`);let a=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:i,file:t});if(n.arguments&&G1(a.declaration)){let u=RI(a.typeName)?.arguments??[],l=Object.entries(a.declaration.properties??{}).map(([d,s])=>{let o=s;return typeof s=="string"&&u?.includes(s)&&(o=n.arguments?.[u.indexOf(s)]??s),[d,o]});return Gj.object({extends:d5t(a.declaration.extends).map(d=>_5({typeName:d,file:t})),properties:B_a({properties:Object.fromEntries(l)},t),extraProperties:a.declaration["extra-properties"]??!1,extendedProperties:void 0})}throw new Error(`Generic type definition not supported: ${i}`)}function Pi_({alias:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type;return OBe(i)?mi_({generic:i,file:t,typeResolver:r}):Gj.alias({aliasOf:t.parseTypeReference(e),resolvedType:rQD({aliasOf:i,file:t,typeResolver:r})})}function rQD({aliasOf:e,file:t,typeResolver:r}){let i=r.resolveTypeOrThrow({type:e,file:t});switch(i._type){case"primitive":return _U.primitive(i.originalTypeReference.primitive);case"container":return _U.container(i.originalTypeReference.container);case"unknown":return _U.unknown();case"named":{let n=G1(i.declaration)?j4t.Object:Loi(i.declaration)?j4t.Union:M4t(i.declaration)?j4t.Enum:Mhn(i.declaration)?j4t.UndiscriminatedUnion:Ko(i.declaration);return _U.named({name:i.name,shape:n})}}}function ji_({union:e,file:t}){let r=e.union.filter((i,n)=>{let a=typeof i=="string"?i:i.type;return e.union.findIndex(u=>(typeof u=="string"?u:u.type)===a)===n});return Gj.undiscriminatedUnion({members:r.map(i=>typeof i=="string"?{docs:void 0,type:t.parseTypeReference(i)}:{type:t.parseTypeReference(i.type),docs:i.docs})})}function wi_(e){let t=[];if(e.extends!=null){let r=typeof e.extends=="string"?[e.extends]:e.extends;t.push(...r)}return e.properties!=null&&t.push(...Object.values(e.properties).map(r=>typeof r=="string"?r:r.type)),t}function sKs({typeDeclaration:e,file:t,typeResolver:r,seenTypeNames:i=new uKs}){let n=xN(e,{alias:u=>{let l=typeof u=="string"?u:u.type,d=RI(l);if(d!=null){let s=new Set(d.arguments??[]),o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:l,file:t}),c=RI(o.typeName)?.arguments;if(G1(o.declaration)){let b=wi_(o.declaration);c&&b.filter(g=>!c.includes(g)).forEach(g=>s.add(g))}return Array.from(s)}return[l]},object:u=>wi_(u),discriminatedUnion:u=>{let l=[];return u["base-properties"]!=null&&l.push(...Object.values(u["base-properties"]).map(d=>typeof d=="string"?d:d.type)),l.push(...Object.values(u.union).reduce((d,s)=>{let o=typeof s=="string"?s:s.type;return typeof o=="string"&&d.push(o),d},[])),l},undiscriminatedUnion:u=>Object.values(u.union).reduce((l,d)=>{let s=typeof d=="string"?d:d.type;return typeof s=="string"&&l.push(s),l},[]),enum:()=>[]}),a=[];for(let u of n){let l=yU({type:u,_default:void 0,validation:void 0,visitor:{primitive:()=>[],map:({keyType:d,valueType:s})=>[...d,...s],list:d=>d,optional:d=>d,nullable:d=>d,set:d=>d,named:d=>[d],literal:()=>[],unknown:()=>[]}});for(let d of l){let s=_5({typeName:d,file:t});if(!i.hasTypeNameBeenSeen(s)){i.addTypeName(s),a.push(s);let o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:d,file:t});if(OBe(o.typeName))continue;a.push(...sKs({typeDeclaration:o.declaration,file:o.file,typeResolver:r,seenTypeNames:i}))}}}return a}var uKs=class{cache=new Set;addTypeName(t){this.cache.add(this.computeCacheKey(t))}hasTypeNameBeenSeen(t){return this.cache.has(this.computeCacheKey(t))}computeCacheKey(t){return t.fernFilepath.allParts.map(r=>r.originalName).join("/")+":"+t.name.originalName}};function Si_({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,sourceResolver:a,workspace:u}){let l=uG(t),d=_5({typeName:e,file:r}),s=sKs({typeDeclaration:t,file:r,typeResolver:i}),o={};G1(t)&&(o=b1n(t.properties??{}));let c=nQD({file:r,typeDeclaration:t,typeName:e,sourceResolver:a});return{propertiesByAudience:o,typeDeclaration:{...l,inline:sQD(t),name:d,shape:iQD({typeDeclaration:t,file:r,typeResolver:i}),referencedTypes:new Set(s.map(b=>b.typeId)),encoding:aQD({typeDeclaration:t,source:c}),source:c,userProvidedExamples:typeof t!="string"&&t.examples!=null?t.examples.map(b=>({name:b.name!=null?r.casingsGenerator.generateName(b.name):void 0,docs:b.docs,jsonExample:n.resolveAllReferencesInExampleOrThrow({example:b.value,file:r}).resolvedExample,shape:iKs({typeName:d,example:b.value,typeResolver:i,exampleResolver:n,typeDeclaration:t,fileContainingType:r,fileContainingExample:r,workspace:u})})):[],autogeneratedExamples:[]},descendantFilepaths:new Set(s.map(b=>b.fernFilepath))}}function iQD({typeDeclaration:e,file:t,typeResolver:r}){return xN(e,{alias:i=>Pi_({alias:i,file:t,typeResolver:r}),object:i=>ar_({object:i,file:t}),discriminatedUnion:i=>Or_({union:i,file:t,typeResolver:r}),undiscriminatedUnion:i=>ji_({union:i,file:t}),enum:i=>Gj.enum(_zo({_enum:i,file:t}))})}function nQD({file:e,typeDeclaration:t,typeName:r,sourceResolver:i}){if(typeof t=="string"||t.source==null&&t.encoding==null)return;if(t.encoding!=null){let a=Oi_({encoding:t.encoding});if(a!=null)return n$r.proto(a)}if(t.source==null)return;let n=i.resolveSourceOrThrow({source:t.source,relativeFilepath:e.relativeFilepath});if(!(n==null||n.type!=="protobuf"))return n$r.proto(gi_({source:n,name:r}))}function aQD({typeDeclaration:e,source:t}){return typeof e!="string"&&e.encoding!=null?oQD(e.encoding):uQD(t)}function oQD(e){return e.proto!=null?{json:void 0,proto:{}}:{json:{},proto:void 0}}function uQD(e){return e!=null&&e.type==="proto"?{json:void 0,proto:{}}:{json:{},proto:void 0}}function sQD(e){if(typeof e!="string"&&"inline"in e)return e.inline}function Di_(e,t){let r=t[e];if(r==null)throw new THr(`Illegal Error: Failed to load type declaration for type ${e}`);return r}function Ei_(e){return{types:Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,lQD({typeDeclaration:r,ir:e})])),services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(i=>cQD({endpoint:i,ir:e}))}]))}}function cQD({endpoint:e,ir:t}){return e.requestBody?.type!=="inlinedRequestBody"?e:{...e,requestBody:{...e.requestBody,extendedProperties:e.requestBody.extends.flatMap(r=>Mi_(r,t))}}}function lQD({typeDeclaration:e,ir:t}){switch(e.shape.type){case"object":return{...e,shape:{...e.shape,extendedProperties:e.shape.extends.flatMap(r=>Mi_(r,t))}}}return e}function Mi_(e,t){let r=cKs(e.typeId,t);return Ai_({objectTypeDeclaration:r,ir:t})}function cKs(e,t){let r=Di_(e,t.types);switch(r.shape.type){case"object":return r.shape;case"alias":if(r.shape.resolvedType.type==="named")return cKs(r.shape.resolvedType.name.typeId,t)}throw new THr(`Unexpected error: ${e} is extended but has shape ${r.shape.type}`)}function Ai_({objectTypeDeclaration:e,ir:t}){let r=e.extends.flatMap(i=>{let n=cKs(i.typeId,t);return Ai_({objectTypeDeclaration:n,ir:t})});return[...e.properties,...r]}function Ti_({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:kI({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)}}:void 0;return i!==void 0?CN.samePropertiesAsObject(i):void 0},singleProperty:r=>{let i=kI({filteredIr:e,exampleTypeReference:r});return i!==void 0?CN.singleProperty(i):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function kI({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:i=>({...t,shape:mb.container(NO.list({...i,list:i.list.map(n=>kI({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:mb.container(NO.set({...i,set:i.set.map(n=>kI({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?kI({filteredIr:e,exampleTypeReference:i.optional}):void 0;return n!=null?{...t,shape:mb.container(NO.optional({optional:n,valueType:i.valueType}))}:void 0},nullable:i=>{let n=i.nullable!=null?kI({filteredIr:e,exampleTypeReference:i.nullable}):void 0;return n!=null?{...t,shape:mb.container(NO.nullable({nullable:n,valueType:i.valueType}))}:void 0},map:i=>({...t,shape:mb.container(NO.map({...i,map:i.map.map(n=>{let a=kI({filteredIr:e,exampleTypeReference:n.key}),u=kI({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=kI({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:mb.named({...r,shape:Qj.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:mb.named({...r,shape:Qj.enum(i)})}),object:i=>({...t,shape:mb.named({...r,shape:Qj.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:kI({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=Ti_({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:mb.named({...r,shape:Qj.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=kI({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:mb.named({...r,shape:Qj.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function lKs({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=kI({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function fQD({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=kI({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function qi_({filteredIr:e,headers:t}){return t.map(r=>{let i=kI({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function dQD({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=kI({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=kI({filteredIr:e,exampleTypeReference:r});return i!==void 0?y$.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function pQD({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>mq.ok(RT.body(i!=null?kI({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>mq.ok(RT.stream(i.map(n=>kI({filteredIr:e,exampleTypeReference:n})).filter(u0))),sse:i=>mq.ok(RT.sse(i.map(({event:n,data:a})=>{let u=kI({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:n,data:u}:void 0}).filter(u0))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>mq.error({error:r,body:i!=null?kI({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function fKs({filteredIr:e,example:t}){return{...t,rootPathParameters:lKs({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:lKs({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:lKs({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:qi_({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:qi_({filteredIr:e,headers:t.endpointHeaders}),queryParameters:fQD({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?dQD({filteredIr:e,requestBody:t.request}):void 0,response:pQD({filteredIr:e,response:t.response})}}function Ci_({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=kI({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:Qj.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:Qj.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:kI({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=Ti_({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:Qj.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=kI({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:Qj.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}var Pzo=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=Ng.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=Ng.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=Ng.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.name.originalName?this.channels.has(t.name.originalName):!0}hasWebhookPayloadProperty(t,r){let i=this.webhookPayloadProperties[t];return i==null?!0:i.has(r)}};var wzo=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=_QD(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let u=Ng.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=Ng.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=Ng.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&ez(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=Ng.generateServiceId(t.name),a=r.id,u=new Set,l=new Set,d=new Set;for(let s of[...t.headers,...r.headers])ez(s.valueType,u,d);for(let s of[...t.pathParameters,...r.pathParameters])ez(s.valueType,u,d);for(let s of r.queryParameters)ez(s.valueType,u,d);if(i!=null&&i.request!=null&&typeof i.request!="string"){let s=b1n(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:s}}r.requestBody!=null&&Ux._visit(r.requestBody,{inlinedRequestBody:s=>{for(let o of s.extends)jzo(o,u,d);for(let o of s.properties)ez(o.valueType,u,d);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&zT(i.request.body)){let o=b1n(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:s})=>{ez(s,u,d)},fileUpload:({properties:s})=>{for(let o of s)TN._visit(o,{file:Qo,bodyProperty:({valueType:c})=>{ez(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&&Xq._visit(r.response.body,{fileDownload:Qo,json:s=>{ez(s.responseBodyType,u,d)},streaming:s=>{s._visit({sse:o=>ez(o.payload,u,d),json:o=>ez(o.payload,u,d),text:Qo,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.type)}})},streamParameter:s=>{s.streamResponse._visit({sse:o=>ez(o.payload,u,d),json:o=>ez(o.payload,u,d),text:Qo,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.streamResponse.type)}}),s.nonStreamResponse.type==="json"&&ez(s.nonStreamResponse.value.responseBodyType,u,d)},text:Qo,bytes:Qo,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(s=>{l.add(Ng.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=Ng.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)}}addWebhook(t,r,i){let n=r.id;if(n==null)return;let a=new Set,u=new Set;r.payload!=null&&hU._visit(r.payload,{inlinedPayload:l=>{for(let d of l.extends)jzo(d,a,u);for(let d of l.properties)ez(d.valueType,a,u);if(i?.payload!=null&&typeof i.payload=="object"&&!mzo(i.payload)){let d=b1n(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:d}}},reference:({payloadType:l})=>{ez(l,a,u)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),u.add(t.fernFilepath),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.fernFilepath))}addChannel(t,r,i,n){if(r==null)return;let a=new Set,u=new Set;for(let l of i.messages)Xte._visit(l.body,{reference:({bodyType:d})=>{ez(d,a,u)},inlinedBody:d=>{for(let s of d.extends)jzo(s,a,u);for(let s of d.properties)ez(s.valueType,a,u)},_other:()=>{}});u.add(t.fernFilepath),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.fernFilepath))}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 Pzo({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:Ko(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(Ng.generateSubpackageId(i))}}};function _QD(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:Ko(e)}}function ez(e,t,r){nh._visit(e,{container:i=>{hQD(i,t,r)},named:i=>{jzo(i,t,r)},primitive:Qo,unknown:Qo,_other:Qo})}function jzo(e,t,r){t.add(Ng.generateTypeId(e)),r.add(e.fernFilepath)}function hQD(e,t,r){Tg._visit(e,{list:i=>{ez(i,t,r)},map:i=>{ez(i.keyType,t,r),ez(i.valueType,t,r)},optional:i=>{ez(i,t,r)},nullable:i=>{ez(i,t,r)},set:i=>{ez(i,t,r)},literal:Qo,_other:Qo})}function Bi_({reference:e,referencedIn:t,imports:r}){let[i,n,...a]=e.split(".");if(i==null||a.length>0)return;if(n==null)return{endpointName:i,relativeFilepath:t};let l=r[i];if(l!=null)return{endpointName:n,relativeFilepath:Wfi({referencedIn:t,importPath:l})}}var Jzi=class{workspace;constructor(t){this.workspace=t}resolveEndpointOrThrow({endpoint:t,file:r}){let i=this.resolveEndpoint({endpoint:t,file:r});if(i==null)throw new Error("Cannot resolve endpoint: "+t+" in file "+r.relativeFilepath);return i}resolveEndpointByMethodAndPath({method:t,path:r}){let i;return XN(this.workspace,(n,a,u)=>{let l=Hb({relativeFilepath:n,definitionFile:a,casingsGenerator:$fi,rootApiFile:this.workspace.definition.rootApiFile.contents,defaultUrl:u.defaultUrl});for(let[d,s]of Object.entries(a.service?.endpoints??{}))s.method===t&&s.path===r&&(i={endpointId:d,endpoint:s,file:l})}),CIi(this.workspace,(n,a)=>{let u=Hb({relativeFilepath:n,definitionFile:a,casingsGenerator:$fi,rootApiFile:this.workspace.definition.rootApiFile.contents});for(let[l,d]of Object.entries(a.service?.endpoints??{}))d.method===t&&d.path===r&&(i={endpointId:l,endpoint:d,file:u})}),i}resolveEndpoint({endpoint:t,file:r}){let n=new fTi().tryParse(t);if(n!=null)return this.resolveEndpointByMethodAndPath(n);let a=this.getDeclarationOfEndpoint({referenceToEndpoint:t,file:r});if(a==null)return;let u=a.file.definitionFile.service?.endpoints?.[a.endpointName];if(u!=null)return{endpointId:a.endpointName,endpoint:u,file:a.file}}getDeclarationOfEndpoint({referenceToEndpoint:t,file:r}){let i=Bi_({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=aie(this.workspace,i.relativeFilepath);if(!(n==null||n.service?.endpoints?.[i.endpointName]==null))return{endpointName:i.endpointName,file:Hb({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var Kzi=class{workspace;constructor(t){this.workspace=t}getDeclarationOrThrow(t,r){let i=this.getDeclaration(t,r);if(i==null)throw new Error("Error does not exist: "+t);return i}getDeclaration(t,r){let i=PSe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=aie(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.errors?.[i.typeName];if(a!=null)return{declaration:a,file:Hb({definitionFile:n,relativeFilepath:i.relativeFilepath,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var wSe=class{typeResolver;constructor(t){this.typeResolver=t}resolveAllReferencesInExample({example:t,file:r}){if(typeof t=="string"){let i=this.resolveExample({example:t,file:r});return i==null||typeof i.resolvedExample=="string"?i:this.resolveAllReferencesInExample({example:i.resolvedExample,file:i.file})}else if(Hj(t)){let i={};for(let[n,a]of Object.entries(t)){let u=this.resolveAllReferencesInExample({example:a,file:r});if(u==null)return;i[n]=u.resolvedExample}return{resolvedExample:i}}else if(Array.isArray(t)){let i=[];for(let n of t){let a=this.resolveAllReferencesInExample({example:n,file:r});if(a==null)return;i.push(a.resolvedExample)}return{resolvedExample:i}}return{resolvedExample:t}}resolveAllReferencesInExampleOrThrow({example:t,file:r}){let i=this.resolveAllReferencesInExample({example:t,file:r});if(i==null)throw new Error("Failed to resolve examples");return i}resolveExample({example:t,file:r}){if(typeof t!="string")return{resolvedExample:t,file:r};if(t.startsWith(`\\${NGt}`))return{resolvedExample:t.slice(1),file:r};if(!t.startsWith(NGt))return{resolvedExample:t,file:r};let i=this.parseExampleReference(t);if(i==null)return;let n=this.typeResolver.getDeclarationOfNamedType({referenceToNamedType:i.rawTypeReference,file:r});if(n==null||typeof n.declaration=="string"||n.declaration.examples==null)return;let a=n.declaration.examples.find(u=>u.name===i.exampleName);if(a!=null)return this.resolveExample({example:a.value,file:n.file})}resolveExampleOrThrow({example:t,file:r}){let i=this.resolveExample({example:t,file:r});if(i==null)throw new Error("Cannot resolve example: "+t);return i}parseExampleReference(t){let[r,i,n,...a]=t.split(".");if(!(r==null||i==null||a.length>0))return n==null?{rawTypeReference:r.slice(NGt.length),exampleName:i}:{rawTypeReference:`${r}.${i}`.slice(NGt.length),exampleName:n}}};var Szo=class{typeResolver;endpointResolver;constructor(t,r){this.typeResolver=t,this.endpointResolver=r,this.typeResolver=t,this.endpointResolver=r}resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:i}){let n=this.resolveRequestProperty({file:t,endpoint:r,propertyComponents:i});if(n==null)throw new Error("Cannot resolve request property from endpoint: "+r+" in file "+t.relativeFilepath);return n}resolveRequestProperty({file:t,endpoint:r,propertyComponents:i}){let n=this.endpointResolver.resolveEndpointOrThrow({endpoint:r,file:t});if(n.endpoint.request==null)return;if(typeof n.endpoint.request!="string")return this.resolveRequestPropertyFromInlinedRequest({typeResolver:this.typeResolver,file:n.file,requestType:n.endpoint.request,propertyComponents:i});let a=this.resolveObjectProperty({file:n.file,typeName:n.endpoint.request,propertyComponents:i});if(a!=null)return{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:i,file:t}),property:Kte.body(a)}}resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i}){let n=this.resolveResponseProperty({file:t,endpoint:r,propertyComponents:i});if(n==null)throw new Error("Cannot resolve response property from endpoint: "+r+" in file "+t.relativeFilepath);return n}resolveResponseProperty({file:t,endpoint:r,propertyComponents:i}){let n=this.endpointResolver.resolveEndpointOrThrow({endpoint:r,file:t}),a=this.resolveObjectProperty({file:n.file,typeName:(typeof n.endpoint.response!="string"?n.endpoint.response?.type:n.endpoint.response)??"",propertyComponents:i});if(a!=null)return{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:i,file:t}),property:a}}resolveRequestPropertyFromInlinedRequest({typeResolver:t,file:r,requestType:i,propertyComponents:n}){if(n.length===1){let a=n[0]??"",u=i["query-parameters"]?.[a]??void 0;if(u!=null)return{property:Kte.query(hzo({file:r,queryParameterKey:a,queryParameter:u})),propertyPath:void 0}}return this.resolveRequestPropertyFromInlinedRequestBody({typeResolver:t,file:r,requestType:i,propertyComponents:n})}resolveRequestPropertyFromInlinedRequestBody({typeResolver:t,file:r,requestType:i,propertyComponents:n}){if(i.body==null)return;if(typeof i.body=="string"){let u=this.resolveObjectProperty({file:r,typeName:i.body,propertyComponents:n});return u==null?void 0:{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:Kte.body(u)}}if(zT(i.body)){let u=kJs({typeResolver:t,file:r,objectSchema:i.body,propertyComponents:n});return u==null?void 0:{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:Kte.body(u)}}let a=this.resolveObjectProperty({file:r,typeName:i.body.type,propertyComponents:n});if(a!=null)return{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:Kte.body(a)}}resolveObjectProperty({file:t,typeName:r,propertyComponents:i}){let n=this.typeResolver.resolveTypeOrThrow({type:r,file:t});return ZJs({typeResolver:this.typeResolver,file:I_a(n)??t,resolvedType:n,propertyComponents:i})}propertyPathFromPropertyComponents({propertyComponents:t,file:r}){return t.length<=1?[]:t.slice(0,-1).map(i=>r.casingsGenerator.generateName(i))}};var t1=class{workspace;constructor(t){this.workspace=t}resolveTypeOrThrow({type:t,file:r}){let i=this.resolveType({type:t,file:r});if(i==null)throw new Error("Cannot resolve type: "+t+" in file "+r.relativeFilepath);return i}getDeclarationOfNamedTypeOrThrow({referenceToNamedType:t,file:r}){let i=this.getDeclarationOfNamedType({referenceToNamedType:t,file:r});if(i==null)throw new Error("Cannot find declaration of type: "+t+" in file "+r.relativeFilepath);return i}getDeclarationOfNamedType({referenceToNamedType:t,file:r}){let i=PSe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=aie(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.types?.[i.typeName];if(a==null){let u=RI(i.typeName);if(u!=null){for(let l of Object.keys(n.types??{})??[])if(u.name&&l.startsWith(u.name)&&l.endsWith(">")){let d=n.types?.[l];return d!=null?{typeName:l,declaration:d,file:Hb({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}:void 0}}return}return{typeName:i.typeName,declaration:a,file:Hb({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}resolveType({type:t,file:r,objectPath:i=[]}){return yU({type:t,_default:void 0,validation:void 0,visitor:{primitive:n=>({_type:"primitive",primitive:n,originalTypeReference:nh.primitive(n)}),unknown:()=>({_type:"unknown",originalTypeReference:nh.unknown()}),map:({keyType:n,valueType:a})=>n!=null&&a!=null?{_type:"container",container:{_type:"map",keyType:n,valueType:a},originalTypeReference:nh.container(Tg.map({keyType:n.originalTypeReference,valueType:a.originalTypeReference}))}:void 0,list:n=>n!=null?{_type:"container",container:{_type:"list",itemType:n},originalTypeReference:nh.container(Tg.list(n.originalTypeReference))}:void 0,optional:n=>n!=null?{_type:"container",container:{_type:"optional",itemType:n},originalTypeReference:nh.container(Tg.optional(n.originalTypeReference))}:void 0,nullable:n=>n!=null?{_type:"container",container:{_type:"nullable",itemType:n},originalTypeReference:nh.container(Tg.nullable(n.originalTypeReference))}:void 0,set:n=>n!=null?{_type:"container",container:{_type:"set",itemType:n},originalTypeReference:nh.container(Tg.set(n.originalTypeReference))}:void 0,literal:n=>({_type:"container",container:{_type:"literal",literal:n},originalTypeReference:nh.container(Tg.literal(n))}),named:n=>{let a=this.getDeclarationOfNamedType({referenceToNamedType:n,file:r});if(a==null)return;let u={typeName:a.typeName,file:a.file.relativeFilepath,reference:n};if(!i.some(l=>l.file===u.file&&l.typeName===u.typeName))return this.resolveNamedTypeFromDeclaration({referenceToNamedType:n,referencedIn:r,rawDeclaration:a,objectPath:[...i,u]})}}})}resolveNamedTypeOrThrow({referenceToNamedType:t,file:r}){let i=this.resolveNamedType({referenceToNamedType:t,file:r});if(i==null)throw new Error("Cannot resolve type: "+t);return i}resolveNamedType({referenceToNamedType:t,file:r}){let i=this.getDeclarationOfNamedType({referenceToNamedType:t,file:r});if(i!=null)return this.resolveNamedTypeFromDeclaration({referenceToNamedType:t,referencedIn:r,rawDeclaration:i})}resolveNamedTypeFromDeclaration({referenceToNamedType:t,referencedIn:r,rawDeclaration:i,objectPath:n=[]}){let{declaration:a,file:u}=i;if(Foi(a))return this.resolveType({type:typeof a=="string"?a:a.type,file:u,objectPath:n});let l=R_a({type:t,_default:void 0,validation:void 0,file:r});if(!(l.type!=="named"||aie(this.workspace,u.relativeFilepath)==null))return{_type:"named",rawName:i.typeName,name:l,declaration:a,filepath:u.relativeFilepath,objectPath:n,originalTypeReference:l,file:u}}};var y5t=class e{static VARIABLE_PREFIX="$";getDeclarationOrThrow(t,r){let i=this.getDeclaration(t,r);if(i==null)throw new Error("Variable does not exist: "+t);return i}getDeclaration(t,r){if(!t.startsWith(e.VARIABLE_PREFIX))return;let i=r.rootApiFile.variables?.[t.substring(1)];if(i!=null)return{declaration:i,file:NQr({casingsGenerator:r.casingsGenerator,rootApiFile:r.rootApiFile})}}getVariableIdOrThrow(t){let r=this.getVariableId(t);if(r==null)throw new Error("Variable reference does not start with "+e.VARIABLE_PREFIX);return r}getVariableId(t){if(t.startsWith(e.VARIABLE_PREFIX))return t.substring(e.VARIABLE_PREFIX.length)}};function Dzo(e,t){if(t){for(let[r,i]of Object.entries(t))if(typeof i!="string"&&r===e)return i.audiences}}function _2({workspace:e,generationLanguage:t,keywords:r,smartCasing:i,exampleGeneration:n,audiences:a,readme:u,packageName:l,version:d,context:s,fdrApiDefinitionId:o,sourceResolver:c,includeDynamicExamples:b}){let g=i5t({generationLanguage:t,keywords:r,smartCasing:i}),O=new wzo(a),m=NQr({casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents}),w=(e.definition.rootApiFile.contents.errors??[]).map(st=>({error:Hfi({errorName:st,file:m}),docs:void 0})),E=new t1(e),A=new Jzi(e),q=new Szo(E,A),D=new Kzi(e),C=new wSe(E),R=new y5t,$={fdrApiDefinitionId:o,apiVersion:fi_({file:m,rawApiFileSchema:e.definition.rootApiFile.contents}),apiName:g.generateName(e.definition.rootApiFile.contents.name),apiDisplayName:e.definition.rootApiFile.contents["display-name"],apiDocs:C_a(e.definition.rootApiFile.contents.docs),auth:li_({rawApiFileSchema:e.definition.rootApiFile.contents,file:m,propertyResolver:q,endpointResolver:A}),headers:e.definition.rootApiFile.contents.headers!=null?Object.entries(e.definition.rootApiFile.contents.headers).map(([st,ye])=>rze({headerKey:st,header:ye,file:m})):[],idempotencyHeaders:e.definition.rootApiFile.contents["idempotency-headers"]!=null?Object.entries(e.definition.rootApiFile.contents["idempotency-headers"]).map(([st,ye])=>rze({headerKey:st,header:ye,file:m})):[],types:{},errors:{},services:{},constants:kr_(g),environments:aKs({casingsGenerator:g,rawApiFileSchema:e.definition.rootApiFile.contents}),errorDiscriminationStrategy:yi_(e.definition.rootApiFile.contents["error-discrimination"],m),basePath:e.definition.rootApiFile.contents["base-path"]!=null?iV(e.definition.rootApiFile.contents["base-path"]):void 0,pathParameters:v1n({pathParameters:e.definition.rootApiFile.contents["path-parameters"],file:m,location:PBe.Root,variableResolver:R}),variables:e.definition.rootApiFile.contents.variables!=null?Object.entries(e.definition.rootApiFile.contents.variables).map(([st,ye])=>({docs:typeof ye!="string"?ye.docs:void 0,id:st,name:m.casingsGenerator.generateName(st),type:m.parseTypeReference(ye)})):[],serviceTypeReferenceInfo:{typesReferencedOnlyByService:{},sharedTypes:[]},webhookGroups:{},websocketChannels:{},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0},I=new gzo,U=st=>{I.addSubpackage(st.fernFilepath),Wj(st.definitionFile,{imports:Qo,docs:ye=>{ye!=null&&I.addDocs(st.fernFilepath,ye)},types:ye=>{if(ye!=null)for(let[Pe,Ot]of Object.entries(ye)){if(OBe(Pe))continue;let wt=Si_({typeName:Pe,typeDeclaration:Ot,file:st,typeResolver:E,exampleResolver:C,sourceResolver:c,workspace:e}),sr=wt.typeDeclaration;n.disabled&&(sr.userProvidedExamples=[],sr.autogeneratedExamples=[]);let ur=wt.descendantFilepaths,ni=Ng.generateTypeId(sr.name);$.types[ni]=sr,I.addType(ni,sr),O.addType({declaredTypeName:sr.name,descendantTypeIds:sr.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:wt.propertiesByAudience,descendantFilepaths:ur}),O.markTypeForAudiences(sr.name,nr_(Ot))}},errors:ye=>{if(ye==null)return;if(e.definition.rootApiFile.contents["error-discrimination"]==null)throw new Error("error-discrimination is missing in api.yml but there are declared errors.");for(let[Ot,wt]of Object.entries(ye)){let sr=_i_({errorName:Ot,errorDeclaration:wt,file:st,typeResolver:E,exampleResolver:C,workspace:e}),ur=Ng.generateErrorId(sr.name);$.errors[ur]=sr,I.addError(ur,sr),O.addError(sr)}},service:ye=>{if(ye==null)return;let Pe=Kr_({rootDefaultUrl:st.defaultUrl??e.definition.rootApiFile.contents["default-url"],rootPathParameters:$.pathParameters,serviceDefinition:ye,file:st,errorResolver:D,typeResolver:E,propertyResolver:q,exampleResolver:C,sourceResolver:c,globalErrors:w,variableResolver:R,workspace:e}),Ot=Ng.generateServiceId(Pe.name);$.services[Ot]=Pe,I.addService(Ot,Pe);let wt={};Pe.endpoints.forEach(sr=>{n.disabled&&(sr.autogeneratedExamples=[],sr.userSpecifiedExamples=[]);let ur=ye.endpoints[sr.name.originalName];O.addEndpoint(Pe,sr,ur),wt[sr.name.originalName]=sr}),ye.audiences!=null&&O.markEndpointForAudience(Pe.name,Pe.endpoints,ye.audiences),Object.entries(ye.endpoints).map(([sr,ur])=>{let ni=wt[sr];ni!=null&&ur.audiences!=null&&O.markEndpointForAudience(Pe.name,[ni],ur.audiences)})},webhooks:ye=>{if(ye==null)return;let Pe=Ng.generateWebhookGroupId(st.fernFilepath),Ot=bi_({webhooks:ye,file:st,typeResolver:E,exampleResolver:C,workspace:e}),wt={};for(let sr of Ot)wt[sr.name.originalName]=sr;Object.entries(ye).forEach(([sr,ur])=>{let ni=wt[sr];ni!=null&&(O.addWebhook(st,ni,ur),ur.audiences!=null&&O.markWebhookForAudiences(st,ni,ur.audiences))}),$.webhookGroups[Pe]=Ot,I.addWebhookGroup(Pe,st.fernFilepath)},channel:ye=>{if(ye==null)return;let Pe=Ng.generateWebSocketChannelId(st.fernFilepath),Ot=di_({channel:ye,file:st,variableResolver:R,typeResolver:E,exampleResolver:C,workspace:e});O.addChannel(st,Pe,Ot,ye),ye.audiences!=null&&O.markChannelForAudiences(st,Pe,ye.audiences),$.websocketChannels!=null&&($.websocketChannels[Pe]=Ot,I.addWebSocketChannel(Pe,st.fernFilepath))}})};XN(e,(st,ye,Pe)=>{U(Hb({relativeFilepath:st,definitionFile:ye,casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents,defaultUrl:Pe.defaultUrl}))}),CIi(e,(st,ye)=>{if(ye.navigation!=null)if(typeof ye.navigation=="string")I.addPackageRedirection({from:_ie({relativeFilepath:st,casingsGenerator:g}),to:_ie({relativeFilepath:sR(UCe(st),ry.of(ye.navigation)),casingsGenerator:g})});else{let Pe=ye.navigation.map(Ot=>Ng.generateSubpackageId(_ie({relativeFilepath:sR(UCe(st),ry.of(Ot)),casingsGenerator:g})));st===W1?I.sortRootPackage(Pe):I.sortSubpackage(Ng.generateSubpackageId(_ie({relativeFilepath:st,casingsGenerator:g})),Pe)}}),$.serviceTypeReferenceInfo=vQD(O);let H=n.disabled?$:fpa({ir:$,exampleGeneration:n}),k=e.definition.rootApiFile.contents,K=aKs({casingsGenerator:g,rawApiFileSchema:k}),te=K?.environments._visit({singleBaseUrl:st=>st.environments.filter(ye=>Dzo(ye.id,k.environments)!=null).length===0,multipleBaseUrls:st=>st.environments.filter(ye=>Dzo(ye.id,k.environments)!=null).length===0,_other:()=>!1});K?.environments.environments.forEach(st=>{O.markEnvironmentForAudiences(st,Dzo(st.id,k.environments)??[],te)});let fe=O.hasNoAudiences()?void 0:O.build(),me=bQD(H,fe),be=e.definition.rootApiFile.contents.auth!=null&&Object.values(me.services).every(st=>st.endpoints.every(ye=>ye.auth)),we=Object.values(me.services).some(st=>st.endpoints.some(ye=>ye.response?.body?.type==="streaming")),Ze=Object.values(me.services).some(st=>st.endpoints.some(ye=>ye.pagination!=null)),Mt=Object.values(me.services).some(st=>st.endpoints.some(ye=>ye.response?.body?.type==="fileDownload")),De={isAuthMandatory:be,hasStreamingEndpoints:we,hasPaginatedEndpoints:Ze,hasFileDownloadEndpoints:Mt,platformHeaders:{language:"X-Fern-Language",sdkName:"X-Fern-SDK-Name",sdkVersion:"X-Fern-SDK-Version",userAgent:d!=null&&l!=null?{header:"User-Agent",value:`${l}/${d}`}:void 0}},Te=u!=null?vi_({readme:u,services:$.services}):void 0,{types:xt,services:Ee}=Ei_(me),It=yQD({...me,...I.build(fe),types:xt,services:Ee,sdkConfig:De,readmeConfig:Te});return{...It,dynamic:Xr_({ir:It,includeExamples:b})}}function yQD(e){let t=r=>{if(!r||typeof r!="object")return r;if(Array.isArray(r))return r.map(t);for(let i in r){let n=r[i];i==="docs"&&typeof n=="string"?r[i]=C_a(n):n&&typeof n=="object"&&t(n)}return r};return t(e)}function vQD(e){let t={},r=[],i=e.getTypesReferencedByService();for(let[n,a]of Object.entries(i)){if(a.size===1){let u=a.values().next().value;if(u==null)break;t[u]===void 0&&(t[u]=[]),t[u]?.push(n);continue}r.push(n)}return{typesReferencedOnlyByService:t,sharedTypes:r}}function bQD(e,t){if(t==null)return e;let r=gAi(e.types,u=>t.hasType(u)),i=Object.fromEntries(Object.entries(r).map(([u,l])=>{let d=[];if(l.userProvidedExamples=l.userProvidedExamples.map(s=>Ci_({filteredIr:t,exampleType:s})).filter(s=>s!==void 0),l.shape.type==="object"){for(let s of l.shape.properties)t.hasProperty(u,s.name.wireValue)&&d.push(s);return[u,{...l,shape:Gj.object({...l.shape,properties:d})}]}return[u,l]})),n=Object.fromEntries(Object.entries(e.webhookGroups).map(([u,l])=>{let d=l.filter(s=>t.hasWebhook(s)).map(s=>{let o=s.id;return s.payload.type==="inlinedPayload"&&o!=null&&(s.payload={...s.payload,properties:s.payload.properties.filter(c=>t.hasWebhookPayloadProperty(o,c.name.wireValue))}),s});return[u,d]})),a=e.environments;if(a){switch(a.environments.type){case"singleBaseUrl":{a.environments.environments=a.environments.environments.filter(u=>t.hasEnvironmentId(u.id));break}case"multipleBaseUrls":{a.environments.environments=a.environments.environments.filter(u=>t.hasEnvironmentId(u.id));break}}a.defaultEnvironment&&(t.hasEnvironmentId(a.defaultEnvironment)||(a.defaultEnvironment=void 0))}return{...e,environments:a,types:i,errors:gAi(e.errors,u=>t.hasError(u)),services:od(gAi(e.services,u=>t.hasService(u)),u=>({...u,endpoints:u.endpoints.filter(l=>t.hasEndpoint(l)).map(l=>(l.autogeneratedExamples=l.autogeneratedExamples.map(d=>({...d,example:fKs({filteredIr:t,example:d.example})})),l.userSpecifiedExamples=l.userSpecifiedExamples.map(d=>({...d,example:d.example!=null?fKs({filteredIr:t,example:d.example}):void 0})),l.queryParameters.length>0&&(l.queryParameters=l.queryParameters.filter(d=>t.hasQueryParameter(l.id,d.name.wireValue))),l.requestBody?.type==="inlinedRequestBody"?{...l,requestBody:{...l.requestBody,properties:l.requestBody.properties.filter(d=>t.hasRequestProperty(l.id,d.name.wireValue))}}:l))})),webhookGroups:n,serviceTypeReferenceInfo:gQD(e.serviceTypeReferenceInfo,t)}}function gQD(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}}function xi_(e){throw new Error("Unexpected value: "+JSON.stringify(e))}var zi_=vi(wkn(),1);var Ii_=["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 v5t(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,zi_.default)(e,{special:Ii_}).replace(/V\s(\d)/g,"V$1")}function U_a(e,t="type"){return{_visit:r=>{let i=r[e[t]];return i!=null?i(e):(r._other==null&&xi_(e),r._other(e))}}}function aXt(e){return typeof e.subpackageId=="string"}function TC(e){return e.map(t=>t.type==="literal"?t.value:`{${t.value}}`).join("")}function ize(e){return e.map(t=>t.type==="literal"?t.value:`:${t.value}`).join("")}var dKs="__package__",Qfi=class e{api;context;static create(t,r){return new e(t,r)}#e=new Map;#t=new Map;#r=new Map;#n=new Map;#i=new Map;#a=new Map;#o=new Map;#c=new Map;#l=new Map;#u=new Map;#s=new Map;static getSubpackageId(t){return aXt(t)?t.subpackageId:dKs}getSubpackageByIdOrLocator(t){if(t==null)return;let r=p2.SubpackageId(t);return r===dKs?this.api.rootPackage:this.api.subpackages[r]??this.#s.get(r)}resolveSubpackage(t){if(t!=null){for(;t?.pointsTo!=null;)t=this.api.subpackages[t.pointsTo];return t}}constructor(t,r){this.api=t,this.context=r,[t.rootPackage,...Object.values(t.subpackages)].forEach(i=>{let n=p2.SubpackageId(e.getSubpackageId(i)),a={endpoints:new Map,webSockets:new Map,webhooks:new Map};this.#o.set(n,a),i.endpoints.forEach(u=>{a.endpoints.set(u.id,u);let l=e.createEndpointId(u,n);this.#e.set(l,u);let d=[],s=[u.method];u.response?.type.type==="stream"&&s.push("STREAM"),s.forEach(o=>{d.push(`${o} ${TC(u.path.parts)}`),d.push(`${o} ${ize(u.path.parts)}`),u.environments.forEach(c=>{d.push(`${o} ${Cv(c.baseUrl,TC(u.path.parts))}`),d.push(`${o} ${Cv(c.baseUrl,ize(u.path.parts))}`);let b=Ezo(c);b!=null&&(d.push(`${o} ${Cv(b,TC(u.path.parts))}`),d.push(`${o} ${Cv(b,ize(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.trace(`Registering endpoint locator: ${o}`),this.#c.set(o,u)})}),i.websockets.forEach(u=>{a.webSockets.set(u.id,u);let l=e.createWebSocketId(u,n);this.#t.set(l,u);let d=[];["GET","WSS"].forEach(o=>{d.push(`${o} ${TC(u.path.parts)}`),d.push(`${o} ${ize(u.path.parts)}`),u.environments.forEach(c=>{d.push(`${o} ${Cv(c.baseUrl,TC(u.path.parts))}`),d.push(`${o} ${Cv(c.baseUrl,ize(u.path.parts))}`);let b=Ezo(c);b!=null&&(d.push(`${o} ${Cv(b,TC(u.path.parts))}`),d.push(`${o} ${Cv(b,ize(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.trace(`Registering websocket locator: ${o}`),this.#l.set(o,u)})}),i.webhooks.forEach(u=>{a.webhooks.set(u.id,u),this.#r.set(e.createWebhookId(u,n),u)})}),this.#e.forEach((i,n)=>{this.#n.set(i,n)}),this.#t.forEach((i,n)=>{this.#i.set(i,n)}),this.#r.forEach((i,n)=>{this.#a.set(i,n)}),this.#f(t.rootPackage,[])}#f(t,r){if(t==null)return;let i=aXt(t)?[...r,t.name]:r,n=i.length===0?[dKs]:i;if([n.join("."),n.join("/"),`${n.join(".")}.yml`].forEach(u=>{this.context?.logger.trace(`Registering subpackage locator: ${u}`),this.#s.set(u,t)}),t.pointsTo!=null)return this.#f(this.api.subpackages[t.pointsTo],i);t.endpoints.forEach(u=>{let l=[...i,u.id];[l.join("."),l.join("/")].forEach(s=>{this.context?.logger.trace(`Registering endpoint locator: ${s}`),this.#c.set(s,u)})}),t.websockets.forEach(u=>{let l=[...i,u.id];[l.join("."),l.join("/")].forEach(s=>{this.context?.logger.trace(`Registering websocket locator: ${s}`),this.#l.set(s,u)})}),t.webhooks.forEach(u=>{let l=[...i,u.id];[l.join("."),l.join("/")].forEach(s=>{this.context?.logger.trace(`Registering webhook locator: ${s}`),this.#u.set(s,u)})}),t.subpackages.forEach(u=>{this.#f(this.api.subpackages[u],i)})}get endpoints(){return this.#e}get webSockets(){return this.#t}get webhooks(){return this.#r}get endpointsByLocator(){return this.#c}get webSocketsByLocator(){return this.#l}get webhooksByLocator(){return this.#u}get subpackages(){return this.#o}get subpackagesByLocator(){return this.#s}getEndpointId(t){return this.#n.get(t)}getWebSocketId(t){return this.#i.get(t)}getWebhookId(t){return this.#a.get(t)}static createEndpointId(t,r){return zo.EndpointId(t.originalEndpointId??`${r}.${t.id}`)}static createWebSocketId(t,r){return zo.WebSocketId(`${r}.${t.id}`)}static createWebhookId(t,r){return zo.WebhookId(`${r}.${t.id}`)}};function Ezo(e){if(e!=null){if(e.baseUrl.startsWith("/"))return e.baseUrl;if(e.baseUrl.startsWith("http")||e.baseUrl.startsWith("ws"))try{return new URL(e.baseUrl).pathname}catch{return}}}var g1n=vi(pIo(),1),Ni_=vi(_Io(),1);function Ri_(e){let t=e.split(".")[0];if(t==null)return;let i=/(^\d{1,4})-(\d{1,2})-(\d{1,4})/.exec(t)?.[0];if(i!=null)try{return new Date(i)}catch{}}g1n.default.extend(Ni_.default);var OQD="Changelog",mQD=["summary","index","overview"],LQr=class{markdownToFullSlug;markdownToNoIndex;changelogFiles;docsWorkspace;idgen;constructor(t,r,i,n,a){this.markdownToFullSlug=t,this.markdownToNoIndex=r,this.changelogFiles=i,this.docsWorkspace=n,this.idgen=a}toChangelogNode(t){let r=t.title??OQD,i=[],n;for(let b of this.changelogFiles??[]){let g=Bus(b.split("/"));if(g==null)continue;let O=Ri_(g);if(O==null){let w=g.split(".")[0]?.toLowerCase();w!=null&&mQD.includes(w)&&(n=b);continue}let m=this.toRelativeFilepath(b);i.push({date:O,pageId:zo.PageId(m),absoluteFilepath:b})}let a=t.parentSlug.apply({fullSlug:n!=null?this.markdownToFullSlug.get(n)?.split("/"):void 0,skipUrlSlug:!1,urlSlug:t.slug??Oq(r)}),u=n!=null?this.markdownToNoIndex.get(n):void 0,l=i.map(b=>{let g=g1n.default.utc(b.date);return{id:this.idgen.get(b.pageId),type:"changelogEntry",title:g.format("MMMM D, YYYY"),slug:a.apply({fullSlug:this.markdownToFullSlug.get(b.absoluteFilepath)?.split("/"),urlSlug:g.format("YYYY/M/D")}).get(),icon:void 0,hidden:void 0,date:b.date.toISOString(),pageId:b.pageId,noindex:this.markdownToNoIndex.get(b.absoluteFilepath),authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}),d=pKs(l,b=>b.date,"desc"),s=n!=null?zo.PageId(this.toRelativeFilepath(n)):void 0,o=this.idgen.get(s??"changelog"),c=this.groupByYear(o,d,a);return{id:o,type:"changelog",title:r,slug:a.get(),icon:t.icon,hidden:t.hidden,children:c,overviewPageId:s,noindex:u,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:void 0}}orUndefined(){return this.changelogFiles!=null&&this.changelogFiles.length>0?this:void 0}groupByYear(t,r,i){let n=new Map;for(let a of r){let u=g1n.default.utc(a.date).year(),l=n.get(u)??[];l.push(a),n.set(u,l)}return pKs(Array.from(n.entries()).map(([a,u])=>{let l=i.append(a.toString()).get(),d=this.idgen.get(`${t}/year/${a}`);return{id:d,type:"changelogYear",title:a.toString(),year:a,slug:l,icon:void 0,hidden:void 0,children:this.groupByMonth(d,u,i),authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}),"year","desc")}groupByMonth(t,r,i){let n=new Map;for(let a of r){let u=g1n.default.utc(a.date).month()+1,l=n.get(u)??[];l.push(a),n.set(u,l)}return pKs(Array.from(n.entries()).map(([a,u])=>{let l=(0,g1n.default)(new Date(0,a-1));return{id:this.idgen.get(`${t}/month/${a}`),type:"changelogMonth",title:l.format("MMMM YYYY"),month:a,slug:i.append(a.toString()).get(),icon:void 0,hidden:void 0,children:u,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}),"month","desc")}toRelativeFilepath(t){if(t!=null)return Qq(this.docsWorkspace.absoluteFilePath,t)}};function pKs(e,t,r="asc"){return e.concat().sort((i,n)=>{let a=typeof t=="function"?t(i):i[t],u=typeof t=="function"?t(n):n[t];return a<u?r==="asc"?-1:1:a>u?r==="asc"?1:-1:0})}function Mzo(e){if(e)return{disabled:void 0,environments:e.environments!=null&&e.environments.length>0?e.environments.map(t=>zo.V1.EnvironmentId(t)):void 0,button:e.button!=null&&e.button.href?{href:zo.V1.Url(e.button.href)}:void 0,"limit-websocket-messages-per-connection":e.limitWebsocketMessagesPerConnection!=null?e.limitWebsocketMessagesPerConnection:void 0}}function V_a({child:e,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i}){if(e.type==="apiPackage"){let n=zo.V1.SlugGenerator.init(e.slug),u=(t.get(e.id)??[]).flatMap(s=>r(s,n)),l=e.children.map(s=>V_a({child:s,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i})),d=i(l,u);return{...e,children:d,pointsTo:void 0}}return e}function O1n({children:e,findEndpointById:t,stringifyEndpointPathParts:r,disableEndpointPairs:i,apiDefinitionId:n}){if(i)return e;let a=[],u=new Map;return e.forEach(l=>{if(l.type!=="endpoint"){a.push(l);return}let d=t(l.endpointId);if(d==null)throw new Error(`Endpoint ${l.endpointId} not found`);let s=`${d.method} ${r(d)}`,o=u.get(s);if(u.set(s,l),o==null||o.isResponseStream===l.isResponseStream){a.push(l);return}let c=a.indexOf(o),b=l.isResponseStream?l:o,g=l.isResponseStream?o:l,O={id:zo.V1.NodeId(`${n}:${g.endpointId}+${b.endpointId}`),type:"endpointPair",stream:b,nonStream:g};a[c]=O}),a}function Azo({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}){return O1n({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}).filter(u=>u.type==="apiPackage"?u.children.length>0:!0)}function oXt(e,t){if(t!=null)return Qq(e.absoluteFilePath,t)}function qzo({docsWorkspace:e,page:t,parentSlug:r,idgen:i,markdownFilesToFullSlugs:n,markdownFilesToNoIndex:a}){let u=zo.V1.PageId(oXt(e,t.absolutePath)),l=r.apply({fullSlug:n.get(t.absolutePath)?.split("/"),urlSlug:t.slug??Oq(t.title)});return{id:i.get(u),type:"page",pageId:u,title:t.title,slug:l.get(),icon:t.icon,hidden:t.hidden,noindex:t.noindex||a.get(t.absolutePath),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}var Tzo=class{apiSection;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;workspace;apiDefinitionId;#e;#t=new Set;#r=new Set;#n=new Set;#i=new Set;#a=new Map;#o=[];#c;#l;#u;disableEndpointPairs;constructor(t,r,i,n,a,u,l,d,s){this.apiSection=t,this.docsWorkspace=n,this.taskContext=a,this.markdownFilesToFullSlugs=u,this.markdownFilesToNoIndex=l,this.workspace=s,this.disableEndpointPairs=n.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=zo.V1.ApiDefinitionId(r.id),this.#e=Qfi.create(r,a),this.#u=d,this.#c=this.apiSection.overviewAbsolutePath!=null?zo.V1.PageId(oXt(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let o=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#l=i.apply({fullSlug:o?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??Oq(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#o=this.#s(this.apiSection.navigation,this.#e.api.rootPackage,this.#l)),this.#o=this.#y(this.#o.map(c=>this.#g(c)),this.#j(this.#e.api.rootPackage,this.#l))}get(){let t=zo.V1.followRedirects(this.#o),r=new LQr(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#u).orUndefined();return{id:this.#u.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#c,paginated:this.apiSection.paginated,slug:this.#l.get(),icon:this.apiSection.icon,hidden:this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#l,viewers:void 0}),children:this.#o,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#O(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#s(t,r,i){r=this.#e.resolveSubpackage(r);let n=r!=null?Qfi.getSubpackageId(r):void 0;return t.map(a=>U_a(a)._visit({link:u=>({id:this.#u.get(u.url),type:"link",title:u.text,icon:u.icon,url:zo.Url(u.url)}),page:u=>this.#f(u,i),package:u=>this.#h(u,i),section:u=>this.#_(u,i),item:({value:u})=>this.#p(u,n,i),endpoint:u=>this.#b(u,n,i)})).filter(u0)}#f(t,r){return qzo({page:t,parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex,idgen:this.#u})}#h(t,r){let i=t.overviewAbsolutePath!=null?zo.V1.PageId(oXt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#e.getSubpackageByIdOrLocator(t.package);if(a!=null){let u=Qfi.getSubpackageId(a),l=this.#u.get(i??`${this.apiDefinitionId}:${u}`);this.#i.has(u)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${u}`),this.#i.add(u),this.#a.set(l,[u]);let d=t.slug??(aXt(a)?a.urlSlug:this.apiSection.slug??Oq(this.apiSection.title)),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#s(t.contents,a,s);return{id:l,type:"apiPackage",children:o,title:t.title??(aXt(a)?a.displayName??v5t(a.name):this.apiSection.title),slug:s.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}else{this.taskContext.logger.warn(`Subpackage ${t.package} not found in ${this.apiDefinitionId}, treating it as a section`);let u=t.slug??Oq(t.package),l=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#s(t.contents,void 0,l);return{id:this.#u.get(i??`${this.apiDefinitionId}:${Oq(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#_(t,r){let i=t.overviewAbsolutePath!=null?zo.V1.PageId(oXt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(t.overviewAbsolutePath):void 0,u=this.#u.get(i??n??r.get()),l=t.referencedSubpackages.map(c=>{let b=this.#e.getSubpackageByIdOrLocator(c);return b!=null?Qfi.getSubpackageId(b):void 0}).filter(c=>(c==null&&this.taskContext.logger.error(`Subpackage ${c} not found in ${this.apiDefinitionId}`),c!=null)).filter(u0);this.#a.set(u,l),l.forEach(c=>{this.#i.has(c)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${c}`),this.#i.add(c)});let d=t.slug??Oq(t.title),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#s(t.contents,void 0,s);return{id:u,type:"apiPackage",children:o,title:t.title,slug:s.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:a,playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}#p(t,r,i){t=t.trim();let n=this.#e.getSubpackageByIdOrLocator(t);if(n!=null){let a=Qfi.getSubpackageId(n),u=this.#u.get(`${this.apiDefinitionId}:${a}`);this.#i.has(a)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a}`),this.#i.add(a),this.#a.set(u,[a]);let l=aXt(n)?n.urlSlug:"",d=i.apply({urlSlug:l});return{id:u,type:"apiPackage",children:[],title:aXt(n)?n.displayName??v5t(n.name):this.apiSection.title,slug:d.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}return this.#b({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i)}#b(t,r,i){let n=(r!=null?this.#e.subpackages.get(p2.SubpackageId(r))?.endpoints.get(p2.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(n!=null){let l=this.#e.getEndpointId(n);if(l==null)throw new Error(`Expected Endpoint ID for ${n.id}. Got undefined.`);this.#t.has(l)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${l}`),this.#t.add(l);let d=t.slug!=null?i.append(t.slug):i.apply(n);return{id:this.#u.get(`${this.apiDefinitionId}:${l}`),type:"endpoint",method:n.method,endpointId:l,apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:t.title??n.name??TC(n.path.parts),slug:d.get(),icon:t.icon,hidden:t.hidden,playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let a=(r!=null?this.#e.subpackages.get(p2.SubpackageId(r))?.webSockets.get(p2.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(a!=null){let l=this.#e.getWebSocketId(a);if(l==null)throw new Error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return this.#r.has(l)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${l}`),this.#r.add(l),{id:this.#u.get(`${this.apiDefinitionId}:${l}`),type:"webSocket",webSocketId:l,title:t.title??a.name??TC(a.path.parts),slug:(t.slug!=null?i.append(t.slug):i.apply(a)).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(a.availability),playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let u=(r!=null?this.#e.subpackages.get(p2.SubpackageId(r))?.webhooks.get(p2.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(zo.V1.WebhookId(t.endpoint));if(u!=null){let l=this.#e.getWebhookId(u);if(l==null)throw new Error(`Expected Webhook ID for ${u.id}. Got undefined.`);return this.#n.has(l)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${l}`),this.#n.add(l),{id:this.#u.get(`${this.apiDefinitionId}:${l}`),type:"webhook",webhookId:l,method:u.method,title:t.title??u.name??Cv("/",...u.path),slug:(t.slug!=null?i.append(t.slug):i.apply(u)).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#y(t,r){return Azo({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>TC(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#g(t){return V_a({child:t,nodeIdToSubpackageId:this.#a,convertApiDefinitionPackageId:(r,i)=>this.#P(r,i),mergeAndFilterChildren:this.#y.bind(this)})}#j(t,r){let i=[];return t.endpoints.forEach(n=>{let a=this.#e.getEndpointId(n);if(a==null)throw new Error(`Expected Endpoint ID for ${n.id}. Got undefined.`);if(this.#t.has(a))return;let u=r.apply(n);i.push({id:zo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:n.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:n.name??TC(n.path.parts),slug:u.get(),icon:void 0,hidden:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.websockets.forEach(n=>{let a=this.#e.getWebSocketId(n);if(a==null)throw new Error(`Expected WebSocket ID for ${n.id}. Got undefined.`);this.#r.has(a)||i.push({id:zo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:n.name??TC(n.path.parts),slug:r.apply(n).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(n.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.webhooks.forEach(n=>{let a=this.#e.getWebhookId(n);if(a==null)throw new Error(`Expected Webhook ID for ${n.id}. Got undefined.`);this.#n.has(a)||i.push({id:zo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:n.method,title:n.name??v5t(n.id),slug:r.apply(n).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.subpackages.forEach(n=>{if(this.#i.has(n))return;let a=this.#e.getSubpackageByIdOrLocator(n);if(a==null){this.taskContext.logger.error(`Subpackage ${n} not found in ${this.apiDefinitionId}`);return}let u=aXt(a)?r.apply(a):r,l=this.#P(n,u);l.length>0&&i.push({id:zo.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"apiPackage",children:l,title:aXt(a)?a.displayName??v5t(a.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&(i=i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,l=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(l)})),i}#P(t,r){let i=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return i==null?(this.taskContext.logger.error(`Subpackage ${t} not found in ${this.apiDefinitionId}`),[]):this.#j(i,r)}#O(t){return Mzo(t)}mergeEndpointPairs(t){return O1n({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>TC(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var Czo=class{#e={};#t={};#r={};#n={};constructor(t){for(let[r,i]of Object.entries(t.subpackages))this.#e[r]=i,this.#e[`subpackage_${r}`]=i;for(let[r,i]of Object.entries(t.endpoints)){this.#r[r]=i,this.#r[r.replace("endpoint_","")]=i,this.#r[r.replace("endpoint_","subpackage_")]=i;for(let n of[i.method,"STREAM"])i.environments?.forEach(a=>{this.#r[`${n} ${Cv(a.baseUrl,TC(i.path))}`]=i,this.#r[`${n} ${Cv(a.baseUrl,ize(i.path))}`]=i;let u=Ezo(a);u!=null&&(this.#r[`${n} ${Cv(u,TC(i.path))}`]=i,this.#r[`${n} ${Cv(u,ize(i.path))}`]=i)}),this.#r[`${i.method} ${TC(i.path)}`]=i,this.#r[`${i.method} ${ize(i.path)}`]=i}for(let[r,i]of Object.entries(t.webhooks))this.#t[r]=i,this.#t[r.replace("webhook_","")]=i,this.#t[r.replace("webhook_","subpackage_")]=i,this.#t[`${i.method} ${i.path.join("/")}`]=i;for(let[r,i]of Object.entries(t.websockets))this.#n[r]=i,this.#n[r.replace("websocket_","")]=i,this.#n[r.replace("websocket_","subpackage_")]=i,this.#n[`STREAM ${TC(i.path)}`]=i,this.#n[`STREAM ${ize(i.path)}`]=i}getSubpackageByLocator(t){if(["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","CONNECT","TRACE"].some(i=>t.includes(i)))return;let r=t.replace(".yml","").replace(".yaml","");return this.#e[r]}getWebhookByLocator(t,r){return this.#t[t]??this.#t[`${r}.${t}`]??this.#t[`webhook_${r}.${t}`]}getEndpointByLocator(t,r){return this.#r[t]??this.#r[`${r}.${t}`]??this.#r[`endpoint_${r}.${t}`]}getWebSocketByLocator(t,r){return this.#n[t]??this.#n[`${r}.${t}`]??this.#n[`websocket_${r}.${t}`]}};function W_a({item:e,parentSlug:t}){return t.apply({urlSlug:Oq(e.id.split(".").pop()??"")}).get()}var H_a=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;apiDefinitionId;#e;#t;#r=new Set;#n=new Set;#i=new Set;#a=new Set;#o=new Map;#c=[];#l;#u;#s;#f=new Map;disableEndpointPairs;constructor(t,r,i,n,a,u,l,d,s){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=l,this.markdownFilesToNoIndex=d,this.#e=r,this.#t=new Czo(r),this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=zo.V1.ApiDefinitionId(r.id),this.#s=s,this.#l=this.apiSection.overviewAbsolutePath!=null?zo.V1.PageId(oXt(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let o=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#u=i.apply({fullSlug:o?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??Oq(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#c=this.#h(this.apiSection.navigation,void 0,this.#u)),this.#c=this.#j(this.#c.map(c=>this.#P(c)),this.#O(this.#e,this.#u))}get(){let t=zo.V1.followRedirects(this.#c),r=new LQr(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#s).orUndefined();return{id:this.#s.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#l,paginated:this.apiSection.paginated,slug:this.#u.get(),icon:this.apiSection.icon,hidden:this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#u,viewers:void 0}),children:this.#c,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#S(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#h(t,r,i){return t.map(n=>U_a(n)._visit({link:a=>({id:this.#s.get(a.url),type:"link",title:a.text,icon:a.icon,url:zo.Url(a.url)}),page:a=>this.#_(a,i),package:a=>this.#p(a,i),section:a=>this.#b(a,i),item:({value:a})=>this.#y(a,r,i),endpoint:a=>this.#g(a,r,i)})).filter(u0)}#_(t,r){return qzo({docsWorkspace:this.docsWorkspace,page:t,parentSlug:r,idgen:this.#s,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex})}#p(t,r){let i=t.overviewAbsolutePath!=null?zo.V1.PageId(oXt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#t.getSubpackageByLocator(t.package);if(a!=null){let u=this.#s.get(i??`${this.apiDefinitionId}:${a.id}`);this.#a.has(a.id)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a.id}`),this.#a.add(a.id),this.#o.set(u,[a.id]);let l=t.slug??Oq(a.name),d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#h(t.contents,a.id,d),o={id:u,type:"apiPackage",children:s,title:t.title??a.displayName??v5t(a.name),slug:d.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#f.set(a.id,o),o}else{this.taskContext.logger.warn(`Subpackage ${t.package} not found in ${this.apiDefinitionId}, treating it as a section`);let u=t.slug??Oq(t.package),l=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#h(t.contents,t.package,l),s={id:this.#s.get(i??`${this.apiDefinitionId}:${Oq(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#f.set(t.package,s),s}}#b(t,r){let i=t.overviewAbsolutePath!=null?zo.V1.PageId(oXt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#s.get(i??n??r.get()),u=t.referencedSubpackages.map(c=>{let b=this.#t.getSubpackageByLocator(c);return b?.id}).filter(c=>(c==null&&this.taskContext.logger.error(`Subpackage ${c} not found in ${this.apiDefinitionId}`),c!=null)).filter(u0);this.#o.set(a,u),u.forEach(c=>{this.#a.has(c)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${c}`),this.#a.add(c)});let l=t.slug??Oq(t.title),d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#h(t.contents,t.title,d),o={id:a,type:"apiPackage",children:s,title:t.title,slug:d.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return u.forEach(c=>{this.#f.set(c,o)}),o}#y(t,r,i){t=t.trim();let n=this.#t.getSubpackageByLocator(t);if(n!=null){let a=n.id,u=this.#s.get(`${this.apiDefinitionId}:${a}`);this.#a.has(a)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a}`),this.#a.add(a),this.#o.set(u,[a]);let l=Oq(n.name),d=i.apply({urlSlug:l}),s={id:u,type:"apiPackage",children:[],title:n.displayName??v5t(n.name),slug:d.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};return this.#f.set(a,s),s}return this.#g({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i)}#g(t,r,i){let n=this.#t.getEndpointByLocator(t.endpoint,r);if(n!=null){if(n.id==null)throw new Error(`Expected Endpoint ID for ${n.id}. Got undefined.`);this.#r.has(n.id)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${n.id}`),this.#r.add(n.id);let l=t.slug!=null?i.append(t.slug).get():W_a({item:n,parentSlug:i});return{id:this.#s.get(`${this.apiDefinitionId}:${n.id}`),type:"endpoint",method:n.method,endpointId:n.id,apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(n.availability),isResponseStream:n.responses?.[0]?.body.type==="stream",title:t.title??n.displayName??TC(n.path),slug:l,icon:t.icon,hidden:t.hidden,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let a=this.#t.getWebSocketByLocator(t.endpoint,r);if(a!=null){if(a.id==null)throw new Error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return this.#n.has(a.id)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${a.id}`),this.#n.add(a.id),{id:this.#s.get(`${this.apiDefinitionId}:${a.id}`),type:"webSocket",webSocketId:a.id,title:t.title??a.displayName??TC(a.path),slug:t.slug!=null?i.append(t.slug).get():W_a({item:a,parentSlug:i}),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(a.availability),playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let u=this.#t.getWebhookByLocator(t.endpoint,r);if(u!=null){if(u.id==null)throw new Error(`Expected Webhook ID for ${u.id}. Got undefined.`);return this.#i.has(u.id)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${u.id}`),this.#i.add(u.id),{id:this.#s.get(`${this.apiDefinitionId}:${u.id}`),type:"webhook",webhookId:u.id,method:u.method,title:t.title??u.displayName??Cv("/",...u.path),slug:t.slug!=null?i.append(t.slug).get():W_a({item:u,parentSlug:i}),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#j(t,r){return Azo({left:t,right:r,findEndpointById:i=>this.#t.getEndpointByLocator(i,void 0),stringifyEndpointPathParts:i=>TC(i.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#P(t){return V_a({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(r,i)=>this.#w(r,i),mergeAndFilterChildren:this.#j.bind(this)})}#O(t,r){let i=[];return Object.entries(t.subpackages).forEach(([n,a])=>{if(!this.#a.has(n)){let u=this.#D(n,a,r);u!=null&&i.push(u)}}),Object.entries(t.endpoints).forEach(([n,a])=>{if(n==null)throw new Error(`Expected Endpoint ID for ${a.id}. Got undefined.`);!this.#r.has(KM.EndpointId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#M(n,a,r,i)}),Object.entries(t.websockets).forEach(([n,a])=>{if(n==null)throw new Error(`Expected WebSocket ID for ${a.id}. Got undefined.`);!this.#n.has(KM.WebSocketId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#E(n,a,r,i)}),Object.entries(t.webhooks).forEach(([n,a])=>{if(n==null)throw new Error(`Expected Webhook ID for ${a.id}. Got undefined.`);!this.#i.has(KM.WebhookId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#d(n,a,r,i)}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,l=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(l)}),i}#D(t,r,i){let n=zo.V1.SlugGenerator.init(i.get()).apply({urlSlug:Oq(r.name)}),a=this.#w(t,n),u={id:zo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"apiPackage",children:a,title:r.displayName??v5t(r.name),slug:n.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};return this.#f.set(t,u),a.length>0?u:void 0}#m(t,r,i,n){r.slug=W_a({item:t,parentSlug:i}),n.push(r)}#M(t,r,i,n){let a={id:zo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"endpoint",method:r.method,endpointId:KM.EndpointId(t),apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(r.availability),isResponseStream:r.responses?.[0]?.body.type==="stream",title:r.displayName??TC(r.path),slug:i.get(),icon:void 0,hidden:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#m(r,a,i,n)}#E(t,r,i,n){let a={id:zo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webSocket",webSocketId:KM.WebSocketId(t),title:r.displayName??TC(r.path),slug:i.get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(r.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#m(r,a,i,n)}#d(t,r,i,n){let a={id:zo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webhook",webhookId:KM.WebhookId(t),method:r.method,title:r.displayName??v5t(r.id),slug:i.get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#m(r,a,i,n)}#T(t){let r=Object.fromEntries(Object.entries(this.#e?.subpackages??{}).filter(([u,l])=>t===this.#e.id?l.id.split(".").length===1:l.id!=null&&l.id.includes(t)&&l.id!==t&&l.id.split(".").length===t.split(".").length+1)),i=Object.fromEntries(Object.entries(this.#e?.endpoints??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===KM.api.v1.SubpackageId(t))),n=Object.fromEntries(Object.entries(this.#e?.websockets??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===KM.api.v1.SubpackageId(t))),a=Object.fromEntries(Object.entries(this.#e?.webhooks??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===KM.api.v1.SubpackageId(t)));return{id:KM.ApiDefinitionId(t),endpoints:i,websockets:n,webhooks:a,types:{},subpackages:r,auths:{},globalHeaders:void 0,snippetsConfiguration:void 0}}#w(t,r){let i=t!=null?this.#T(t):void 0;return i==null?(this.taskContext.logger.error(`Subpackage ${t} not found in ${this.apiDefinitionId}`),[]):this.#O(i,r)}#S(t){return Mzo(t)}mergeEndpointPairs(t){return O1n({children:t,findEndpointById:r=>this.#e?.endpoints[r],stringifyEndpointPathParts:r=>TC(r.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var Fi_=vi(require("crypto"),1);function PQD(e){return Fi_.default.createHash("sha256").update(e).digest("hex")}var Bzo=class e{static init(){return new e}constructor(){}#e=new Map;#t=new Set;#r(t){let r=this.#e.get(t)??0;return this.#e.set(t,r+1),PQD(r===0?t:`${t}-${r}`)}#n(t){let r=this.#r(t),i=0;for(;this.#t.has(r);)if(r=this.#r(t),i++,i>100)throw new Error(`Infinite loop detected for id: ${t}`);return r}get(t){return zo.V1.NodeId(this.#n(t))}};function xzo(e){return e==null?{}:{pythonSdk:e.python!=null?{package:typeof e.python=="string"?e.python:e.python.package,version:typeof e.python=="string"?void 0:e.python.version}:void 0,typescriptSdk:e.typescript!=null?{package:typeof e.typescript=="string"?e.typescript:e.typescript.package,version:typeof e.typescript=="string"?void 0:e.typescript.version}:void 0,goSdk:e.go!=null?{githubRepo:typeof e.go=="string"?e.go:e.go.package,version:typeof e.go=="string"?void 0:e.go.version}:void 0,javaSdk:e.java!=null?{coordinate:typeof e.java=="string"?e.java:e.java.package,version:typeof e.java=="string"?void 0:e.java.version}:void 0,rubySdk:e.ruby!=null?{gem:typeof e.ruby=="string"?e.ruby:e.ruby.package,version:typeof e.ruby=="string"?void 0:e.ruby.version}:void 0,csharpSdk:e.csharp!=null?{package:typeof e.csharp=="string"?e.csharp:e.csharp.package,version:typeof e.csharp=="string"?void 0:e.csharp.version}:void 0}}var Izo=vi(zte(),1);var _Ks=vi(zte(),1);function Li_(e,t,r){let i=e.schemes[0];if(e.schemes.length===1&&i!=null)switch(i.type){case"basic":return{type:"basicAuth",passwordName:i.password.originalName,usernameName:i.username.originalName};case"bearer":return{type:"bearerAuth",tokenName:i.token.originalName};case"header":return{type:"header",headerWireValue:i.name.wireValue,nameOverride:i.name.name.originalName,prefix:i.prefix};case"oauth":{let n=i.configuration.tokenEndpoint.responseProperties.accessToken.propertyPath?.map(a=>a.originalName).join(".")||"$.body.access_token";return r?.oauth?{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:_Ks.FernRegistry.EndpointId(i.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:_Ks.FernRegistry.JqString(n),headerName:i.configuration.tokenHeader,tokenPrefix:i.configuration.tokenPrefix}}}:{type:"bearerAuth",tokenName:"token"}}default:Ko(i)}}var VP=vi(zte(),1);var Jfi=vi(zte(),1);function Vi_(e){return e._visit({alias:t=>({type:"alias",value:qD(t.aliasOf)}),enum:t=>({type:"enum",default:t.default!=null?t.default.name.wireValue:void 0,values:t.values.map(r=>({description:r.docs??void 0,value:r.name.wireValue,availability:g7(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>Jfi.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:Jfi.FernRegistry.PropertyKey(r.name.wireValue),valueType:qD(r.valueType),availability:g7(r.availability)})),extraProperties:SQD(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:Jfi.FernRegistry.PropertyKey(i.name.wireValue),valueType:qD(i.valueType),availability:g7(i.availability),description:i.docs}));return{type:"discriminatedUnion",discriminant:t.discriminant.wireValue,variants:t.types.map(i=>({description:i.docs??void 0,discriminantValue:i.discriminantValue.wireValue,displayName:i.displayName,availability:i.availability!=null?g7(i.availability):void 0,additionalProperties:Tc.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[Jfi.FernRegistry.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:Jfi.FernRegistry.PropertyKey(n.name.wireValue),valueType:qD(n.type),description:void 0,availability:void 0},...r],extraProperties:void 0}),noProperties:()=>({extends:[],properties:r,extraProperties:void 0}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+i.shape.propertiesType)}})}))}},undiscriminatedUnion:t=>({type:"undiscriminatedUnion",variants:t.members.map(r=>({typeName:r.type.type==="named"?r.type.name.originalName:void 0,description:r.docs??void 0,type:qD(r.type),availability:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function qD(e){return e._visit({container:t=>Tc.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:qD(r)}),map:({keyType:r,valueType:i})=>({type:"map",keyType:qD(r),valueType:qD(i)}),optional:r=>({type:"optional",itemType:qD(r),defaultValue:void 0}),nullable:r=>({type:"optional",itemType:qD(r),defaultValue:void 0}),set:r=>({type:"set",itemType:qD(r)}),literal:r=>Tc.types.Literal._visit(r,{boolean:i=>({type:"literal",value:{type:"booleanLiteral",value:i}}),string:i=>({type:"literal",value:{type:"stringLiteral",value:i}}),_other:()=>{throw new Error("Unknown literal type: "+r.type)}}),_other:()=>{throw new Error("Unknown container reference: "+t.type)}}),named:t=>({type:"id",value:Jfi.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:Tc.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>wQD(t.v2),float:()=>Ui_(t.v2),double:()=>Ui_(t.v2),string:()=>jQD(t.v2),long:()=>({type:"long",default:t.v2?.type==="long"?t.v2.default:void 0,minimum:void 0,maximum:void 0}),boolean:()=>({type:"boolean",default:t.v2?.type==="boolean"?t.v2.default:void 0}),dateTime:()=>({type:"datetime",default:void 0}),date:()=>({type:"date",default:void 0}),uuid:()=>({type:"uuid",default:void 0}),base64:()=>({type:"base64",mimeType:void 0,default:void 0}),bigInteger:()=>({type:"bigInteger",default:t.v2?.type==="bigInteger"?t.v2.default:void 0}),uint:()=>({type:"uint"}),uint64:()=>({type:"uint64"}),_other:()=>{throw new Error("Unknown primitive: "+t.v1)}})}),unknown:()=>({type:"unknown"}),_other:()=>{throw new Error("Unknown Type reference: "+e.type)}})}function jQD(e){let t=e!=null&&e.type==="string"?e.validation:void 0;return{type:"string",format:t?.format,regex:t?.pattern,minLength:t?.minLength,maxLength:t?.maxLength,default:e!=null&&e.type==="string"?e.default:void 0}}function wQD(e){let t=e!=null&&e.type==="integer"?e.validation:void 0;return{type:"integer",minimum:t?.min,maximum:t?.max,default:e!=null&&e.type==="integer"?e.default:void 0}}function Ui_(e){let t=e!=null&&e.type==="double"?e.validation:void 0;return{type:"double",minimum:t?.min,maximum:t?.max,default:e!=null&&e.type==="double"?e.default:void 0}}function SQD(e){return typeof e=="boolean"?e?nh.unknown():void 0:typeof e=="string"?{type:"id",value:Jfi.FernRegistry.TypeId(e),default:void 0}:qD(e)}function yKs(e,t){let r=e.service!=null?t.services[e.service]:void 0,i=e.webhooks!=null?t.webhookGroups[e.webhooks]:void 0,n=e.websocket!=null&&t.websocketChannels!=null?t.websocketChannels[e.websocket]:void 0;return{endpoints:r!=null?EQD(r,t):[],webhooks:i!=null?DQD(i):[],websockets:n!=null?[MQD(n,t)]:[],types:e.types.map(a=>VP.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>VP.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?VP.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function DQD(e){return e.map(t=>({description:t.docs??void 0,id:VP.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??jkn(t.name.originalName),headers:t.headers.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:qD(r.valueType),availability:g7(r.availability)})),payload:zQD(t.payload),examples:t.examples!=null?t.examples.map(r=>({payload:r.payload.jsonExample})):[]}))}function EQD(e,t){let r=[];for(let i of e.endpoints){let n=i.autogeneratedExamples[0],a=[];if(i.userSpecifiedExamples.length>0)a.push(...i.userSpecifiedExamples.map(l=>hKs({userSpecifiedExample:l,...n!=null&&{autogeneratedExample:n},irEndpoint:i,ir:t})).filter(u0));else if(n!=null){let l=hKs({autogeneratedExample:n,irEndpoint:i,ir:t});l!=null&&a.push(l)}else if(i.response?.body?.type==="fileDownload"){let l=lpa({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(l.type==="success"){let d=hKs({autogeneratedExample:l,irEndpoint:i,ir:t});if(d!=null){let s={...d,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let u={availability:g7(i.availability??e.availability),auth:i.auth,description:i.docs??void 0,method:CQD(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?VP.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?AQD({environmentsConfig:t.environments,endpoint:i}):void 0,id:VP.FernRegistry.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.displayName??jkn(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(l=>({description:l.docs??void 0,key:VP.FernRegistry.PropertyKey(l.name.originalName),type:qD(l.valueType),availability:void 0})),parts:[...m1n(i.basePath),...m1n(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(l=>({description:l.docs??void 0,key:VP.FernRegistry.PropertyKey(l.name.originalName),type:qD(l.valueType),availability:void 0})),parts:[...t.basePath!=null?m1n(t.basePath):[],...m1n(e.basePath),...m1n(i.path)]},queryParameters:i.queryParameters.map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:qD(l.valueType),availability:g7(l.availability)})),headers:[...e.headers,...i.headers].map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:qD(l.valueType),availability:g7(l.availability)})),request:i.requestBody!=null?BQD(i.requestBody):void 0,response:i.response!=null?xQD(i.response):void 0,errors:void 0,errorsV2:IQD(i.errors,t),examples:a};r.push(u)}return r}function MQD(e,t){return{auth:e.auth,availability:g7(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?VP.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?qQD({environmentsConfig:t.environments,channel:e}):[],id:VP.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??jkn(e.name.originalName),path:{pathParameters:e.pathParameters.map(r=>({description:r.docs??void 0,key:VP.FernRegistry.PropertyKey(r.name.originalName),type:qD(r.valueType),availability:void 0})),parts:m1n(e.path)},headers:e.headers.map(r=>({key:r.name.wireValue,type:qD(r.valueType),description:r.docs,availability:g7(r.availability)})),queryParameters:e.queryParameters.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:qD(r.valueType),availability:g7(r.availability)})),messages:e.messages.map(r=>({type:VP.FernRegistry.api.v1.WebSocketMessageId(r.type),displayName:r.displayName,origin:r.origin,body:RQD(r.body),description:r.docs,availability:g7(r.availability)})),examples:e.examples.map(r=>({name:r.name?.originalName,description:r.docs,path:r.url,pathParameters:r.pathParameters.reduce((i,n)=>(i[VP.FernRegistry.PropertyKey(n.name.originalName)]=n.value.jsonExample,i),{}),queryParameters:r.queryParameters.reduce((i,n)=>(i[n.name.wireValue]=n.value.jsonExample,i),{}),headers:r.headers.reduce((i,n)=>(i[n.name.wireValue]=n.value.jsonExample,i),{}),messages:r.messages.map(i=>({type:VP.FernRegistry.api.v1.WebSocketMessageId(i.type),body:i.body.jsonExample}))}))}}function g7(e){if(e!=null)switch(e.status){case"DEPRECATED":return VP.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return VP.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return VP.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return VP.FernRegistry.Availability.Beta;default:Ko(e.status)}}function AQD({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:VP.FernRegistry.EnvironmentId(n.id),baseUrl:n.url}));case"multipleBaseUrls":if(i==null)throw new Error(`Expected endpoint ${t.name.originalName} to have base url.`);return r.environments.map(n=>{let a=n.urls[i];if(a==null)throw new Error(`Expected environment ${n.id} to contain url for ${i}`);return{id:VP.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:Ko(r)}}function qQD({environmentsConfig:e,channel:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:VP.FernRegistry.EnvironmentId(n.id),baseUrl:TQD(n.url,"wss")}));case"multipleBaseUrls":if(i==null)throw new Error(`Expected channel ${t.name.originalName} to have base url.`);return r.environments.map(n=>{let a=n.urls[i];if(a==null)throw new Error(`Expected environment ${n.id} to contain url for ${i}`);return{id:VP.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:Ko(r)}}function TQD(e,t){return e.replace(/^[^:]+/,t)}function CQD(e){return Tc.http.HttpMethod._visit(e,{get:()=>VP.FernRegistry.HttpMethod.Get,post:()=>VP.FernRegistry.HttpMethod.Post,put:()=>VP.FernRegistry.HttpMethod.Put,patch:()=>VP.FernRegistry.HttpMethod.Patch,delete:()=>VP.FernRegistry.HttpMethod.Delete,_other:()=>{throw new Error("Unknown http method: "+e)}})}function m1n(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:VP.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function BQD(e){let t=Tc.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??zB.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>VP.FernRegistry.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:VP.FernRegistry.PropertyKey(i.name.wireValue),valueType:qD(i.valueType),availability:g7(i.availability)})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??zB.APPLICATION_JSON,shape:{type:"reference",value:qD(r.requestBodyType)},description:r.docs??void 0}),fileUpload:r=>({type:"fileUpload",value:{name:r.name.originalName,description:void 0,availability:void 0,properties:r.properties.map(i=>i._visit({file:n=>{let a=n._visit({file:u=>({type:"file",key:VP.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:VP.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:void 0,availability:void 0}),_other:()=>{}});if(a!=null)return{type:"file",value:a}},bodyProperty:n=>({type:"bodyProperty",key:VP.FernRegistry.PropertyKey(n.name.wireValue),valueType:qD(n.valueType),contentType:n.contentType,description:n.docs,availability:g7(n.availability),exploded:n.style==="exploded"}),_other:()=>{}})).filter(u0)},description:r.docs??void 0}),bytes:r=>({type:"bytes",description:r.docs??void 0,availability:void 0,isOptional:r.isOptional,contentType:r.contentType}),_other:()=>{throw new Error("Unknown HttpRequestBody: "+e.type)}});return t!=null?{type:t,description:e.docs}:void 0}function xQD(e){if(e.body==null)return;let t,r=Tc.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:qD(i.responseBodyType)}),text:()=>{},bytes:()=>{},streamParameter:()=>{},streaming:i=>{if(i.type==="text")return t=i.docs,{type:"streamingText"};if(i.type==="json")return t=i.docs,{type:"stream",shape:{type:"reference",value:qD(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:qD(i.payload)},terminator:i.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});return r!=null?{type:r,statusCode:e.statusCode,description:t}:e.statusCode!=null?{statusCode:e.statusCode,description:t,type:{type:"object",extends:[],properties:[],extraProperties:void 0}}:void 0}function IQD(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let i of e){let n=t.errors[i.error.errorId];n&&r.push({type:n.type==null?void 0:{type:"alias",value:qD(n.type)},statusCode:n.statusCode,description:n.docs??void 0,name:n.name.name.originalName,availability:void 0,examples:n.examples.map(a=>({name:a.name?.originalName,responseBody:{type:"json",value:a.jsonExample},description:a.docs}))})}else for(let i of e){let n=t.errors[i.error.errorId];if(n){let a=[{key:VP.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.discriminant.wireValue),valueType:{type:"literal",value:{type:"stringLiteral",value:n.discriminantValue.name.originalName}},description:n.docs,availability:void 0}];n.type!=null&&a.push({key:VP.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:qD(n.type),description:n.docs,availability:void 0}),r.push({type:n.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},statusCode:n.statusCode,description:n.docs??void 0,availability:void 0,name:n.name.name.originalName,examples:n.examples.map(u=>({name:u.name?.originalName,responseBody:{type:"json",value:u.jsonExample},description:u.docs}))})}}return r}function hKs({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:i}){let n=i.headers.map(l=>{let d=l.valueType.type==="container"&&l.valueType.container.type==="literal"?l.valueType.container.literal._visit({boolean:s=>`${s}`,string:s=>s,_other:()=>{}}):void 0;if(d!=null)return{name:l.name,value:{jsonExample:d,shape:Tc.ExampleTypeReferenceShape.primitive(Tc.ExamplePrimitive.string({original:d}))}}}).filter(u0),a=e?.example??t?.example;if(a==null)return;let{codeSamples:u}=e??{codeSamples:[]};return{name:a.name?.originalName,description:a.docs,path:a.url,pathParameters:[...a.rootPathParameters,...a.servicePathParameters,...a.endpointPathParameters].reduce((l,d)=>(l[VP.FernRegistry.PropertyKey(d.name.originalName)]=d.value.jsonExample,l),{}),queryParameters:a.queryParameters.reduce((l,d)=>(l[d.name.wireValue]=d.value.jsonExample,l),{}),headers:[...n,...a.serviceHeaders,...a.endpointHeaders].reduce((l,d)=>(l[d.name.wireValue]=d.value.jsonExample,l),{}),requestBody:a.request?.jsonExample,requestBodyV3:r.requestBody?._visit({inlinedRequestBody:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,reference:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,fileUpload:l=>{if(a.request==null)return;let d={};if(Hj(a.request.jsonExample)){let s=a.request.jsonExample;for(let o of l.properties)o._visit({file:c=>{let b=s[c.key.wireValue];if(c.type==="file")d[c.key.wireValue]={type:"filename",value:typeof b=="string"?b:"<file1>"};else if(c.type==="fileArray"){let g=(Array.isArray(b)?b:[b]).filter(O=>typeof O=="string");d[c.key.wireValue]={type:"filenames",value:g}}},bodyProperty:c=>{if(c.style==="exploded"){let b=s[c.name.wireValue];d[c.name.wireValue]={type:"exploded",value:Array.isArray(b)?b:[b]}}else d[c.name.wireValue]={type:"json",value:s[c.name.wireValue]}},_other:L2t})}return{type:"form",value:d}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??Tc.http.ExampleResponse._visit(a.response,{ok:l=>l._visit({body:d=>d!=null?200:204,stream:d=>d.length>0?200:204,sse:d=>d.length>0?200:204,_other:()=>{throw new Error("Unknown ExampleResponseBody: "+l.type)}}),error:({error:l})=>{let d=i.errors[l.errorId];if(d==null)throw new Error("Cannot find error "+l.errorId);return d.statusCode},_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),responseBody:a.response._visit({ok:l=>l._visit({body:d=>d?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:l=>l.body?.jsonExample,_other:()=>{}}),responseBodyV3:a.response._visit({ok:l=>l._visit({body:d=>d!=null?{type:"json",value:d.jsonExample}:void 0,stream:d=>({type:"stream",value:d.map(s=>s.jsonExample)}),sse:d=>({type:"sse",value:d.map(({event:s,data:o})=>({event:s,data:o.jsonExample}))}),_other:()=>{throw new Error("Unknown ExampleResponseBody: "+l.type)}}),error:l=>l.body!=null?{type:"json",value:l.body.jsonExample}:void 0,_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),codeSamples:u?.map(l=>C1e._visit(l,{language:d=>({language:d.language,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:d.install}),sdk:d=>({language:d.sdk,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:void 0}),_other:()=>{}})).filter(u0)}}function zQD(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>VP.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:VP.FernRegistry.PropertyKey(t.name.wireValue),valueType:qD(t.valueType),availability:g7(t.availability)})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:qD(e.payloadType)},description:e.docs};default:Ko(e)}}function RQD(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>VP.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:VP.FernRegistry.PropertyKey(t.name.wireValue),valueType:qD(t.valueType),availability:g7(t.availability)})),extraProperties:void 0};case"reference":return{type:"reference",value:qD(e.bodyType)};default:Ko(e)}}function SSe({ir:e,snippetsConfig:t,playgroundConfig:r}){let i={types:{},subpackages:{},rootPackage:yKs(e.rootPackage,e),auth:Li_(e.auth,e,r),snippetsConfiguration:t,globalHeaders:e.headers.map(n=>({availability:g7(n.availability),description:n.docs??void 0,key:n.name.wireValue,type:qD(n.valueType)})),navigation:void 0};for(let[n,a]of Object.entries(e.types))i.types[Izo.FernRegistry.TypeId(n)]={description:a.docs??void 0,name:a.name.name.originalName,shape:Vi_(a.shape),availability:g7(a.availability)};for(let[n,a]of Object.entries(e.subpackages)){let u=a.service!=null?e.services[a.service]:void 0;i.subpackages[Izo.FernRegistry.api.v1.SubpackageId(n)]={subpackageId:Izo.FernRegistry.api.v1.SubpackageId(n),displayName:u?.displayName,name:a.name.originalName,description:a.docs??void 0,...yKs(a,e)}}return i}var vKs=vi(zte(),1);async function bKs({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:u}){let l=_2({workspace:t,audiences:n,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new d2(r,t)}),d=zTi({token:i.value}),s=SSe({ir:l,snippetsConfig:a,playgroundConfig:u}),o=await d.api.v1.register.registerApiDefinition({orgId:vKs.FernRegistry.OrgId(e),apiId:vKs.FernRegistry.ApiId(l.apiName.originalName),definition:s});if(o.ok)return r.logger.debug(`Registered API Definition ${o.body.apiDefinitionId}`),{id:o.body.apiDefinitionId,ir:l};switch(o.error.error){case"UnauthorizedError":case"UserNotInOrgError":return r.failAndThrow("You do not have permissions to register the docs. Reach out to support@buildwithfern.com");default:return r.failAndThrow("Failed to register API",o.error)}}var NQD=new Fzi({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function $_a(e,t,r){return g_a(y_a(SSe({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:r}),p2.ApiDefinitionId(t),NQD))}var I_={};Io(I_,{AlgoliaSearchIndex:()=>Wi_,ApiDefinitionId:()=>ln_,ApiId:()=>_n_,Availability:()=>An_,DocsConfigId:()=>hn_,EndpointId:()=>vn_,EndpointPathLiteral:()=>En_,EnvironmentId:()=>yn_,FileId:()=>Pn_,HttpMethod:()=>Mn_,IndexSegmentId:()=>Hi_,JqString:()=>wn_,OrgId:()=>dn_,PageId:()=>mn_,PayloadLocation:()=>ra_,PropertyKey:()=>Sn_,PullRequestState:()=>Xn_,RoleId:()=>Dn_,TokenId:()=>pn_,TypeId:()=>On_,Url:()=>jn_,VersionId:()=>fn_,WebSocketId:()=>bn_,WebhookId:()=>gn_,algolia:()=>gKs,api:()=>AKs,commons:()=>qKs,diff:()=>qn_,docs:()=>FKs,generators:()=>UKs,git:()=>VKs,navigation:()=>$Ks,sdks:()=>QKs,snippets:()=>ea_,snippetsFactory:()=>ta_,templates:()=>JKs,tokens:()=>ia_});var gKs={};Io(gKs,{AlgoliaSearchIndex:()=>Wi_,IndexSegmentId:()=>Hi_});function Wi_(e){return e}function Hi_(e){return e}var AKs={};Io(AKs,{latest:()=>PKs,v1:()=>MKs});var PKs={};Io(PKs,{AuthSchemeId:()=>$i_,WebhookHttpMethod:()=>Ki_,auth:()=>OKs,commons:()=>Gi_,endpoint:()=>Qi_,type_:()=>Ji_,webhook:()=>mKs,websocket:()=>Yi_});var OKs={};Io(OKs,{AuthSchemeId:()=>$i_});function $i_(e){return e}var Gi_={};var Qi_={};var Ji_={};var mKs={};Io(mKs,{WebhookHttpMethod:()=>Ki_});var Ki_={Get:"GET",Post:"POST"};var Yi_={};var MKs={};Io(MKs,{SubpackageId:()=>on_,WebSocketMessageId:()=>un_,WebSocketMessageOrigin:()=>sn_,WebhookHttpMethod:()=>cn_,commons:()=>EKs,db:()=>jKs,read:()=>SKs,register:()=>DKs});var jKs={};Io(jKs,{endpoint:()=>Xi_});var Xi_={};var SKs={};Io(SKs,{SupportedLanguage:()=>Zi_,endpoint:()=>wKs,type_:()=>ki_,webhook:()=>en_,websocket:()=>tn_});var wKs={};Io(wKs,{SupportedLanguage:()=>Zi_});var Zi_={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var ki_={};var en_={};var tn_={};var DKs={};Io(DKs,{SourceId:()=>FQD,endpoint:()=>rn_,type_:()=>in_,webhook:()=>nn_,websocket:()=>an_});var rn_={};var in_={};var nn_={};var an_={};function FQD(e){return e}var EKs={};Io(EKs,{SubpackageId:()=>on_,WebSocketMessageId:()=>un_,WebSocketMessageOrigin:()=>sn_,WebhookHttpMethod:()=>cn_});function on_(e){return e}function un_(e){return e}var sn_={Client:"client",Server:"server"};var cn_={Get:"GET",Post:"POST"};var qKs={};Io(qKs,{ApiDefinitionId:()=>ln_,ApiId:()=>_n_,Availability:()=>An_,DocsConfigId:()=>hn_,EndpointId:()=>vn_,EndpointPathLiteral:()=>En_,EnvironmentId:()=>yn_,FileId:()=>Pn_,HttpMethod:()=>Mn_,JqString:()=>wn_,OrgId:()=>dn_,PageId:()=>mn_,PropertyKey:()=>Sn_,RoleId:()=>Dn_,TokenId:()=>pn_,TypeId:()=>On_,Url:()=>jn_,VersionId:()=>fn_,WebSocketId:()=>bn_,WebhookId:()=>gn_});function ln_(e){return e}function fn_(e){return e}function dn_(e){return e}function pn_(e){return e}function _n_(e){return e}function hn_(e){return e}function yn_(e){return e}function vn_(e){return e}function bn_(e){return e}function gn_(e){return e}function On_(e){return e}function mn_(e){return e}function Pn_(e){return e}function jn_(e){return e}function wn_(e){return e}function Sn_(e){return e}function Dn_(e){return e}function En_(e){return e}var Mn_={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var An_={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var qn_={};var FKs={};Io(FKs,{latest:()=>BKs,v1:()=>RKs,v2:()=>NKs});var BKs={};Io(BKs,{Layout:()=>Cn_,MdxEngine:()=>LQD,TwitterCardSetting:()=>Bn_,commons:()=>Tn_,frontmatter:()=>TKs,seo:()=>CKs});var LQD={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var Tn_={};var TKs={};Io(TKs,{Layout:()=>Cn_});var Cn_={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var CKs={};Io(CKs,{TwitterCardSetting:()=>Bn_});var Bn_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var RKs={};Io(RKs,{commons:()=>zKs,db:()=>xn_,read:()=>In_,write:()=>xKs});var xn_={};var In_={};var xKs={};Io(xKs,{DocsRegistrationId:()=>VQD,FilePath:()=>UQD});function UQD(e){return e}function VQD(e){return e}var zKs={};Io(zKs,{ContentAlignment:()=>Fn_,FontDisplay:()=>Hn_,FontStyle:()=>Wn_,HeaderPosition:()=>Ln_,JsScriptStrategy:()=>Vn_,ProgrammingLanguage:()=>zn_,SearchbarPlacement:()=>Rn_,TabsPlacement:()=>Nn_,TwitterCardSetting:()=>Un_,commons:()=>IKs});var IKs={};Io(IKs,{ContentAlignment:()=>Fn_,FontDisplay:()=>Hn_,FontStyle:()=>Wn_,HeaderPosition:()=>Ln_,JsScriptStrategy:()=>Vn_,ProgrammingLanguage:()=>zn_,SearchbarPlacement:()=>Rn_,TabsPlacement:()=>Nn_,TwitterCardSetting:()=>Un_});var zn_={Typescript:"typescript",Javascript:"javascript",Python:"python",Java:"java",Go:"go",Ruby:"ruby",Csharp:"csharp",Nodets:"nodets",Nodejs:"nodejs",Dotnet:"dotnet",Curl:"curl",Jvm:"jvm",Ts:"ts",Js:"js"};var Rn_={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var Nn_={Header:"HEADER",Sidebar:"SIDEBAR"};var Fn_={Center:"CENTER",Left:"LEFT"};var Ln_={Fixed:"FIXED",Absolute:"ABSOLUTE"};var Un_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var Vn_={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var Wn_={Normal:"normal",Italic:"italic"};var Hn_={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var NKs={};Io(NKs,{read:()=>$n_,write:()=>Gn_});var $n_={};var Gn_={};var UKs={};Io(UKs,{ChangelogEntryType:()=>Jn_,GeneratorId:()=>WQD,GeneratorLanguage:()=>HQD,ReleaseType:()=>Kn_,cli:()=>Qn_,commons:()=>LKs,versions:()=>Yn_});var Qn_={};var LKs={};Io(LKs,{ChangelogEntryType:()=>Jn_,ReleaseType:()=>Kn_});var Jn_={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var Kn_={Ga:"GA",Rc:"RC"};var Yn_={};function WQD(e){return e}var HQD={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var VKs={};Io(VKs,{PullRequestState:()=>Xn_});var Xn_={Open:"open",Closed:"closed",Merged:"merged"};var $Ks={};Io($Ks,{latest:()=>WKs,v1:()=>HKs});var WKs={};Io(WKs,{NodeId:()=>QQD,ProductId:()=>JQD,Slug:()=>$QD,TabId:()=>GQD});function $QD(e){return e}function GQD(e){return e}function QQD(e){return e}function JQD(e){return e}var HKs={};Io(HKs,{NavigationV1Availability:()=>kQD,NodeId:()=>XQD,ProductId:()=>ZQD,Slug:()=>KQD,TabId:()=>YQD});function KQD(e){return e}function YQD(e){return e}function XQD(e){return e}function ZQD(e){return e}var kQD={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var QKs={};Io(QKs,{Language:()=>Zn_,VersionBump:()=>kn_,versions:()=>GKs});var GKs={};Io(GKs,{Language:()=>Zn_,VersionBump:()=>kn_});var Zn_={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var kn_={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var ea_={};var ta_={};var JKs={};Io(JKs,{PayloadLocation:()=>ra_});var ra_={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var ia_={};var P1n=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function xd(e){return e!=null}var aa_=vi(wkn(),1);var na_=["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 uXt(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,aa_.default)(e,{special:na_}).replace(/V\s(\d)/g,"V$1")}function zzo({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let u=[...n,a],l=I_.api.v1.SubpackageId(u.join("."));r[l]={id:l,name:a,displayName:uXt(a)},n.push(a)})}),r}var Rzo=class{errors=new P1n},j1n=class{input;context;constructor(t,r){this.input=t,this.context=r}errors(){return this.context.errors.errors}warnings(){return this.context.errors.warnings}};function oa_(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var Nzo=class extends Rzo{},Rp=class extends j1n{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){if(super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,n!=null){let a=Array.isArray(this.pathId)?this.pathId:[this.pathId];a.every((u,l)=>u===this.accessPath[this.accessPath.length-a.length+l])||this.accessPath.push(...a)}r.logger.debug(`Processing ${oa_(this.accessPath)}`)}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}},nF=class extends Rp{},yie=class extends nF{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var ua_="x-fern-base-path",sa_="x-fern-availability",Fzo="x-fern-sdk-group-name",ca_="x-fern-global-headers",la_="x-fern-sdk-method-name";var fa_="x-fern-webhook",da_="x-fern-access-token-locator",pa_="x-fern-basic",_a_="x-fern-username-variable-name",ha_="x-fern-password-variable-name",ya_="x-fern-bearer",va_="x-fern-token-variable-name",ba_="x-fern-header",ga_="x-fern-header-variable-name",Oa_="x-fern-server-name",ma_="x-fern-examples";var Lzo=class extends Rp{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[Oa_]}convert(){if(this.serverName!=null)return this.serverName}};var Uzo=class extends Rp{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,i])=>t.replace(`{${r}}`,i.default),this.input.url)??this.input.url,this.serverName=new Lzo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.serverName?.convert()??this.url;if(!(this.url==null||t==null))return{id:I_.EnvironmentId(t),baseUrl:this.url}}};function sXt(e,t,r,i){let n=e??[],a=new Set(n.map(l=>l.url)),u=(t??[]).filter(l=>!a.has(l.url)).map((l,d)=>new Uzo({input:l,context:r,accessPath:i,pathId:["servers",`${d}`]}));return[...n,...u]}function Y1(e){return typeof e=="object"&&xd(e)&&"$ref"in e&&typeof e.$ref=="string"}function sV(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(Y1(n)&&(n=sV(n,t,r)),n)}function Vzo(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return Y1(r)?sV(r,t,void 0):r}var Ba_=vi(ex());var Wzo=class extends Rp{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[pa_];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var Hzo=class extends Rp{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[ha_]}convert(){return this.passwordVariableName}};var $zo=class extends Rp{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[_a_]}convert(){return this.usernameVariableName}};var Gzo=class extends Rp{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[ya_];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var Qzo=class extends Rp{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[va_]}convert(){return this.tokenVariableName}};function Pa_(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var ja_="x-bearer-format",wa_="x-code-samples",Sa_="x-codeSamples";var Jzo=class extends Rp{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[ja_]}convert(){return this.bearerFormat}};var Kzo=class extends Rp{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[ba_];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var Yzo=class extends Rp{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[ga_]}convert(){return this.headerVariableName}};function Da_(e){return e.type==="apiKey"}var w1n=class extends Rp{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){Da_(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new Kzo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new Yzo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new Jzo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.headerAuthNode?.convert();if(t!=null)return{type:"header",nameOverride:t?.name,headerWireValue:this.headerName??"Authorization",prefix:t?.prefix??this.headerBearerFormatNode?.convert()}}};function Ea_(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function Ma_(e){return Object.is(e,-0)?"-0":e.toString()}function Aa_(e){let t=[],r=e.length;if(r===0)return t;let i=0,n="",a="",u=!1;for(e.charCodeAt(0)===46&&(t.push(""),i++);i<r;){let l=e[i];a?l==="\\"&&i+1<r?(i++,n+=e[i]):l===a?a="":n+=l:u?l==='"'||l==="'"?a=l:l==="]"?(u=!1,t.push(n),n=""):n+=l:l==="["?(u=!0,n&&(t.push(n),n="")):l==="."?n&&(t.push(n),n=""):n+=l,i++}return n&&t.push(n),t}function KKs(e,t,r){if(e==null)return r;switch(typeof t){case"string":{let i=e[t];return i===void 0?Ea_(t)?KKs(e,Aa_(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=Ma_(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return eJD(e,t,r);Object.is(t?.valueOf(),-0)?t="-0":t=String(t);let i=e[t];return i===void 0?r:i}}}function eJD(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null)return r;i=i[t[n]]}return i===void 0?r:i}function qa_(e){return function(t){return KKs(t,e)}}function Xzo(e,t){switch(t=t??qe_,typeof t){case"string":case"symbol":case"number":case"object":return f5(e,qa_(t));case"function":return f5(e,t)}}function YKs(e){if(e==null)return"";if(Array.isArray(e))return e.map(YKs).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function Ta_(e){return typeof e!="string"&&(e=YKs(e)),e.replace(/['\u2019]/g,"")}function b5t(e){return ae_(Ta_(e))}function mM(e){if(e!=null)return Array.isArray(e)?e:[e]}function Zzo({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,displayName:a,isWebhook:u}){if(t==null)return;let l=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(i==null&&n==null&&a==null&&l==null))return`${tJD(u)}${rJD(e)}.${iJD(i,n,a,l)}`}function tJD(e){return e?"webhook_":"endpoint_"}function rJD(e){return e!=null?mM(e)?.map(t=>b5t(t)).join("/"):""}function iJD(e,t,r,i){return e||t||b5t(r??"")||b5t(i??"")}function Ca_(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var kzo=class extends Rp{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[da_],this.accessTokenLocator!=null&&(Ca_(this.accessTokenLocator)||(this.context.errors.error({message:"Invalid access token locator, must be a valid jq path",path:this.accessPath}),this.accessTokenLocator=void 0))}convert(){return this.accessTokenLocator}};var eRo=class extends Rp{authorizationUrl;headerAuthNode;accessTokenLocatorNode;constructor(t){super(t),this.safeParse()}parse(){if(this.input.flows.clientCredentials!=null){let t=this.input.flows.clientCredentials;this.authorizationUrl=t.tokenUrl,this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.headerAuthNode=new w1n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new kzo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.accessTokenLocatorNode?.accessTokenLocator==null&&this.context.errors.error({message:"Expected 'x-fern-access-token-locator' property to be specified",path:this.accessPath})}}convert(){let t=this.accessTokenLocatorNode?.convert();if(t==null||this.authorizationUrl==null)return{type:"bearerAuth",tokenName:void 0};let r=Zzo({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,displayName:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:I_.EndpointId(r),accessTokenLocator:I_.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var S1n=class extends Rp{authScheme;headerAuthNode;bearerTokenNode;bearerTokenVariableNameNode;basicAuthNode;basicUsernameVariableNameNode;basicPasswordVariableNameNode;oauth2Node;constructor(t){super(t),this.safeParse()}parse(){switch(this.input.type){case"http":switch(this.input.scheme){case"basic":{this.authScheme="basic",this.basicAuthNode=new Wzo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new $zo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new Hzo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),(this.basicAuthNode==null||this.basicAuthNode.username==null&&this.basicUsernameVariableNameNode?.usernameVariableName==null||this.basicAuthNode.password==null&&this.basicPasswordVariableNameNode?.passwordVariableName==null)&&this.context.errors.warning({message:"Basic auth should specify either a username or a username variable name",path:this.accessPath});break}case"bearer":{this.authScheme="bearer",this.bearerTokenNode=new Gzo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new Qzo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}default:{this.context.errors.warning({message:`Unsupported HTTP auth scheme: ${this.input.scheme}`,path:this.accessPath});break}}break;case"apiKey":{Pa_(this.input)?(this.authScheme="header",this.headerAuthNode=new w1n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})):this.context.errors.error({message:`Unsupported API key location: ${this.input.in}`,path:this.accessPath});break}case"oauth2":{this.authScheme="oauth",this.oauth2Node=new eRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}case"openIdConnect":{this.authScheme="bearer";break}}}convert(){switch(this.authScheme){case"basic":{let t=this.basicAuthNode?.convert();return{type:"basicAuth",usernameName:t?.username?.name??this.basicUsernameVariableNameNode?.convert(),passwordName:t?.password?.name??this.basicPasswordVariableNameNode?.convert()}}case"bearer":return{type:"bearerAuth",tokenName:this.bearerTokenNode?.convert()?.tokenVariableName??this.bearerTokenVariableNameNode?.convert()};case"header":return this.headerAuthNode?.convert();case"oauth":return this.oauth2Node?.convert();case void 0:return;default:new Ba_.UnreachableCaseError(this.authScheme);return}}};var D1n=class extends Rp{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=Vzo(i,this.context.document);if(n==null){this.context.errors.warning({message:`No auth scheme found for ${i}. Inline security schemes are not supported.`,path:this.accessPath});return}let a=new S1n({input:n,context:this.context,accessPath:this.accessPath,pathId:["security",`${r}`]});a.convert()!=null?(this.authNodesMap??={},this.authNodesMap[i]=a):this.context.errors.warning({message:`No auth scheme found for ${i}`,path:this.accessPath})}))}convert(){return Object.fromEntries(Object.entries(this.authNodesMap??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[t,i]}).filter(xd))}};var tRo=class extends Rp{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[ua_],this.basePath!=null?(this.basePath.startsWith("/")&&(this.basePath=this.basePath.slice(1)),this.basePath.endsWith("/")&&(this.basePath=this.basePath.slice(0,-1))):this.basePath=void 0}convert(){return this.basePath}};function xa_(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function Ia_(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function E1n(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>mM(n.convert())?.map(u=>((t!=null&&!t.includes(i)||t==null&&!xa_(n))&&(u=Ia_(u,u.type==="enum"?u.default:void 0)),{key:I_.PropertyKey(i),valueShape:u,description:n.description,availability:n.availability?.convert()})).filter(xd)).filter(xd).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]])}function rRo(e,t){return Y1(e)?sV(e,t,void 0):e}function Kfi(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function za_(e,t){let r={...e};for(let[i,n]of Object.entries(t??{}))r[i]=[...r[i]??[],...n];return Object.keys(r).length>0?r:void 0}function Ra_(e,t){if(e==null)return t;if(t==null)return e;let r=[];for(let i of e)for(let n of t)r.push({path:i.path??n.path,responseStatusCode:i.responseStatusCode??n.responseStatusCode,name:i.name??n.name,description:i.description??n.description,pathParameters:i.pathParameters??n.pathParameters,queryParameters:i.queryParameters??n.queryParameters,headers:i.headers??n.headers,requestBody:i.requestBody??n.requestBody,responseBody:i.responseBody??n.responseBody,snippets:{...n.snippets,...i.snippets}});return r}var Na_=vi(ex());var XKs=["decimal","decimal128","double-int","double","float","sf-decimal"],ZKs=["int16","int32","int64","int8","sf-integer","uint8"],kKs=["base64url","binary","byte","char","commonmark","date-time","date","decimal","decimal128","duration","email","hostname","html","http-date","idn-email","idn-hostname","int64","ipv4","ipv6","iri-reference","iri","json-pointer","media-range","password","regex","relative-json-pointer","sf-binary","sf-boolean","sf-string","sf-token","time","uri-reference","uri-template","uri","uuid"],eYs=["beta","pre-release","in-development","generally-available","deprecated"];function aF(e,t){return Y1(e)?sV(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var nze=class extends Rp{availability;constructor(t){super(t),this.safeParse()}parse(){if(aF(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[sa_];r!=null&&(eYs.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${eYs.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return I_.Availability.Beta;case"in-development":return I_.Availability.InDevelopment;case"generally-available":return I_.Availability.GenerallyAvailable;case"deprecated":return I_.Availability.Deprecated;case void 0:return;default:new Na_.UnreachableCaseError(this.availability);return}}};var nRo=vi(ex());function Fa_(e){return typeof e=="object"&&e!=null&&"language"in e}function La_(e){return typeof e=="object"&&e!=null&&"sdk"in e}function Ua_(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function Va_(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function iRo(e){return typeof e=="object"&&e!=null&&"event"in e}function tYs(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(iRo)}function Yfi(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function Wa_(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var aRo=class extends Rp{path;successResponseStatusCode;requestBodyByContentType;responseBodies;examples;constructor(t,r,i,n,a){super(t),this.path=r,this.successResponseStatusCode=i,this.requestBodyByContentType=n,this.responseBodies=a,this.safeParse()}parse(){this.examples=this.input[ma_]}convertFormDataExampleRequest(t,r){if(t.fields!=null)switch(t.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(t.fields).map(([n,a])=>{let u=typeof r=="object"?r[n]:void 0;switch(a.multipartType){case"file":return Yfi(u)?[n,{type:"filenameWithData",filename:u.filename,data:I_.FileId(u.data)}]:u!=null?[n,{type:"filename",value:u}]:void 0;case"files":{if(Array.isArray(u)){if(u.every(l=>Yfi(l)))return[n,{type:"filenamesWithData",value:u.map(l=>({filename:l.filename,data:I_.FileId(l.data)}))}];if(u.every(l=>typeof l=="string"))return[n,{type:"filenames",value:u}]}return}case"property":return[n,{type:"json",value:u}];case void 0:return;default:new nRo.UnreachableCaseError(a.multipartType);return}}).filter(xd))};case"json":return{type:"json",value:r};case"bytes":return typeof r=="string"?{type:"bytes",value:{type:"base64",value:r}}:void 0;default:return}}convert(){if(this.examples==null)return;this.requestBodyByContentType!=null&&Object.keys(this.requestBodyByContentType).length>1&&this.context.logger.warn(`Multiple request bodies found for #/${[this.accessPath,this.pathId,"x-fern-examples"].join("/")}. Coercing to first request body until supported.`);let t=Object.keys(this.requestBodyByContentType??{})[0];return this.examples.flatMap(r=>(this.responseBodies??[]).map(i=>{let n=t!=null?this.requestBodyByContentType?.[t]:void 0,a;if(n!=null)switch(n.contentType){case"form-data":a=Wa_(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a=r.request!=null?{type:"json",value:r.request}:void 0;break;case"bytes":a=typeof r.request=="string"&&r.request!=null?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new nRo.UnreachableCaseError(n.contentType);break}let u;switch(i.contentType){case"application/json":{Ua_(r.response)&&(u={type:"json",value:r.response.body});break}case"text/event-stream":{tYs(r.response)&&(u={type:"sse",value:r.response.stream.map(c=>({event:c.event,data:c.data}))});break}case"application/octet-stream":!tYs(r.response)&&Va_(r.response)&&(u={type:"stream",value:r.response.stream});break;case void 0:break;default:new nRo.UnreachableCaseError(i.contentType);break}let l={};r["code-samples"]?.forEach(c=>{Fa_(c)?c.language!=null&&(l[c.language]??=[],l[c.language]?.push({name:c.name,language:c.language,install:c.install,code:c.code,generated:!1,description:c.docs})):La_(c)&&c.sdk!=null&&(l[c.sdk]??=[],l[c.sdk]?.push({name:c.name,language:c.sdk,install:void 0,code:c.code,generated:!1,description:c.docs}))});let d=Object.fromEntries(Object.entries(r["path-parameters"]??{}).map(([c,b])=>[I_.PropertyKey(c),b])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([c,b])=>[I_.PropertyKey(c),b])),o=Object.fromEntries(Object.entries(r.headers??{}).map(([c,b])=>[I_.PropertyKey(c),b]));return{path:this.path,responseStatusCode:this.successResponseStatusCode,name:r.name,description:r.docs,pathParameters:Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,headers:Object.keys(o).length>0?o:void 0,requestBody:a,responseBody:u,snippets:l}}))}};var G_a=class extends Rp{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[Fzo]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>I_.api.v1.SubpackageId(b5t(r)))}};var oRo=class extends Rp{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[la_]}convert(){return this.sdkMethodName}};var uRo=class extends Rp{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[fa_]}convert(){return this.isWebhook}};var sRo=class extends Rp{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[wa_]??[],...this.input[Sa_]??[]],this.codeSamples.forEach(t=>{[...Object.values(I_.api.v1.read.SupportedLanguage),"Kotlin","Swift","PHP"].map(r=>r.toLowerCase()).includes(t.lang.toLowerCase())||this.context.errors.warning({message:`Unsupported language: ${t.lang}. This may not render correctly.`,path:this.accessPath})})}convert(){let t={};if(this.codeSamples?.forEach(r=>{t[r.lang.toLowerCase()]??=[],t[r.lang.toLowerCase()]?.push({name:r.label,language:r.lang,code:r.source,install:void 0,generated:!1,description:void 0})}),Object.keys(t).length!==0)return t}};var Yzi=vi(ex());function rYs(e,t){return Y1(e)?sV(e,t,void 0):e}function Ha_(e,t){return e.replace(/{(\w+)}/g,(r,i)=>t[i]!=null&&typeof t[i]=="string"||typeof t[i]=="number"||typeof t[i]=="boolean"?`${t[i]}`:r)}var y5="",cXt=class extends Rp{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,i,n,a){super(t),this.path=r,this.responseStatusCode=i,this.name=n,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,i])=>{let n=this.resolvedRequestInput?.value[r];switch(i.multipartType){case"file":return t&&(Yfi(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>Yfi(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new Yzi.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=rYs(this.input?.requestExample,this.context.document)??(t!=null?{value:t}:void 0);let r=this.shapes.responseBody?.schema?.example({includeOptionals:!1,override:void 0});if(this.resolvedResponseInput=rYs(this.input?.responseExample,this.context.document)??(r!=null?{value:r}:void 0),this.summary=this.input?.requestExample?.summary??this.input?.responseExample?.summary,this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody?.contentType){case"json":{if(typeof this.resolvedRequestInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break}case"bytes":{if(typeof this.resolvedRequestInput.value!="string"){this.context.errors.error({message:"Invalid example, expected string for bytes",path:this.accessPath});return}break}case"form-data":{if(!this.validateFormDataRequestExample()){this.context.errors.error({message:"Invalid example, expected valid form-data",path:this.accessPath});return}break}case void 0:break;default:new Yzi.UnreachableCaseError(this.shapes.requestBody?.contentType),this.context.errors.error({message:"Invalid example, unsupported content type",path:this.accessPath});return}if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody?.contentType){case"application/json":if(this.resolvedResponseInput!=null&&typeof this.resolvedResponseInput!="object"||this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break;case"text/event-stream":if(this.resolvedResponseInput.value!=null&&!Array.isArray(this.resolvedResponseInput.value)&&!this.resolvedResponseInput.value.every(iRo)){this.context.errors.error({message:"Invalid example, expected array of SSE events for event-stream",path:this.accessPath});return}break;case"application/octet-stream":if(this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="string"&&!Array.isArray(this.resolvedResponseInput.value)){this.context.errors.error({message:"Invalid example, expected string or array for octet-stream",path:this.accessPath});return}break;case void 0:break;default:new Yzi.UnreachableCaseError(this.shapes.responseBody?.contentType);return}}convertFormDataExampleRequest(){if(!(this.resolvedRequestInput==null||this.shapes.requestBody?.fields==null))switch(this.shapes.requestBody?.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(this.shapes.requestBody.fields).map(([r,i])=>{let n=this.resolvedRequestInput?.value?.[r];switch(i.multipartType){case"file":return Yfi(n)?[r,{type:"filenameWithData",filename:n.filename,data:I_.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>Yfi(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:I_.FileId(a.data)}))}];if(n.every(a=>typeof a=="string"))return[r,{type:"filenames",value:n}]}return}case"property":return[r,{type:"json",value:n}];case void 0:return;default:new Yzi.UnreachableCaseError(i.multipartType);return}}).filter(xd))};case"json":return{type:"json",value:this.resolvedRequestInput.value};case"bytes":return typeof this.resolvedRequestInput.value=="string"?{type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}}:void 0;default:return}}convertDescription(){if(this.resolvedRequestInput!=null&&this.resolvedResponseInput!=null)return this.resolvedResponseInput.description;if(this.resolvedRequestInput!=null)return this.resolvedRequestInput.description;if(this.resolvedResponseInput!=null)return this.resolvedResponseInput.description}convert(){let t;if(this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody.contentType){case"form-data":t=this.convertFormDataExampleRequest();break;case"json":t={type:"json",value:this.resolvedRequestInput.value};break;case"bytes":t={type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}};break;case void 0:break;default:new Yzi.UnreachableCaseError(this.shapes.requestBody?.contentType);break}let r;if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody.contentType){case"application/json":{r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break}case"text/event-stream":r={type:"sse",value:this.resolvedResponseInput?.value};break;case"application/octet-stream":r={type:typeof this.resolvedResponseInput?.value=="string"?"filename":"stream",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;case void 0:r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;default:new Yzi.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([u,l])=>[u,l.example({includeOptionals:!1,override:u})]));i=Object.keys(i).length>0?i:void 0;let n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([u,l])=>l.required||l.inputExample!=null?[u,l.example({includeOptionals:!1,override:u})]:void 0).filter(xd));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([u,l])=>l.required||l.inputExample!=null?[u,l.example({includeOptionals:!1,override:u})]:void 0).filter(xd));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&n==null&&i==null))return{path:Ha_(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?uXt(this.name):this.summary!=null?uXt(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function $a_(e,t){return Y1(e)?sV(e,t,void 0):e}var no_=vi(ex());var Ga_="#/components/schemas/";function M1n(e){if(e.$ref.startsWith(Ga_))return e.$ref.replace(Ga_,"")}function UQr(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function Xfi(e){return typeof e.type=="string"&&e.type==="array"}function Qa_(e){return e.type==="boolean"}function Ja_(e){return e.type==="integer"}function Zfi(e){return!Array.isArray(e.type)&&!Xfi(e)}function Ka_(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||Zfi(t)||Xfi(t))}function Ya_(e){return"nullable"in e&&typeof e.nullable=="boolean"}function Xa_(e){return e.type==="null"}function Za_(e){return e.type==="number"}function iYs(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function ka_(e){return e.type==="string"}var cRo=class extends yie{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new FA({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items",seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return mM(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(t){return this.input.example??this.input.examples?.[0]??[this.item?.example(t)]}};var lRo=class extends nF{constValue;description;availability;constructor(t){super(t),this.safeParse()}parse(){this.input.const!=null&&(typeof this.input.const=="string"||typeof this.input.const=="number"||typeof this.input.const=="boolean")?this.constValue=this.input.const.toString():this.context.errors.warning({message:`Unsupported const type: ${typeof this.input}`,path:this.accessPath}),this.description=this.input.description,this.availability=new nze({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"})}convert(){if(this.constValue!=null)return{type:"enum",default:this.constValue,values:[{value:this.constValue,description:this.description,availability:this.availability?.convert()}]}}example(){return this.input.example??this.input.examples?.[0]??this.constValue}};var fRo=class extends yie{typeNodes;nullable;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new FA({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(xd)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>mM(n.convert())?.map(u=>({displayName:n.name,shape:u,description:n.description,availability:n.availability?.convert()}))).filter(xd).reduce((n,a)=>n.flatMap(u=>a.length>0?a.map(l=>[...u,l]):[[...u]]),[[]]).map(n=>({type:"undiscriminatedUnion",variants:n}));return this.nullable?i.map(UQr).filter(xd):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function dRo(e){return e!=null&&e.length>0?e:[void 0]}var A1n=class extends yie{description;extends=[];properties;extraProperties;requiredProperties;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new FA({input:r,context:this.context,accessPath:this.accessPath,pathId:["properties",t],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new FA({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:["additionalProperties"],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map((t,r)=>{if(Y1(t))return M1n(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new FA({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(xd))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return E1n(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:{type:"alias",value:{type:"unknown",displayName:this.extraProperties}}}]:mM(this.extraProperties.convert())?.map(r=>({type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:r})).filter(xd)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>dRo(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:n}:{type:"object",extends:this.extends.map(a=>I_.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=aF(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,u])=>[a,new FA({input:u,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))})}),this.input.example??this.input.examples?.[0]??(!t&&this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((i,n)=>{let a=r?.[n];return i[n]=a?.example({includeOptionals:t,override:n}),i},{}):Object.entries(r).reduce((i,[n,a])=>(i[n]=a?.example({includeOptionals:t,override:n}),i),{}))}};var pRo=class extends yie{isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>aF(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>aF(t,this.context.document)?.type!=="null"?new FA({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(xd);else{let t=this.input.discriminator.mapping;if(t!=null){this.discriminated=!0,this.discriminant=this.input.discriminator.propertyName,this.discriminatedMapping={};let r=this.discriminatedMapping;Object.entries(t).map(([i,n])=>{let a=aF({$ref:n},this.context.document);if(a==null){this.context.errors.warning({message:`Expected schema reference. Received undefined reference: ${n}`,path:[...this.accessPath,"discriminator","mapping",i]});return}r[i]=new FA({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let n=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(xd);return this.isNullable&&n!=null?n.map(UQr).filter(xd):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:I_.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>mM(a.convert())?.map(l=>{if(!(l==null||l.type!=="object"))return{discriminantValue:n,displayName:a.name??uXt(n),availability:a.availability?.convert(),description:a.description,...l}}).filter(xd)).filter(xd)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>mM(n.convert())?.map(u=>{if(u==null)return;t+=1;let l=u.type==="object"?uXt(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(u.type==="alias"&&u.value.type==="id"?uXt(u.value.id):l),shape:u,description:n.description,availability:n.availability?.convert()}}).filter(xd)).filter(xd)}:void 0,i=this.isNullable?UQr(r):r;return i!=null?[i]:void 0}example(t){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example(t)??Object.values(this.discriminatedMapping??{})[0]?.example(t)}};var _Ro=class extends nF{default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.input.default!=null&&typeof this.input.default!="boolean"&&this.context.errors.warning({message:`Expected default value to be a boolean. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default}convert(){return{type:"alias",value:{type:"primitive",value:{type:"boolean",default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:!1)}};var kfi=class extends nF{default;values=[];nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(Y1(r)){let n=aF(r,this.context.document);r=typeof n=="string"?n:typeof n?.default=="string"?n?.default:typeof n?.example=="string"?n.example:void 0}if(typeof r!="string"){this.context.errors.error({message:`Expected enum values to be strings. Received ${r}`,path:[...this.accessPath,`enum[${i}]`]}),t=!1;return}return r}}).filter(xd),this.values=Array.from(new Set(this.values))}this.default=this.input.default}convert(){return{type:"enum",values:this.values.map(t=>({value:t,description:void 0,availability:void 0})),default:this.default}}example(){return this.input.example??this.input.examples?.[0]??this.default??this.values[0]??(this.nullable?null:void 0)}};var eo_=vi(ex());function nJD(e){return ZKs.includes(e)}var hRo=class extends nF{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be an integer. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(nJD(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${ZKs.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="integer";if(this.format!=null)switch(this.format){case"int64":t="long";break;case"int8":case"int16":case"int32":case"uint8":case"sf-integer":case void 0:t="integer";break;default:new eo_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var yRo=class extends nF{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return UQr({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var to_=vi(ex());function aJD(e){return XKs.includes(e)}var vRo=class extends nF{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be a number. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(aJD(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${XKs.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="double";if(this.format!=null)switch(this.format){case"decimal":case"decimal128":case"double-int":case"double":case"float":case"sf-decimal":case void 0:t="double";break;default:new to_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var ro_=vi(ex());function oJD(e){return kKs.includes(e)}var bRo=class extends nF{format;regex;default;minLength;maxLength;enum;mimeType;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}mapToFdrType(t){switch(t){case"base64url":case"binary":case"byte":case"sf-binary":return"base64";case"date-time":return"datetime";case"int64":return"bigInteger";case"date":return"date";case"uuid":return"uuid";case"char":case"commonmark":case"decimal":case"decimal128":case"duration":case"email":case"hostname":case"html":case"http-date":case"idn-email":case"idn-hostname":case"ipv4":case"ipv6":case"iri-reference":case"iri":case"json-pointer":case"media-range":case"password":case"regex":case"relative-json-pointer":case"sf-boolean":case"sf-string":case"sf-token":case"time":case"uri-reference":case"uri-template":case"uri":case void 0:return"string";default:return new ro_.UnreachableCaseError(t),"string"}}parse(){this.regex=this.input.pattern,this.minLength=this.input.minLength,this.maxLength=this.input.maxLength,this.mimeType=this.input.contentMediaType,this.input.default!=null&&typeof this.input.default!="string"&&this.context.errors.warning({message:`Expected default value to be a string. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(oJD(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${kKs.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new kfi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum",nullable:this.nullable}))}convert(){if(this.enum!=null)return this.enum.convert();let t="string";return this.format!=null&&(t=this.mapToFdrType(this.format)),{type:"alias",value:{type:"primitive",value:t==="base64"?{type:t,mimeType:this.mimeType,default:this.default}:{type:t,format:t==="string"?this.format:void 0,regex:this.regex,minLength:this.minLength,maxLength:this.maxLength,default:this.default}}}}example({override:t}){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:t??"string")}};var io_=vi(ex());var gRo=class extends nF{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,io_.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var Xzi=class extends yie{description;availability;schemaId;maybeEnumConverterNode;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.description=t.description,this.availability=t.availability,this.safeParse()}parse(){this.schemaId=M1n(this.input);let t=aF(this.input,this.context.document);t?.enum!=null&&Zfi(t)&&(this.maybeEnumConverterNode=new kfi({input:t,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",nullable:this.nullable})),this.schemaId==null&&this.context.errors.error({message:`Unprocessable reference: ${this.input.$ref}`,path:this.accessPath})}convert(){if(this.schemaId!=null)return{type:"alias",value:{type:"id",id:I_.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=aF(this.input,this.context.document);if(r!=null)return new FA({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var FA=class e extends yie{typeShapeNode;description;name;examples;availability;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new nze({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),Zfi(this.input)&&Ya_(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),Y1(this.input)){let t=M1n(this.input);if(t==null){this.context.errors.error({message:"Reference object does not have a valid schema ID",path:this.accessPath});return}if(this.seenSchemas.has(t)){this.context.errors.warning({message:"Circular or deeply nested schema found, terminating",path:this.accessPath});return}this.seenSchemas.add(t),this.typeShapeNode=new Xzi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName,description:this.description,availability:this.availability})}else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new lRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(Ka_(this.input))this.typeShapeNode=new fRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(Zfi(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new pRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(iYs(this.input)&&this.input.allOf!=null)this.typeShapeNode=new A1n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(Zfi(this.input)&&this.input.enum!=null)this.typeShapeNode=new kfi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string"||Array.isArray(this.input.type)&&this.input.type.length===1){if(this.input.type=Array.isArray(this.input.type)?this.input.type[0]:this.input.type,!Array.isArray(this.input.type))switch(this.input.type){case"object":iYs(this.input)&&(this.typeShapeNode=new A1n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":Xfi(this.input)&&(this.typeShapeNode=new cRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":Qa_(this.input)&&(this.typeShapeNode=new _Ro({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":Ja_(this.input)&&(this.typeShapeNode=new hRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":Za_(this.input)&&(this.typeShapeNode=new vRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":ka_(this.input)&&(this.typeShapeNode=new bRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":Xa_(this.input)&&(this.typeShapeNode=new yRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new no_.UnreachableCaseError(this.input.type);break}}else if(Array.isArray(this.input.type)&&this.input.type.includes("null")&&this.input.type.length===2){let t=this.input.type.filter(r=>r!=="null")[0];t!=="array"&&(this.typeShapeNode=new e({input:{...this.input,type:t},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:!0,schemaName:this.schemaName}))}else this.input.properties!=null&&(this.typeShapeNode=new A1n({input:{...this.input,type:"object"},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));this.typeShapeNode==null&&(this.typeShapeNode=new gRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!Y1(this.input)&&(!Xfi(this.input)&&this.input==null||Xfi(this.input)&&this.input.items==null)&&this.context.errors.error({message:"Expected type declaration. Received: null",path:this.accessPath}))}convert(){let t=this.typeShapeNode?.convert();if(t==null)return;let r=mM(t)?.map(i=>this.nullable?UQr(i):i).filter(xd);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function edi(e){if(e!=null)return E1n(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(xd))}var lXt=class extends nF{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;Y1(this.input)?r=this.input:this.input.schema!=null?(r=this.input.schema,this.required=this.input.required):(r={type:"string"},this.required=!1),this.availability=new nze({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new FA({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=$a_(this.input,this.context.document);this.inputExample=i?.example??Object.values(i?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function ao_(e,t){return Y1(e)?sV(e,t,void 0):e}var nYs=vi(ex());function ORo(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[I_.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var oo_=vi(jus(),1),q1n=class e{type;subtype;essence;parameters;mimeType;input;constructor(t,r,i,n,a,u){this.type=t,this.subtype=r,this.essence=i,this.parameters=n,this.mimeType=a,this.input=u}static APPLICATION_JSON="application/json";static APPLICATION_OCTET_STREAM="application/octet-stream";static MULTIPART_FORM_DATA="multipart/form-data";static parse(t){if(t==null)return null;let r=oo_.default.parse(t);return r==null?null:new e(r.type,r.subtype,r.essence,r.parameters,r,t)}toString(){return this.input}isText(){return this.type==="text"}isImage(){return this.type==="image"}isAudio(){return this.type==="audio"}isVideo(){return this.type==="video"}isFont(){return this.type==="font"}isMultipart(){return this.type==="multipart"}isApplication(){return this.type==="application"}isMessage(){return this.type==="message"}isModel(){return this.type==="model"}isCSS(){return this.isText()&&this.subtype==="css"}isCSV(){return this.isText()&&this.subtype==="csv"}isMarkdown(){return this.isText()&&this.subtype==="markdown"}isPlainText(){return this.isText()&&this.subtype==="plain"}isEventStream(){return this.isText()&&this.subtype==="event-stream"}isMultiPartFormData(){return this.isMultipart()&&this.subtype==="form-data"}isJSON(){return this.isApplication()&&this.subtype==="json"}containsJSON(){return this.isApplication()&&this.subtype.includes("json")}isURLEncoded(){return this.isApplication()&&this.subtype==="x-www-form-urlencoded"}isOctetStream(){return this.isApplication()&&this.subtype==="octet-stream"}isPDF(){return this.isApplication()&&this.subtype==="pdf"}isZip(){return this.isApplication()&&this.subtype==="zip"}isGzip(){return this.isApplication()&&this.subtype==="gzip"}isTar(){return this.isApplication()&&this.subtype==="tar"}isBrotli(){return this.isApplication()&&this.subtype==="br"}isDeflate(){return this.isApplication()&&this.subtype==="deflate"}isProtobuf(){return this.isApplication()&&this.subtype==="protobuf"}isAvif(){return this.isImage()&&this.subtype==="avif"}isWebP(){return this.isImage()&&this.subtype==="webp"}isSVG(){return this.isImage()&&this.subtype==="svg+xml"}isPNG(){return this.isImage()&&this.subtype==="png"}isJPEG(){return this.isImage()&&this.subtype==="jpeg"}isGIF(){return this.isImage()&&this.subtype==="gif"}isMPEG(){return this.isAudio()&&this.subtype==="mpeg"}isWAV(){return this.isAudio()&&this.subtype==="wav"}isHTML(){return this.mimeType.isHTML()}isXML(){return this.mimeType.isXML()}isJavaScript(){return this.mimeType.isJavaScript()}};function uJD(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var T1n=class extends Rp{typeSchemas;securitySchemes;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas!=null&&(this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new FA({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),uJD(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(Y1(r)?n=Vzo(r.$ref,this.context.document):n=r,n!=null)return[t,new S1n({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(xd)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[I_.api.latest.AuthSchemeId(t),i]}).filter(xd)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=mM(r.convert());return n==null?[t,void 0]:[I_.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>xd(r))):void 0}}};var mRo=class extends FA{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=aF(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${Y1(this.input)?`Received undefined reference: ${this.input.$ref}`:""}`,path:this.accessPath});return}if(t.type==="string"&&t.format==="binary")this.multipartType="file",this.contentType=t.contentMediaType;else if(t.type==="array"){let r=aF(t.items,this.context.document);r?.type==="string"&&r?.format==="binary"?(this.multipartType="files",this.contentType=r?.contentMediaType):(this.context.errors.warning({message:"Expected multipart form data files definition with array type with internal string type and binary format.",path:this.accessPath}),this.multipartType=void 0,this.contentType=void 0)}else this.multipartType="property",this.contentType=t.contentMediaType}};var PRo=class extends Rp{description;method;path;schema;isOptional;contentType;availability;requiredFields;fields;examples;constructor(t){super(t),this.method=t.method,this.path=t.path,this.safeParse(t)}parse({contentType:t}){if(this.input.schema!=null){let i=aF(this.input.schema,this.context.document);this.availability=new nze({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=Y1(this.input.schema)?new Xzi({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:!1,schemaName:"Request Body",description:this.input.schema.description,availability:this.availability}):void 0;let n=q1n.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new FA({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):n?.isOctetStream()?(this.contentType="bytes",this.isOptional=i?.required==null):n?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=i?.required,this.fields=Object.fromEntries(Object.entries(i?.properties??{}).map(([a,u])=>{if(u!=null)return[a,new mRo({input:u,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(xd))):this.context.errors.warning({message:`Expected request body of reference or object with json, streaming or form-data content types. Received: ${t}`,path:this.accessPath})}let r=this.schema?.example({includeOptionals:!0,override:void 0});this.examples={...this.input.example!=null?{[y5]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[y5]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:mM(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=b5t([this.method,this.path,this.contentType,"request"].join("_"));return ORo({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:I_.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new nYs.UnreachableCaseError(n);return}}).filter(xd)}convert(){if(this.schema instanceof Xzi)return this.schema.convert();switch(this.contentType){case"json":return this.convertJsonLike();case"bytes":return{type:"bytes",isOptional:this.isOptional??!1,contentType:this.contentType};case"form-data":return Object.entries(this.fields??{}).map(([i,n])=>{switch(n.multipartType){case"file":return[{type:n.multipartType,key:I_.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"files":return[{type:n.multipartType,key:I_.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=mM(n.convert()),u=n.multipartType;return a?.map(l=>({type:u,key:I_.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:l,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new nYs.UnreachableCaseError(n.multipartType),[]}}).filter(xd).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]]).map(i=>({type:"formData",fields:i,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var jRo=class extends Rp{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=ao_(this.input,this.context.document);if(i==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(i.content).forEach(([n,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[n]=new PRo({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:n,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>mM(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(xd)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>mM(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(xd)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var uo_={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"};function so_(e,t){if(Y1(e)){let r=sV(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var wRo=vi(ex());var co_="application/json";var lo_="application/octet-stream";function fo_(e,t){return e===t||t===y5||e===y5}var Q_a=class extends Rp{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,u,l,d){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=u,this.requests=l,this.shapes=d,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,u]of Object.entries(n?.examples??{}))for(let[l,d]of Object.entries(r))for(let s of d)fo_(l,a)&&(i.add(l),this.examples?.push(new cXt({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,Kfi(a,l),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let i=0;for(let n of t){let a=0;for(let[u,l]of r){if(a===i){let[d,s,o]=n??[void 0,void 0,void 0];this.examples?.push(...l.map(c=>new cXt({input:{requestExample:o,responseExample:c},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,Kfi(s,u),{requestBody:d,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}i++}if(t.length>r.length)for(let n of t.slice(r.length)){let[a,u]=r[r.length-1]??[void 0,void 0],[l,d,s]=n??[void 0,void 0,void 0];this.examples?.push(...(u??[void 0]).map(o=>new cXt({input:{requestExample:s,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:d!=null&&d!==""?["examples",d]:"examples"},this.path,this.statusCode,Kfi(d,a),{requestBody:l,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[n,a,u]=t[t.length-1]??[void 0,void 0,void 0];for(let[l,d]of r.slice(t.length))this.examples?.push(...d.map(s=>new cXt({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,Kfi(a,l),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,i,n){let a=t[y5];if(a!=null)for(let u of a)this.examples?.push(new cXt({input:{requestExample:n,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,Kfi(i,void 0),{requestBody:r,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}))}addGlobalFallbackExample(t,r){if(t==null||t.length===0)this.pushResponseExample(r,void 0,void 0,void 0);else for(let i of t)if(Object.keys(i.examples??{}).length===0)this.pushResponseExample(r,i,void 0,void 0);else for(let[n,a]of Object.entries(i.examples??{}))this.pushResponseExample(r,i,n,a)}parse(t){if(t==="empty")this.empty=!0;else{let l=q1n.parse(t);if(l?.isJSON()||l?.isEventStream())this.contentType=co_,this.input.schema==null?(this.streamingFormat==null||this.streamingFormat==="json")&&this.context.errors.error({message:"Expected schema for JSON response body. Received null",path:this.accessPath}):this.schema=new FA({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type",seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"});else if(l?.isOctetStream())this.contentType=lo_,this.contentSubtype=aF(this.input.schema,this.context.document)?.contentMediaType;else if(this.unsupportedContentType=t,this.input.schema==null){this.context.errors.error({message:"Expected schema for plain text response body. Received null",path:this.accessPath});return}else this.schema=new FA({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"})}let r={};this.input.examples!=null&&(r=Xzo(this.input.examples,l=>[l])),this.input.example!=null&&Object.keys(r).length===0&&(r[y5]??=[],r[y5]=[{value:this.input.example}]);let i=aF(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=Xzo(i.examples,l=>[l])),i.example!=null&&Object.keys(r).length===0&&(r[y5]??=[],r[y5]?.push({value:i.example}))),Object.keys(r).length===0){let l=this.schema?.example({includeOptionals:!0,override:void 0});r[y5]??=[],r[y5]?.push(l!=null?{value:l}:void 0)}this.examples??=[];let n=new Set;this.matchRequestResponseExamplesByName(this.requests,r,n);let a=[];for(let l of this.requests)a.push(...Object.entries(l.examples??{}).filter(([d])=>!n.has(d)&&d!==y5).map(([d,s])=>[l,d,s]));let u=Object.entries(r).filter(([l,d])=>!n.has(l)&&xd(d)&&l!==y5);Object.keys(r).every(l=>l===y5)||this.matchExamplesByIndex(a,u),!n.has(y5)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return mM(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new wRo.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return mM(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=b5t([this.method,this.path,this.statusCode,"response"].join("_"));return ORo({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:I_.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new wRo.UnreachableCaseError(i);return}}).filter(xd)}convert(){if(this.empty)return{type:"empty"};if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?this.convertJsonLike():this.convertStreamingFormat();case"application/octet-stream":return{type:"fileDownload",contentType:this.contentSubtype};case"text/event-stream":return this.convertStreamingFormat();case void 0:return;default:new wRo.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var J_a=class extends Rp{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a,u){super(t),this.path=r,this.method=i,this.statusCode=n,this.requests=a,this.shapes=u,this.safeParse()}parse(t){this.description=this.input.description;let r=so_(this.input,this.context.document);if(r==null){this.context.errors.error({message:Y1(this.input)?`Undefined reference: ${this.input.$ref}`:"Expected response, received null",path:this.accessPath});return}Object.entries(r.headers??{}).forEach(([i,n])=>{this.headers??={},this.headers[i]=new lXt({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new Q_a({input:{},context:this.context,accessPath:this.accessPath,pathId:["content"]},"empty",t,this.path,this.method,this.statusCode,this.requests,this.shapes))):Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new Q_a({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(xd)}};var SRo=class extends Rp{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n,a){super(t),this.path=r,this.method=i,this.requests=n,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new J_a({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new J_a({input:i,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,parseInt(r),this.requests,this.shapes)))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return dRo(edi(r.headers)).flatMap(n=>i?.map(a=>({headers:n,response:{statusCode:parseInt(t),body:a,description:r.description},examples:(r.responses??[]).flatMap(u=>(u.examples??[]).map(l=>l.convert()).filter(xd))})))}).filter(xd)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=mM(n?.convert());if(n!=null)return a?.map(u=>({statusCode:parseInt(t),shape:u,description:r.description??n.description,availability:n.availability?.convert(),name:n.name??uo_[parseInt(t)]??"UNKNOWN ERROR",examples:i.examples?.map(l=>{let d=l.convert();if(d!=null&&d.responseBody?.type==="json")return{name:d.name,description:d.description,responseBody:d.responseBody}}).filter(xd)})).filter(xd)})).filter(xd)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var tdi=class extends Rp{servers;globalAuth;path;method;basePath;isWebhook;endpointIds;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespaces;xFernExamplesNode;redocExamplesNode;emptyResponseExamples;constructor(t){super(t),this.servers=t.servers,this.globalAuth=t.globalAuth,this.path=t.path,this.method=t.method,this.basePath=t.basePath,this.isWebhook=t.isWebhook,this.safeParse()}pushEmptyResponseExample(t,r,i){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new cXt({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,Kfi(i,void 0),{requestBody:r,pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}))}parse(){if(this.isWebhook&&this.method!=="POST"&&this.method!=="GET"){this.context.errors.error({message:`Webhook method must be POST or GET. Received: ${this.method}`,path:this.accessPath});return}this.description=this.input.description,this.displayName=this.input.summary,this.operationId=this.input.operationId,this.availability=new nze({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=sXt(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new uRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(Y1(i)){let a=rRo(i,this.context.document);if(a!=null)i=a;else{this.context.errors.warning({message:`Expected parameter reference to resolve to an object. Received undefined reference: ${i.$ref}`,path:[...this.accessPath,`parameters[${n}]`]});return}}i.in==="path"?i.schema!=null&&(this.pathParameters??={},this.pathParameters[i.name]=new lXt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new lXt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new lXt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new sRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new jRo({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody",method:this.method,path:this.path}):void 0,this.responses=this.input.responses!=null?new SRo({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0,this.responses==null){let i=this.requests?.requestBodiesByContentType;i==null||Object.keys(i).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(i).forEach(n=>{if(Object.keys(n.examples??{}).length===0){let a=n.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},n,void 0)}else Object.entries(n.examples??{}).forEach(([a,u])=>{this.pushEmptyResponseExample(u,n,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(i=>Number(i)>=200&&Number(i)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new D1n({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new G_a({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(i=>i.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((i,n)=>new G_a({input:{[Fzo]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new oRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>Zzo({namespace:mM(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(xd),this.xFernExamplesNode=new aRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-examples"},this.path,t,this.requests?.requestBodiesByContentType,this.responses?.responsesByStatusCode?.[t]?.responses)}extractPathParameterIds(){if(this.path!=null)return this.path.split("/").map(t=>{if(t.startsWith("{")&&t.endsWith("}"))return t.slice(1,-1).trim()}).filter(xd)}convertPathToPathParts(){if(this.path===void 0)return;let t=this.path.startsWith("/")?this.path.slice(1):this.path,r=this.basePath?.convert();return(r?[r,...t.split("/")]:t.split("/")).reduce((n,a)=>(n.push({type:"literal",value:"/"}),a.startsWith("{")&&a.endsWith("}")?n.push({type:"pathParameter",value:I_.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=this.emptyResponseExamples?.map(o=>o.convert()).filter(xd),n=Ra_(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(o=>o.examples)??[]])?.map(o=>({...o,snippets:za_(o.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((o,c)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:I_.WebhookId(o),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[c]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(b=>b.value.toString())??[],queryParameters:edi(this.queryParameters)?.flat(),headers:edi(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(xd)}}).filter(xd);let a=this.servers?.map(o=>o.convert()).filter(xd),u=this.convertPathToPathParts();if(u==null)return;let l,d=this.auth?.convert();d!=null&&(l=Object.keys(d));let s=t?.flatMap(o=>o.headers).filter(xd);return this.endpointIds.map((o,c)=>({id:I_.EndpointId(o),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[c]?.convert()?.map(b=>I_.api.v1.SubpackageId(b)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:u,auth:l?.map(b=>I_.api.latest.AuthSchemeId(b)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:edi(this.pathParameters)?.flat(),queryParameters:edi(this.queryParameters)?.flat(),requestHeaders:edi(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(b=>b.response),errors:r,examples:n,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var C1n=class extends Rp{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i,isWebhook:n}){this.description=this.input.description;let a=sXt(t,this.input.servers,this.context,this.accessPath),u=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new tdi({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:u,method:"GET",basePath:i,isWebhook:n})),this.input.post!=null&&(this.post=new tdi({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:u,method:"POST",basePath:i,isWebhook:n})),this.input.put!=null&&(this.put=new tdi({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:u,method:"PUT",basePath:i,isWebhook:!1})),this.input.patch!=null&&(this.patch=new tdi({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:u,method:"PATCH",basePath:i,isWebhook:!1})),this.input.delete!=null&&(this.delete=new tdi({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:u,method:"DELETE",basePath:i,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(xd)}};function DRo(e){return"payloads"in e}var ERo=class extends Rp{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.paths=Object.entries(this.input).map(([n,a])=>{if(a!=null)return new C1n({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:sXt(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(xd)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{DRo(a)?r[I_.WebhookId(a.id)]=a:t[I_.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var MRo=class extends Rp{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[ca_]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||rRo(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new lXt({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return E1n(this.globalHeaders,this.requiredProperties)?.flat()}};function do_(e,t){if(Y1(e)){let r=sV(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var ARo=class extends Rp{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.webhooks=Object.entries(this.input??{}).map(([n,a])=>{let u=do_(a,this.context.document);if(u!=null)return new C1n({input:u,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(xd)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{DRo(i)&&(t[I_.WebhookId(i.id)]=i)}),t),{})}};var qRo=class extends Rp{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=sXt(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new D1n({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new tRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});this.input.paths==null&&this.input.webhooks==null&&this.context.errors.warning({message:"Expected 'paths' or 'webhooks' property to be specified",path:this.accessPath}),this.input.paths!=null&&(this.paths=new ERo({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths",basePath:r,servers:t,globalAuth:this.auth})),this.input.webhooks!=null&&(this.webhooks=new ARo({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks",basePath:r,servers:t,globalAuth:this.auth})),this.input.components!=null&&(this.components=new T1n({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new MRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=zre(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=zzo({endpoints:i,webhookEndpoints:n}),{types:u,auths:l}=this.components?.convert()??{};return{id:I_.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:{...u,...this.context.generatedTypes},subpackages:a,auths:{...l,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};var B1n=class extends j1n{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,this.pathId&&this.pathId!==this.accessPath[this.accessPath.length-1]&&(this.accessPath.push(this.pathId),r.logger.debug(`Processing #/${this.accessPath.join("/")}`))}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}};function aze(e){return typeof e=="object"&&xd(e)&&"$ref"in e&&typeof e.$ref=="string"}function g5t(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(aze(n)&&(n=g5t(n,t,r)),n)}function po_(e,t){return aze(e)?g5t(e,t,{name:"",params:[],result:{name:"",schema:{type:"object"}}}):e}var vo_=vi(ex());function VQr(e){if(typeof e=="boolean")return e;if(e.enum!=null&&e.enum.length>0)return e.enum[0];if(e.const!=null)return e.const;if(e.examples!=null&&e.examples.length>0)return e.examples[0];if(e.type==="object"){let t={};if(e.properties!=null)for(let[r,i]of Object.entries(e.properties))t[r]=VQr(i);return t}if(e.type==="array")return e.items==null?[]:Array.isArray(e.items)?e.items.map(t=>VQr(t)):[VQr(e.items)];if(e.type==="string")return e.default??"string";if(e.type==="number"||e.type==="integer")return e.default??0;if(e.type==="boolean")return e.default??!1;if(e.type==="null")return null;if(e.oneOf?.[0]!=null)return VQr(e.oneOf[0]);if(e.anyOf?.[0]!=null)return VQr(e.anyOf[0]);if(e.allOf!=null&&e.allOf.length>0){let t={};for(let r of e.allOf)r!=null&&Object.assign(t,VQr(r));return t}}function K_a(e,t){return aze(e)?g5t(e,t,{name:"",schema:{type:"object"}}):e}function _o_(e,t){return aze(e)?g5t(e,t,void 0):e}function ho_(e,t){return aze(e)?g5t(e,t,void 0):e}function yo_(e,t){return aze(e)?g5t(e,t,void 0):e}var sJD={key:I_.PropertyKey("apiKey"),description:void 0,availability:void 0,valueShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}}},TRo=class extends B1n{method;servers=[];constructor(t,r){super(t),this.method=t.input,this.servers=r,this.safeParse()}parse(){}convert(){try{let t=this.method.result?K_a(this.method.result,this.context.openrpc):void 0,r=t?new FA({input:t.schema,context:this.context,accessPath:this.accessPath,pathId:"result",seenSchemas:new Set,nullable:void 0,schemaName:"Result"}).convert():void 0,n=this.method.params?.map(l=>K_a(l,this.context.openrpc)).filter(xd)?.map(l=>{let d=new FA({input:l.schema,context:this.context,accessPath:this.accessPath,pathId:["params",l.name],seenSchemas:new Set,nullable:void 0,schemaName:l.name}).convert();if(!d)return;let s=Array.isArray(d)?d[0]:d;if(s)return{key:I_.PropertyKey(l.name),valueShape:l.required?s:{type:"alias",value:{type:"optional",shape:s,default:void 0}},description:l.description,availability:void 0}}).filter(xd),a=n.length>0?{contentType:"application/json",body:{type:"object",extends:[],properties:n,extraProperties:void 0},description:void 0}:void 0,u=this.method.examples?.map(l=>{let d=ho_(l,this.context.openrpc);if(d)return{name:d.name??"Example",path:"",description:void 0,snippets:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:d.params.length>0?{type:"json",value:Object.fromEntries(d.params.map(s=>{let o=_o_(s,this.context.openrpc);if(o)return[o.name??"",o.value]}).filter(xd))}:void 0,responseStatusCode:200,responseBody:d.result?{type:"json",value:d.result}:void 0}}).filter(xd)??[];if(u.length<=0){let l=VQr({type:"object",properties:Object.fromEntries(this.method.params?.map(s=>{let o=K_a(s,this.context.openrpc);return[o?.name??"",o?.schema??{}]})??[])}),d={name:"Example",path:"",pathParameters:{},queryParameters:{},headers:{},requestBody:{type:"json",value:l},responseStatusCode:200,responseBody:{type:"json",value:VQr(K_a(this.method.result,this.context.openrpc)?.schema??{})},snippets:void 0,description:void 0};u.push(d)}return{protocol:{type:"openrpc",methodName:this.input.name},id:I_.EndpointId(this.input.name),displayName:this.input.name,method:"POST",path:[{type:"pathParameter",value:I_.PropertyKey("apiKey")}],auth:void 0,pathParameters:[sJD],queryParameters:[],requests:a!=null?[a]:void 0,responses:r!=null?[this.convertToHttpResponse(r,this.input.description)].filter(xd):[],errors:[],examples:u,description:this.input.description??this.input.summary,operationId:this.input.name,defaultEnvironment:void 0,environments:this.servers.map(l=>l.convert()).filter(xd),availability:this.method.deprecated?"Deprecated":void 0,requestHeaders:[],responseHeaders:[],snippetTemplates:void 0,namespace:this.getNamespace()}}catch{this.context.errors.error({message:"Failed to convert method",path:this.accessPath});return}}getNamespace(){if(this.method.tags?.[0]==null)return;let t=yo_(this.method.tags[0],this.context.openrpc);if(t?.name!=null)return[I_.api.v1.SubpackageId(t.name)]}convertToHttpResponse(t,r){if(t==null)return;let n=mM(t)?.map(a=>{let u=a.type;switch(u){case"alias":return a;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":return;case"object":return a;default:new vo_.UnreachableCaseError(u);return}}).filter(xd)[0];if(n)return{statusCode:200,body:n,description:r}}};var Y_a=class extends B1n{servers=[];methods=[];components;constructor(t){super(t),this.safeParse()}parse(){if(this.context.openrpc.servers!=null&&(this.servers=sXt(this.servers,this.input.servers,this.context,this.accessPath)),this.input.methods!=null)for(let t of this.input.methods){let r=po_(t,this.context.openrpc);r!=null&&this.methods.push(new TRo({input:r,context:this.context,accessPath:this.accessPath,pathId:"methods"},this.servers))}this.context.openrpc.components!=null&&(this.components=new T1n({input:this.context.openrpc.components,context:this.context,accessPath:this.accessPath,pathId:"components"}))}convert(){let t=zre(),{types:r}=this.components?.convert()??{},i=this.methods?.map(u=>u.convert()).filter(xd),n=Object.fromEntries(i?.map(u=>[u.id,u])??[]),a=zzo({endpoints:n});return{id:I_.ApiDefinitionId(t),types:r??{},endpoints:n,websockets:{},webhooks:{},subpackages:a,auths:{},globalHeaders:[],snippetsConfiguration:void 0}}};var X_a=class extends Nzo{openrpc;logger;generatedTypes;constructor(t){super(),this.openrpc=t.openrpc,this.logger=t.logger,this.generatedTypes={}}get document(){return{openapi:"3.1.0",info:{title:"Mock API",version:"1.0.0"},paths:{},components:this.openrpc.components}}};async function Z_a(e,t){if(e instanceof gfi){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof y7))return;let r=new e5t(e.absoluteFilePath),i=await $Ie({context:t,specs:e.specs}),n=await r.loadDocuments({context:t,specs:i}),a;for(let u of n){if(u.type!=="openapi")continue;let l={document:u.value,logger:t.logger,errors:new P1n,generatedTypes:{}},d=new qRo({input:u.value,context:l,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=Fus(a,d.convert())}return a}var bo_=require("fs/promises");async function go_(e,t){let r=await(0,bo_.readFile)(e,"utf-8"),i=JSON.parse(r),n=new X_a({openrpc:i,logger:t.logger});return new Y_a({input:i,context:n,accessPath:[],pathId:"openrpc"}).convert()}function Oo_(e){let t=new Set;return e.logo?.dark!=null&&t.add(e.logo.dark),e.logo?.light!=null&&t.add(e.logo.light),e.favicon!=null&&t.add(e.favicon),e.backgroundImage?.dark!=null&&t.add(e.backgroundImage.dark),e.backgroundImage?.light!=null&&t.add(e.backgroundImage.light),e.metadata?.["og:image"]!=null&&e.metadata["og:image"].type==="filepath"&&t.add(e.metadata["og:image"].value),e.metadata?.["og:logo"]!=null&&e.metadata["og:logo"].type==="filepath"&&t.add(e.metadata["og:logo"].value),e.metadata?.["twitter:image"]!=null&&e.metadata["twitter:image"].type==="filepath"&&t.add(e.metadata["twitter:image"].value),e.typography?.bodyFont!=null&&e.typography.bodyFont.variants.forEach(r=>{t.add(r.absolutePath)}),e.typography?.headingsFont!=null&&e.typography.headingsFont.variants.forEach(r=>{t.add(r.absolutePath)}),e.typography?.codeFont!=null&&e.typography.codeFont.variants.forEach(r=>{t.add(r.absolutePath)}),e.js!=null&&e.js.files.forEach(r=>{t.add(r.absolutePath)}),t}async function mo_({navigation:e,fernWorkspaces:t,visitor:r,context:i}){lJD(e)?await Promise.all(e.map(async n=>{n.layout!=null&&await Promise.all(n.layout.map(async a=>{await aYs({navigationItem:a,visitor:r,fernWorkspaces:t,context:i})}))})):await Promise.all(e.map(async n=>{await aYs({navigationItem:n,visitor:r,fernWorkspaces:t,context:i})}))}async function aYs({navigationItem:e,visitor:t,fernWorkspaces:r,context:i}){if(await RHt(e,{alphabetized:Qo,api:Qo,apiName:Qo,audiences:Qo,displayErrors:Qo,snippets:Qo,summary:Qo,title:Qo,layout:Qo,icon:Qo,slug:Qo,hidden:Qo,skipSlug:Qo,paginated:Qo,playground:Qo,flattened:Qo,path:Qo,page:Qo,featureFlag:Qo,openrpc:Qo,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await aYs({navigationItem:a,visitor:t,fernWorkspaces:r,context:i})}))},viewers:Qo,orphaned:Qo}),cJD(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function cJD(e){return e.api!=null}function lJD(e){return e[0]?.tab!=null}function DSe(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}Po_.default.extend(jo_.default);var fJD=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),CRo=0,dJD=async({ir:e})=>(CRo++,`${e.apiName.snakeCase.unsafeName}-${CRo}`),pJD=async({api:e})=>(CRo++,`${e.id}-${CRo}`),O5t=class{domain;docsWorkspace;ossWorkspaces;fernWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;registerApiV2;constructor(t,r,i,n,a,u,l=fJD,d=dJD,s=pJD){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.fernWorkspaces=n,this.taskContext=a,this.editThisPage=u,this.uploadFiles=l,this.registerApi=d,this.registerApiV2=s}#e=Bzo.init();_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;markdownFilesToNoIndex=new Map;async resolve(){this._parsedDocsConfig=await P_s({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig}),this.docsWorkspace.config.navigation!=null&&await mo_({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:s})=>{(await s.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1})).changelog?.files.forEach(c=>{let b=Qq(this.docsWorkspace.absoluteFilePath,c.absoluteFilepath);this.parsedDocsConfig.pages[b]=c.contents})}},fernWorkspaces:this.fernWorkspaces,context:this.taskContext}),this.markdownFilesToFullSlugs=await this.getMarkdownFilesToFullSlugs(this.parsedDocsConfig.pages),this.markdownFilesToNoIndex=await this.getMarkdownFilesToNoIndex(this.parsedDocsConfig.pages);for(let[s,o]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Xa.of(s)]=await W$s({markdown:o,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(s),context:this.taskContext});for(let[s,o]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Xa.of(s)]=await V$s({markdown:o,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(s),context:this.taskContext});let t=Oo_(this.parsedDocsConfig);for(let[s,o]of Object.entries(this.parsedDocsConfig.pages)){let{filepaths:c,markdown:b}=d_a(o,{absolutePathToMarkdownFile:this.resolveFilepath(s),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[Xa.of(s)]=b;for(let g of c)t.add(g)}let r=Array.from(t).map(s=>({absoluteFilePath:s,relativeFilePath:this.toRelativeFilepath(s)}));(await this.uploadFiles(r)).forEach(s=>{this.collectedFileIds.set(s.absoluteFilePath,s.fileId)});let n=this.getDocsBasePath(),a=await this.getMarkdownFilesToFullyQualifiedPathNames(n);for(let[s,o]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Xa.of(s)]=U$s(o,this.collectedFileIds,a,{absolutePathToMarkdownFile:this.resolveFilepath(s),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let u={};Object.entries(this.parsedDocsConfig.pages).forEach(([s,o])=>{let c=_JD(this.editThisPage,s);u[f5t.PageId(s)]={markdown:o,editThisPageUrl:c?f5t.Url(c):void 0}});let l=await this.convertDocsConfiguration(),d={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){let s=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async o=>{let c=OO(this.docsWorkspace.absoluteFilePath,o);(await(0,BRo.stat)(c)).isDirectory()?(await $Ce(c,"{js,ts,jsx,tsx,md,mdx}")).forEach(O=>{s.add(O)}):c.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&s.add(c)})),d=Object.fromEntries(await Promise.all([...s].map(async o=>{let c=this.toRelativeFilepath(o),b=(await(0,BRo.readFile)(o)).toString();return[c,b]})))}return{config:l,pages:u,jsFiles:d}}resolveFilepath(t){if(t!=null)return OO(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return Qq(this.docsWorkspace.absoluteFilePath,t)}async getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,oYs.default)(n).data.slug;typeof u=="string"&&u.trim().length>0&&r.set(this.resolveFilepath(i),u.trim())}return r}async getMarkdownFilesToNoIndex(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,oYs.default)(n).data.noindex;typeof u=="boolean"&&r.set(this.resolveFilepath(i),u)}return r}async getMarkdownFilesToFullyQualifiedPathNames(t){let r={},i=zo.migrate.FernNavigationV1ToLatest.create().root(await this.toRootNode());return zo.NodeCollector.collect(i).slugMap.forEach((a,u)=>{if(a==null||!zo.isPage(a))return;let l=zo.getPageId(a);if(l==null)return;let d=Xu(this.docsWorkspace.absoluteFilePath,Xa.of(l));r[d]=Cv(t,u)}),r}getDocsBasePath(){return new URL(DSe(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.toRootNode();return{hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?f5t.Url(this.parsedDocsConfig.logo?.href):void 0,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:void 0,root:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(i=>({...i,url:f5t.Url(i.url)})),typographyV2:this.convertDocsTypographyConfiguration(),layout:this.parsedDocsConfig.layout,css:this.parsedDocsConfig.css,js:this.convertJavascriptConfiguration(),metadata:this.convertMetadata(),redirects:this.parsedDocsConfig.redirects,integrations:this.parsedDocsConfig.integrations,footerLinks:this.parsedDocsConfig.footerLinks?.map(i=>({...i,value:f5t.Url(i.value)})),defaultLanguage:this.parsedDocsConfig.defaultLanguage,analyticsConfig:{...this.parsedDocsConfig.analyticsConfig,segment:this.parsedDocsConfig.analyticsConfig?.segment,fullstory:this.parsedDocsConfig.analyticsConfig?.fullstory,intercom:this.parsedDocsConfig.analyticsConfig?.intercom?{appId:this.parsedDocsConfig.analyticsConfig.intercom.appId,apiBase:this.parsedDocsConfig.analyticsConfig.intercom.apiBase}:void 0,posthog:this.parsedDocsConfig.analyticsConfig?.posthog?{apiKey:this.parsedDocsConfig.analyticsConfig.posthog.apiKey,endpoint:this.parsedDocsConfig.analyticsConfig.posthog.endpoint}:void 0,gtm:this.parsedDocsConfig.analyticsConfig?.gtm?{containerId:this.parsedDocsConfig.analyticsConfig.gtm.containerId}:void 0,ga4:this.parsedDocsConfig.analyticsConfig?.ga4?{measurementId:this.parsedDocsConfig.analyticsConfig.ga4.measurementId}:void 0,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},announcement:this.parsedDocsConfig.announcement!=null?{text:this.parsedDocsConfig.announcement.message}:void 0,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0}}getFernWorkspaceForApiSection(t){if(this.fernWorkspaces.length===1&&this.fernWorkspaces[0]!=null)return this.fernWorkspaces[0];if(t.apiName!=null){let r=this.fernWorkspaces.find(i=>i.workspaceName===t.apiName);if(r!=null)return r}throw new Error("Failed to load API Definition referenced in docs")}getOpenApiWorkspaceForApiSection(t){if(this.ossWorkspaces.length===1&&this.ossWorkspaces[0]!=null)return this.ossWorkspaces[0];if(t.apiName!=null){let r=this.ossWorkspaces.find(i=>i.workspaceName===t.apiName);if(r!=null)return r}throw new Error("Failed to load API Definition referenced in docs")}async toRootNode(){let t=zo.V1.SlugGenerator.init(zo.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),i=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:i,slug:t.get(),title:this.parsedDocsConfig.title??"Documentation",hidden:!1,icon:void 0,pointsTo:void 0,authed:void 0,viewers:void 0,orphaned:void 0,roles:this.parsedDocsConfig.roles?.map(n=>zo.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return Rfn(this.parsedDocsConfig.navigation)._visit({untabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),tabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),versioned:r=>this.toVersionedNode(r,t)})}toLandingPageNode(t,r){let i=zo.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??Oq(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:i}){let n=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,i):void 0,u=r.type==="tabbed"?await this.convertTabbedNavigation(n,r.items,i):await this.toSidebarRootNode(n,r.items,i);return{type:"unversioned",id:n,landingPage:a,child:u}}async toVersionedNode(t,r){return{id:this.#e.get("versioned"),type:"versioned",children:await Promise.all(t.versions.map((n,a)=>this.toVersionNode(n,r,a===0)))}}async toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??Oq(t.version)),u=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(n,t.navigation.items,a):await this.toSidebarRootNode(n,t.navigation.items,a);return{type:"version",id:n,versionId:zo.VersionId(t.version),title:t.version,slug:a.get(),child:u,default:i,availability:t.availability!=null?hJD(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,r):void 0,hidden:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),a=await Promise.all(r.map(l=>this.toNavigationChild(n,l,i))),u=[];return a.forEach(l=>{if(l.type==="apiReference"){u.push(l);return}if(l.type==="section"&&!l.collapsed){u.push(l);return}let d=u.length>0?u[u.length-1]:void 0,s;d?.type==="sidebarGroup"?s=d:(s={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},u.push(s)),s.children.push(l)}),{type:"sidebarRoot",id:n,children:u}}async toNavigationChild(t,r,i){return Rfn(r)._visit({page:async n=>this.toPageNode(n,i),apiSection:async n=>this.toApiSectionNode(n,i),section:async n=>this.toSectionNode(t,n,i),link:async n=>this.toLinkNode(n),changelog:async n=>this.toChangelogNode(n,i)})}async toApiSectionNode(t,r){if(t.openrpc!=null){let s=OO(this.docsWorkspace.absoluteFilePath,Xa.of(t.openrpc));if(!await Cf(s))throw new Error(`OpenRPC file does not exist at path: ${s}`);let o=await go_(s,this.taskContext);if(o==null)throw new Error("Failed to generate API Definition from OpenRPC document");return await this.registerApiV2({api:o,apiName:t.apiName,snippetsConfig:xzo(t.snippetsConfiguration)}),new H_a(t,o,r,void 0,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e).get()}if(this.parsedDocsConfig.experimental?.openapiParserV2){let s=this.getOpenApiWorkspaceForApiSection(t),o=xzo(t.snippetsConfiguration),c=await Z_a(s,this.taskContext);if(c==null)throw new Error("Failed to generate API Definition from OpenAPI workspace");return await this.registerApiV2({api:c,snippetsConfig:o,apiName:t.apiName}),new H_a(t,c,r,s,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e).get()}let i=xzo(t.snippetsConfiguration),n,a;this.parsedDocsConfig.experimental?.openapiParserV3?n=await this.getOpenApiWorkspaceForApiSection(t).getIntermediateRepresentation({context:this.taskContext}):(a=this.getFernWorkspaceForApiSection(t),n=_2({workspace:a,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1,skipAutogenerationIfManualExamplesExist:!0},readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new d2(this.taskContext,a)}));let u=await this.registerApi({ir:n,snippetsConfig:i,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName}),l=$_a(n,u,{oauth:t.playground?.oauth});return new Tzo(t,l,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,a).get()}async toChangelogNode(t,r){return new LQr(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:zo.V1.Url(t.url),icon:t.icon}}async toPageNode(t,r){let i=zo.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??Oq(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(i),type:"page",slug:n.get(),title:t.title,icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toSectionNode(t,r,i){let n=this.toRelativeFilepath(r.overviewAbsolutePath),a=n?zo.PageId(n):void 0,u=this.#e.get(a??`${t}/section`),l=i.apply({urlSlug:r.slug??Oq(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),d=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0;return{id:u,type:"section",overviewPageId:a,slug:l.get(),title:r.title,icon:r.icon,collapsed:r.collapsed,hidden:r.hidden,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(s=>this.toNavigationChild(u,s,l))),authed:void 0,pointsTo:void 0,noindex:d,featureFlags:r.featureFlags}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return Rfn(r.child)._visit({link:({href:n})=>this.toTabLinkNode(r,n),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i)})}async toTabChangelogNode(t,r,i){return new LQr(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r){return{type:"link",id:this.#e.get(r),title:t.title,url:zo.V1.Url(r),icon:t.icon}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),u=n.apply({urlSlug:r.slug??Oq(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:u.get(),icon:r.icon,hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,i,u),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):f5t.FileId(r)}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(u0),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:f5t.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return Rfn(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:f5t.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function _JD(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${DSe(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function hJD(e){switch(e){case"beta":return zo.V1.NavigationV1Availability.Beta;case"deprecated":return zo.V1.NavigationV1Availability.Deprecated;case"ga":return zo.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return zo.V1.NavigationV1Availability.Stable;default:Ko(e)}}async function vie(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof y7?t:null))).filter(u0)}var rXs=vi(Oos(),1),Ol_=vi(aNo(),1),_Xt=require("fs/promises"),PNo=require("os"),ml_=vi(fte(),1),Pl_=vi(gl_(),1);var oXD="etag",iXs="preview",uXD="bundle",nXs=".fern";function sXD(){return Xu(Wl.of((0,PNo.homedir)()),Xa.of(nXs),Xa.of(iXs))}function jNo(){return Xu(Wl.of((0,PNo.homedir)()),Xa.of(nXs),Xa.of(iXs),Xa.of(uXD))}function cXD(){return Xu(Wl.of((0,PNo.homedir)()),Xa.of(nXs),Xa.of(iXs),Xa.of(oXD))}async function jl_({bucketUrl:e,logger:t,preferCached:r}){t.debug("Setting up docs preview bundle...");let i=await(0,rXs.fetcher)({url:e,method:"GET",responseType:"text",duplex:"half"});if(!i.ok)return{type:"failure"};let n=i.body,u=await new Pl_.default.Parser().parseStringPromise(n),l=u?.ListBucketResult?.Contents?.[0]?.ETag?.[0],d=u?.ListBucketResult?.Contents?.[0]?.Key?.[0],s=cXD();if(r){let q=await Cf(s),D;if(q&&(t.debug("Reading existing ETag"),D=(await(0,_Xt.readFile)(s)).toString()),D!=null&&D===l)return t.debug("ETag matches. Using already downloaded bundle"),{type:"success"};t.debug("ETag is different. Downloading latest preview bundle")}t.debug("Creating tmp directory to download docs preview bundle");let o=await ml_.default.dir({prefix:"fern"}),c=Wl.of(o.path),b=new URL(d,e).href;t.debug(`Downloading docs preview bundle from ${b}`);let g=await(0,rXs.fetcher)({url:b,method:"GET",responseType:"arrayBuffer",duplex:"half"});if(!g.ok){let q;return g.error.reason==="status-code"?q=`Failed to download docs preview bundle. Status code: ${g.error.statusCode}`:g.error.reason==="unknown"?q=`Failed to download docs preview bundle. Error: ${g.error.errorMessage}`:q=`Failed to download docs preview bundle. Error: ${g.error.reason}`,t.error(q),{type:"failure"}}let O=Xu(c,Xa.of("output.zip")),m=g.body;if(m==null)return{type:"failure"};let w=Buffer.from(m);await(0,_Xt.writeFile)(O,new Uint8Array(w)),t.debug(`Wrote output.zip to ${O}`);let E=sXD();await Cf(E)&&await(0,_Xt.rm)(E,{recursive:!0}),await(0,_Xt.mkdir)(E,{recursive:!0}),t.debug(`rm -rf ${E}`);let A=jNo();return await(0,_Xt.mkdir)(A,{recursive:!0}),await(0,Ol_.default)(O,A),await(0,_Xt.writeFile)(s,l),t.debug(`Downloaded bundle to ${A}`),{type:"success"}}var Rl_=require("fs/promises");var sXs=vi(u8t(),1),ql_=require("path");var G1n=vi(zte(),1);function wNo(e){if(e==null)return;let t=[],r=!1;if(XYt(e,{enter(i){(i.type==="FunctionDeclaration"||i.type==="ArrowFunctionExpression"||i.type==="JSXOpeningElement"||i.type==="JSXOpeningFragment"||i.type==="Identifier")&&(r=!0,this.skip()),i.type==="Literal"&&t.push(i.value)}}),!r)return t.length===1?t[0]:void 0}function aXs(e){if(typeof e=="string")return e;if(e?.type==="mdxJsxAttributeValueExpression")return wNo(e.data?.estree)}function wl_(e){return e.type==="mdxJsxFlowElement"||e.type==="mdxJsxTextElement"}function Sl_(e){return e.type==="mdxFlowExpression"||e.type==="mdxTextExpression"}function oXs(e){return e.type==="mdxJsxAttribute"}function Dl_(e){return e.type==="mdxJsxExpressionAttribute"}var El_=vi(u8t(),1);function Ml_(e){let{content:t}=(0,El_.default)(e);return s_a(t,{extensions:[Mmn(),gmn(),l_a()],mdastExtensions:[Exi(),Pxi(),c_a()]})}function Al_(e,t){XYt(e,{enter(r){r.type==="JSXElement"&&r.openingElement.attributes.forEach(i=>{i.type==="JSXAttribute"&&i.name.type==="JSXIdentifier"&&t[i.name.name]&&t[i.name.name]?.(i,r)})}})}function Tl_(e,{absolutePathToFernFolder:t,absolutePathToMarkdownFile:r}){return e==null||Cl_(e)||Bl_(e)?void 0:OO(e.startsWith("/")?t:fp(r),Xa.of(e.replace(/^\//,"")))}function Cl_(e){return/^(https?:)?\/\//.test(e)}function Bl_(e){return e.startsWith("data:")}function xl_({href:e,metadata:t,markdownFilesToPathName:r}){if(e!=null&&(e.endsWith(".md")||e.endsWith(".mdx"))){let i=Tl_(e,t);if(i!=null){let n=r[i];return n!=null?{type:"replace",slug:n,href:e}:{type:"missing-reference",path:i,href:e}}}}function cXs(e,t,r,i,n){let{content:a,data:u}=(0,sXs.default)(e,{}),l=a,d=Ml_(a),s=0;function o(c){if(c==null||Cl_(c)||Bl_(c))return;if((0,ql_.isAbsolute)(c)){let g=Wl.of(c),O=t.get(g);return O?`file:${O}`:void 0}let b=Tl_(c,i);if(b){let g=t.get(b);return g?`file:${g}`:void 0}}return fXD(u,["image","og:image","og:logo","twitter:image"],o),pXD(u,o),Rf(d,c=>{if(c.position==null)return;let{start:b,length:g}=lXD(a,c.position),O=l.slice(b+s,b+s+g),m=O;function w(q){let D=o(q);q&&D&&(m=m.replace(q,D))}function E(q){let D=xl_({href:q,markdownFilesToPathName:r,metadata:i});q!=null&&D!=null&&D.type==="replace"&&(m=m.replace(q,D.slug))}function A(q){Al_(q,{src:D=>w(udi(wNo(D.value))),href:D=>E(udi(wNo(D.value)))})}if(c.type==="image"){let q=udi(c.url);w(udi(q))}if(c.type==="link"&&E(udi(c.url)),wl_(c)){let q=c.attributes.filter(oXs).find(C=>C.name==="src");w(udi(aXs(q?.value)));let D=c.attributes.find(C=>C.type==="mdxJsxAttribute"&&C.name==="href");E(udi(aXs(D?.value))),c.attributes.forEach(C=>{oXs(C)&&typeof C.value!="string"&&C.value!=null&&C.value.data?.estree?A(C.value.data.estree):Dl_(C)&&C.data?.estree&&A(C.data.estree)})}if(Sl_(c)&&c.data?.estree&&A(c.data.estree),m!==O)return l=l.slice(0,b+s)+m+l.slice(b+s+g),s+=m.length-g,Pp}),sXs.default.stringify(l,u)}function lXD(e,t){let r=e.split(`
|
|
1971
|
+
${JSON.stringify(r)}"`)}}function Jr_(e,t,r,i){let n=r.resolveSourceOrThrow({source:t,relativeFilepath:e.relativeFilepath});if(n==null||n.type!=="protobuf")throw new Error(`Expected a protobuf source for ${t.proto}.`);let a=$r_({source:n,serviceNameOverride:i});if(a==null)throw new Error(`Failed to resolve service name from ${n.relativeFilePath}.`);return mBe.grpc({service:a})}function Kr_({rootDefaultUrl:e,rootPathParameters:t,serviceDefinition:r,file:i,errorResolver:n,typeResolver:a,propertyResolver:u,exampleResolver:l,variableResolver:d,sourceResolver:s,globalErrors:o,workspace:c}){let b=v1n({pathParameters:r["path-parameters"],location:PBe.Service,file:i,variableResolver:d}),g=Gr_({file:i,serviceDeclaration:r,sourceResolver:s}),O={fernFilepath:i.fernFilepath};return{availability:hie(r.availability),name:O,displayName:r["display-name"]??void 0,basePath:iV(r["base-path"]),headers:r.headers!=null?Object.entries(r.headers).map(([w,E])=>rze({headerKey:w,header:E,file:i})):[],pathParameters:b,encoding:CGD(g,r),transport:g,endpoints:Object.entries(r.endpoints).map(([w,E])=>{let A=v1n({pathParameters:_5t(E),location:PBe.Endpoint,file:i,variableResolver:d}),q={...uG(E),id:"",name:i.casingsGenerator.generateName(w),displayName:E["display-name"],auth:E.auth??r.auth,idempotent:E.idempotent??r.idempotent??!1,baseUrl:E.url??r.url??e,method:E.method!=null?TGD(E.method):W3.Post,basePath:E["base-path"]!=null?iV(E["base-path"]):void 0,path:iV(E.path),fullPath:iV(E["base-path"]!=null?Cv(E["base-path"],E.path):i.rootApiFile["base-path"]!=null?Cv(i.rootApiFile["base-path"],r["base-path"],E.path):Cv(r["base-path"],E.path)),pathParameters:A,allPathParameters:E["base-path"]!=null?A:[...t,...b,...A],queryParameters:typeof E.request!="string"&&E.request?.["query-parameters"]!=null?Object.entries(E.request["query-parameters"]).map(([D,C])=>hzo({file:i,queryParameterKey:D,queryParameter:C})):[],headers:typeof E.request!="string"&&E.request?.headers!=null?Object.entries(E.request.headers).map(([D,C])=>rze({headerKey:D,header:C,file:i})):[],requestBody:ur_({request:E.request,file:i}),sdkRequest:dr_({service:r,request:E.request,endpoint:E,endpointKey:w,file:i,typeResolver:a,propertyResolver:u}),response:Nr_({endpoint:E,file:i,typeResolver:a}),errors:[...Hr_({errors:E.errors,file:i}),...o],userSpecifiedExamples:E.examples!=null?E.examples.map(D=>({example:Rr_({service:r,endpoint:E,example:D,typeResolver:a,errorResolver:n,exampleResolver:l,variableResolver:d,file:i,workspace:c}),codeSamples:D["code-samples"]?.map(C=>pr_({codeSample:C,file:i}))})):[],autogeneratedExamples:[],pagination:Wr_({propertyResolver:u,file:i,endpointName:w,endpointSchema:E}),transport:Qr_({file:i,serviceTransport:g,endpointDeclaration:E,sourceResolver:s})};return q.id=Ng.generateEndpointId(O,q),q})}}function v1n({pathParameters:e,location:t,file:r,variableResolver:i}){return e==null?[]:Object.entries(e).map(([n,a])=>AGD({parameterName:n,parameter:a,location:t,file:r,variableResolver:i}))}function AGD({parameterName:e,parameter:t,location:r,file:i,variableResolver:n}){return{...uG(t),name:i.casingsGenerator.generateName(e),valueType:qGD({parameter:t,variableResolver:n,file:i}),location:r,variable:Ehn(t)?n.getVariableIdOrThrow(typeof t=="string"?t:t.variable):void 0}}function qGD({parameter:e,variableResolver:t,file:r}){let i=F_a({parameter:e,variableResolver:t,file:r});return i.file.parseTypeReference(i.rawType)}function F_a({parameter:e,variableResolver:t,file:r}){let i=vzo({parameter:e,variableResolver:t,file:r});if(i==null)throw new Error("Cannot resolve path parameter");return i}function vzo({parameter:e,variableResolver:t,file:r}){if(Ehn(e)){let i=typeof e=="string"?e:e.variable,n=t.getDeclaration(i,r);return n==null?void 0:{rawType:typeof n.declaration=="string"?n.declaration:n.declaration.type,file:n.file}}else return{file:r,rawType:typeof e=="string"?e:e.type}}function TGD(e){switch(e){case"GET":return W3.Get;case"POST":return W3.Post;case"PUT":return W3.Put;case"PATCH":return W3.Patch;case"DELETE":return W3.Delete;default:Ko(e)}}function rze({headerKey:e,header:t,file:r}){let{name:i}=nXt({headerKey:e,header:t});return{...uG(t),name:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:i}),valueType:r.parseTypeReference(t),env:typeof t=="string"?void 0:t.env}}function nXt({headerKey:e,header:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function CGD(e,t){switch(e.type){case"http":return{json:{},proto:void 0};case"grpc":return{json:void 0,proto:{}};default:Ko(e)}}var Yr_="1.0.0";var bzo=class{ir;auth;authValues;constructor(t){this.ir=t,this.auth=this.convertAuth(t.auth),this.authValues=this.getAuthValues(t.auth)}convert({includeExamples:t}){return{version:Yr_,types:this.convertNamedTypes(),headers:this.convertHeaders(),endpoints:this.convertEndpoints({includeExamples:t}),environments:this.ir.environments}}convertNamedTypes(){return Object.fromEntries(Object.entries(this.ir.types).map(([t,r])=>[t,this.convertTypeDeclaration(r)]))}convertHeaders(){return this.convertWireValueParameters({wireValueParameters:this.ir.headers})}convertEndpoints({includeExamples:t}){let r=this.getAllHttpEndpoints();return Object.fromEntries(r.map(i=>[i.id,this.convertEndpoint({endpoint:i,includeExamples:t})]))}convertEndpoint({endpoint:t,includeExamples:r}){let i=this.convertEndpointLocation({endpoint:t});return{auth:this.auth,declaration:this.convertDeclaration({name:t.name,fernFilepath:t.fernFilepath}),location:i,request:this.convertRequest({endpoint:t}),response:Ic.Response.json(),examples:r?this.getEndpointSnippetRequests({endpoint:t,location:i}):void 0}}convertRequest({endpoint:t}){let r=this.convertPathParameters({pathParameters:t.allPathParameters});if(t.sdkRequest==null&&t.requestBody==null)return Ic.Request.body({pathParameters:r,body:void 0});if(t.sdkRequest==null)throw new Error(`Internal error; endpoint "${t.id}" has a request body but no SDK request`);switch(t.sdkRequest.shape.type){case"justRequestBody":return Ic.Request.body({pathParameters:r,body:this.convertReferencedRequestBodyType({body:t.sdkRequest.shape.value})});case"wrapper":return this.convertInlinedRequest({fernFilepath:t.fernFilepath,wrapper:t.sdkRequest.shape,pathParameters:r,queryParameters:this.convertQueryParameters({queryParameters:t.queryParameters}),headers:this.convertWireValueParameters({wireValueParameters:[...t.serviceHeaders,...t.headers]}),body:t.requestBody});default:Ko(t.sdkRequest.shape)}}convertReferencedRequestBodyType({body:t}){switch(t.type){case"bytes":return Ic.ReferencedRequestBodyType.bytes();case"typeReference":return Ic.ReferencedRequestBodyType.typeReference(this.convertTypeReference(t.requestBodyType));default:Ko(t)}}convertInlinedRequest({fernFilepath:t,wrapper:r,pathParameters:i,queryParameters:n,headers:a,body:u}){return Ic.Request.inlined({declaration:this.convertDeclaration({name:r.wrapperName,fernFilepath:t}),pathParameters:i,queryParameters:n,headers:a,body:u!=null?this.convertInlinedRequestBody({wrapper:r,body:u}):void 0,metadata:this.convertInlinedRequestMetadata({wrapper:r})})}convertInlinedRequestMetadata({wrapper:t}){return{includePathParameters:t.includePathParameters??!1,onlyPathParameters:t.onlyPathParameters??!1}}convertInlinedRequestBody({wrapper:t,body:r}){switch(r.type){case"inlinedRequestBody":{let i=[...r.extendedProperties??[],...r.properties];return Ic.InlinedRequestBody.properties(this.convertWireValueParameters({wireValueParameters:i}))}case"reference":return Ic.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:Ic.ReferencedRequestBodyType.typeReference(this.convertTypeReference(r.requestBodyType))});case"bytes":return Ic.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:Ic.ReferencedRequestBodyType.bytes()});case"fileUpload":return this.convertFileUploadRequestBody({properties:r.properties});default:Ko(r)}}convertFileUploadRequestBody({properties:t}){return Ic.InlinedRequestBody.fileUpload({properties:this.convertFileUploadRequestBodyProperties({properties:t})})}convertFileUploadRequestBodyProperties({properties:t}){return t.map(r=>{switch(r.type){case"file":return this.convertFileUploadRequestBodyFileProperty({fileProperty:r.value});case"bodyProperty":return Ic.FileUploadRequestBodyProperty.bodyProperty({name:r.name,typeReference:this.convertTypeReference(r.valueType)});default:Ko(r)}})}convertFileUploadRequestBodyFileProperty({fileProperty:t}){switch(t.type){case"file":return Ic.FileUploadRequestBodyProperty.file(t.key);case"fileArray":return Ic.FileUploadRequestBodyProperty.fileArray(t.key);default:Ko(t)}}convertPathParameters({pathParameters:t}){return t.map(r=>({name:{name:r.name,wireValue:r.name.originalName},typeReference:this.convertTypeReference(r.valueType)}))}convertWireValueParameters({wireValueParameters:t}){return t.map(r=>({name:{name:r.name.name,wireValue:r.name.wireValue},typeReference:this.convertTypeReference(r.valueType)}))}convertQueryParameters({queryParameters:t}){let r=[];for(let i of t){let n=this.convertTypeReference(i.valueType);i.allowMultiple&&(n=Ic.TypeReference.list(n)),r.push({name:{name:i.name.name,wireValue:i.name.wireValue},typeReference:n})}return r}convertTypeReference(t){switch(t.type){case"container":return this.convertContainerType(t.container);case"named":return this.convertNamedType(t);case"primitive":return this.convertPrimitiveType(t.primitive);case"unknown":return this.convertUnknownType();default:Ko(t)}}convertContainerType(t){switch(t.type){case"list":return Ic.TypeReference.list(this.convertTypeReference(t.list));case"map":return Ic.TypeReference.map({key:this.convertTypeReference(t.keyType),value:this.convertTypeReference(t.valueType)});case"optional":return Ic.TypeReference.optional(this.convertTypeReference(t.optional));case"nullable":return Ic.TypeReference.nullable(this.convertTypeReference(t.nullable));case"set":return Ic.TypeReference.set(this.convertTypeReference(t.set));case"literal":return Ic.TypeReference.literal(this.convertLiteral(t.literal));default:Ko(t)}}convertNamedType(t){return Ic.TypeReference.named(t.typeId)}convertTypeDeclaration(t){let r=this.convertDeclaration(t.name);switch(t.shape.type){case"alias":return this.convertAlias({declaration:r,alias:t.shape});case"enum":return this.convertEnum({declaration:r,enum_:t.shape});case"object":return this.convertObject({declaration:r,object:t.shape});case"union":return this.convertDiscriminatedUnion({declaration:r,union:t.shape});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({declaration:r,union:t.shape});default:Ko(t.shape)}}convertAlias({declaration:t,alias:r}){return Ic.NamedType.alias({declaration:t,typeReference:this.convertTypeReference(r.aliasOf)})}convertEnum({declaration:t,enum_:r}){return Ic.NamedType.enum({declaration:t,values:r.values.map(i=>i.name)})}convertObject({declaration:t,object:r}){let i=[...r.extendedProperties??[],...r.properties];return this.convertObjectProperties({declaration:t,properties:i})}convertObjectProperties({declaration:t,properties:r}){return Ic.NamedType.object({declaration:t,properties:this.convertWireValueParameters({wireValueParameters:r})})}convertDiscriminatedUnion({declaration:t,union:r}){let i=[...this.resolveProperties(r.extends),...r.baseProperties];return Ic.NamedType.discriminatedUnion({declaration:t,discriminant:r.discriminant,types:Object.fromEntries(r.types.map(n=>[n.discriminantValue.wireValue,this.convertDiscriminatedUnionType({inheritedProperties:i,discriminantValue:n.discriminantValue,singleUnionTypeProperties:n.shape})]))})}convertDiscriminatedUnionType({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperties:i}){switch(i.propertiesType){case"samePropertiesAsObject":return this.convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:i});case"singleProperty":return this.convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:i});case"noProperties":return this.convertDiscriminatedUnionTypeNoProperties({inheritedProperties:t,discriminantValue:r});default:Ko(i)}}convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:i}){return Ic.SingleDiscriminatedUnionType.samePropertiesAsObject({typeId:i.typeId,discriminantValue:r,properties:this.convertWireValueParameters({wireValueParameters:t})})}convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:i}){return Ic.SingleDiscriminatedUnionType.singleProperty({typeReference:this.convertTypeReference(i.type),discriminantValue:r,properties:t.length>0?this.convertWireValueParameters({wireValueParameters:t}):void 0})}convertDiscriminatedUnionTypeNoProperties({inheritedProperties:t,discriminantValue:r}){return Ic.SingleDiscriminatedUnionType.noProperties({discriminantValue:r,properties:t.length>0?this.convertWireValueParameters({wireValueParameters:t}):void 0})}convertUndiscriminatedUnion({declaration:t,union:r}){return Ic.NamedType.undiscriminatedUnion({declaration:t,types:r.members.map(i=>this.convertTypeReference(i.type))})}convertLiteral(t){switch(t.type){case"boolean":return Ic.LiteralType.boolean(t.boolean);case"string":return Ic.LiteralType.string(t.string);default:Ko(t)}}convertPrimitiveType(t){return Ic.TypeReference.primitive(t.v1)}convertUnknownType(){return Ic.TypeReference.unknown()}convertAuth(t){if(t.schemes[0]==null)return;let r=t.schemes[0];switch(r.type){case"basic":return Ic.Auth.basic(r);case"bearer":return Ic.Auth.bearer(r);case"header":return Ic.Auth.header({header:{name:r.name,typeReference:this.convertTypeReference(r.valueType)}});case"oauth":return;default:Ko(r)}}getAuthValues(t){let r=t.schemes[0];if(r!=null)switch(r.type){case"bearer":return Ic.AuthValues.bearer({token:"<token>"});case"basic":return Ic.AuthValues.basic({username:"<username>",password:"<password>"});case"header":return Ic.AuthValues.header({value:"<value>"});case"oauth":return;default:Ko(r)}}convertDeclaration({name:t,fernFilepath:r}){return{name:t,fernFilepath:r}}convertEndpointLocation({endpoint:t}){return{method:t.method,path:this.getFullPathForEndpoint(t)}}getAllHttpEndpoints(){return Object.values(this.ir.services).flatMap(t=>t.endpoints.map(r=>({...r,serviceHeaders:t.headers,fernFilepath:t.name.fernFilepath})))}resolveProperties(t){let r=[];for(let i of t){let n=this.resolveObjectTypeOrThrow(i.typeId);r.push(...this.resolveProperties(n.extends)),r.push(...n.properties)}return Object.values(r)}resolveObjectTypeOrThrow(t){let r=this.ir.types[t];if(r==null)throw new Error(`Internal error; type "${t}" not found`);if(r.shape.type!=="object")throw new Error(`Internal error; type "${t}" is not an object`);return r.shape}getFullPathForEndpoint(t){let r="";t.fullPath.head.length>0&&(r=Cv(r,t.fullPath.head));for(let i of t.fullPath.parts)r=Cv(r,"{"+i.pathParameter+"}"),i.tail.length>0&&(r=Cv(r,i.tail));return r.startsWith("/")?r:`/${r}`}getEndpointSnippetRequests({endpoint:t,location:r}){let i=[];for(let n of[...t.userSpecifiedExamples,...t.autogeneratedExamples])i.push({id:n?.example?.id??zre(),name:n?.example?.name?.originalName,endpoint:r,baseUrl:void 0,environment:void 0,auth:this.authValues,headers:Object.fromEntries([...n.example?.serviceHeaders??[],...n.example?.endpointHeaders??[]].map(a=>[a.name.wireValue,a.value.jsonExample])),pathParameters:Object.fromEntries([...n.example?.rootPathParameters??[],...n.example?.servicePathParameters??[],...n.example?.endpointPathParameters??[]].map(a=>[a.name.originalName,a.value.jsonExample])),queryParameters:Object.fromEntries([...n.example?.queryParameters??[]].map(a=>[a.name.wireValue,a.value.jsonExample])),requestBody:n.example?.request?.jsonExample});return i}};function Xr_({ir:e,includeExamples:t}){return new bzo(e).convert({includeExamples:t})}var sG={};Io(sG,{validateObjectExample:()=>Gzi,validateTypeExample:()=>pzo,validateTypeReferenceExample:()=>h5});var gzo=class{subpackages={};rootPackage={docs:void 0,fernFilepath:{allParts:[],packagePath:[],file:void 0},websocket:void 0,service:void 0,types:[],errors:[],subpackages:[],webhooks:void 0,navigationConfig:void 0};addPackageRedirection({from:t,to:r}){let i=this.getPackageForFernFilepath(t);if(i.navigationConfig!=null)throw new Error("Found duplicate navigationConfig for package");i.navigationConfig={pointsTo:Ng.generateSubpackageId(r)}}addDocs(t,r){let i=this.getPackageForFernFilepath(t);if(i.docs!=null)throw new Error("Found duplicate docs for package");i.docs=r}addSubpackage(t){this.getPackageForFernFilepath(t)}addType(t,r){this.getPackageForFernFilepath(r.name.fernFilepath).types.push(t)}addError(t,r){this.getPackageForFernFilepath(r.name.fernFilepath).errors.push(t)}addService(t,r){let i=this.getPackageForFernFilepath(r.name.fernFilepath);if(i.service!=null)throw new Error("Found duplicate service for "+t);i.service=t}addWebhookGroup(t,r){let i=this.getPackageForFernFilepath(r);if(i.webhooks!=null)throw new Error("Found duplicate webhook group for "+t);i.webhooks=t}addWebSocketChannel(t,r){let i=this.getPackageForFernFilepath(r);if(i.webhooks!=null)throw new Error("Found duplicate webhook group for "+t);i.websocket=t}build(t){t!=null&&(Object.entries(this.subpackages).forEach(([i,n])=>{t.hasSubpackageId(i)?this.subpackages[i]={...n,types:n.types.filter(a=>t.hasTypeId(a)),errors:n.errors.filter(a=>t.hasErrorId(a)),service:n.service!=null&&t.hasServiceId(n.service)?n.service:void 0,subpackages:n.subpackages.filter(a=>t.hasSubpackageId(a))}:delete this.subpackages[i]}),this.rootPackage={...this.rootPackage,types:this.rootPackage.types.filter(i=>t.hasTypeId(i)),errors:this.rootPackage.errors.filter(i=>t.hasErrorId(i)),service:this.rootPackage.service!=null&&t.hasServiceId(this.rootPackage.service)?this.rootPackage.service:void 0,subpackages:this.rootPackage.subpackages.filter(i=>t.hasSubpackageId(i)),webhooks:this.rootPackage.webhooks!=null?this.rootPackage.webhooks:void 0});let r=new Set(this.getAllChildrenWithEndpoints(this.rootPackage));return{subpackages:od(this.subpackages,(i,n)=>({...i,hasEndpointsInTree:r.has(n)})),rootPackage:{...this.rootPackage,hasEndpointsInTree:r.size>0||this.rootPackage.service!=null}}}sortRootPackage(t){if(!Zr_(this.rootPackage.subpackages,t))throw new Error("Sorted subpackages differ from unsorted packages in root");this.rootPackage.subpackages=t}sortSubpackage(t,r){let i=this.subpackages[t];if(i==null)throw new Error("Subpackage does not exist: "+t);if(!Zr_(i.subpackages,r))throw new Error("Sorted subpackages differ from unsorted packages");i.subpackages=r}getAllSubpackagesWithEndpoints(t){let r=this.subpackages[t];if(r==null)throw new Error("Subpackage does not exist: "+t);let i=this.getAllChildrenWithEndpoints(r);return(i.length>0||r.service!=null)&&i.push(t),i}getAllChildrenWithEndpoints(t){return t.subpackages.flatMap(r=>[...this.getAllSubpackagesWithEndpoints(r)])}getPackageForFernFilepath(t,r=0,i=this.rootPackage){let n=t.allParts[r];if(n==null)return i;let a=i.subpackages.map(s=>{let o=this.subpackages[s];if(o==null)throw new Error("Subpackage ID is invalid: "+s);return o}),u=r+1,l={allParts:t.allParts.slice(0,u),packagePath:t.packagePath.slice(0,u),file:u===t.allParts.length?t.file:void 0},d=a.find(s=>s.name.originalName===n.originalName);if(d==null){let s=Ng.generateSubpackageId(l),o={docs:void 0,fernFilepath:l,name:n,service:void 0,types:[],errors:[],subpackages:[],navigationConfig:void 0,webhooks:void 0,websocket:void 0};this.subpackages[s]=o,i.subpackages.push(s),d=o}return this.getPackageForFernFilepath(t,u,d)}};function Zr_(e,t){if(e.length!==t.length)return!1;let r=new Set(e);for(let i of t)if(!r.has(i))return!1;return!0}function kr_(e){return{errorInstanceIdKey:e.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}}function Ozo({fernFilePath:e}){return e.packagePath.length===0&&e.file==null}function ei_({endpointResolver:e,propertyResolver:t,file:r,refreshTokenEndpoint:i}){let n=e.resolveEndpointOrThrow({endpoint:i.endpoint,file:r});return{endpointReference:{endpointId:Ng.generateEndpointIdFromResolvedEndpoint(n),serviceId:Ng.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:Ozo({fernFilePath:n.file.fernFilepath})?void 0:Ng.generateSubpackageId(n.file.fernFilepath)},requestProperties:{refreshToken:t.resolveRequestPropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.requestProperties.refresh_token})},responseProperties:{accessToken:t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.access_token}),expiresIn:i.responseProperties.expires_in!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.expires_in}):void 0,refreshToken:i.responseProperties.refresh_token!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.refresh_token}):void 0}}}function ti_({endpointResolver:e,propertyResolver:t,file:r,tokenEndpoint:i}){let n=e.resolveEndpointOrThrow({endpoint:i.endpoint,file:r}),a=typeof n.endpoint.request=="object"&&n.endpoint.request.body!=null&&typeof n.endpoint.request.body=="object"&&"properties"in n.endpoint.request.body?n.endpoint.request.body.properties??{}:{};return{endpointReference:{endpointId:Ng.generateEndpointIdFromResolvedEndpoint(n),serviceId:Ng.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:Ozo({fernFilePath:n.file.fernFilepath})?void 0:Ng.generateSubpackageId(n.file.fernFilepath)},requestProperties:{clientId:t.resolveRequestPropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.requestProperties.client_id}),clientSecret:t.resolveRequestPropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.requestProperties.client_secret}),scopes:i.requestProperties.scopes!=null?t.resolveRequestPropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.requestProperties.scopes}):void 0,customProperties:BGD({requestBodyProperties:a,tokenEndpoint:i,file:r,propertyResolver:t})},responseProperties:{accessToken:t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.access_token}),expiresIn:i.responseProperties.expires_in!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.expires_in}):void 0,refreshToken:i.responseProperties.refresh_token!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.refresh_token}):void 0}}}var BGD=({requestBodyProperties:e,tokenEndpoint:t,file:r,propertyResolver:i})=>{let n=Object.keys(e).filter(a=>!t.requestProperties.client_id.includes(a)&&!t.requestProperties.client_secret.includes(a)&&(t.requestProperties.scopes==null||!t.requestProperties.scopes.includes(a)));return n.length>0?n.map(a=>i.resolveRequestPropertyOrThrow({file:r,endpoint:t.endpoint,propertyComponents:[a]})):void 0};function ri_({propertyResolver:e,endpointResolver:t,file:r,oauthScheme:i,tokenEndpoint:n,refreshTokenEndpoint:a}){let u=ti_({propertyResolver:e,endpointResolver:t,file:r,tokenEndpoint:n});if(u==null)throw new Error("Failed to convert OAuth token endpoint.");let l=a!=null?ei_({propertyResolver:e,endpointResolver:t,file:r,refreshTokenEndpoint:a}):void 0;return{clientIdEnvVar:i["client-id-env"],clientSecretEnvVar:i["client-secret-env"],tokenPrefix:i["token-prefix"],tokenHeader:i["token-header"],scopes:i.scopes,tokenEndpoint:u,refreshEndpoint:l}}var L_a={requestProperties:{type:"access_token",client_id:["client_id"],client_secret:["client_secret"],scopes:void 0},responseProperties:{type:"access_token",access_token:["access_token"],expires_in:void 0,refresh_token:void 0}},nKs={requestProperties:{type:"refresh_token",refresh_token:["refresh_token"]},responseProperties:{type:"access_token",access_token:["access_token"],refresh_token:void 0,expires_in:void 0}};function ii_(e){return{endpoint:e["get-token"].endpoint,requestProperties:xGD({requestProperties:e["get-token"]?.["request-properties"]}),responseProperties:IGD({responseProperties:e["get-token"]?.["response-properties"]})}}function ni_(e){if(e["refresh-token"]!=null)return{endpoint:e["refresh-token"].endpoint,requestProperties:zGD({requestProperties:e["refresh-token"]?.["request-properties"]}),responseProperties:RGD({responseProperties:e["refresh-token"]?.["response-properties"]})}}function xGD({requestProperties:e}){if(e==null)return L_a.requestProperties;let t=e["client-id"],r=e["client-secret"],i=e.scopes;return{type:"access_token",client_id:t!=null?p5t(t):L_a.requestProperties.client_id,client_secret:r!=null?p5t(r):L_a.requestProperties.client_secret,scopes:i!=null?p5t(i):L_a.requestProperties.scopes}}function IGD({responseProperties:e}){return ai_({responseProperties:e,defaultValue:L_a.responseProperties})}function zGD({requestProperties:e}){if(e==null)return nKs.requestProperties;let t=e["refresh-token"];return{type:"refresh_token",refresh_token:t!=null?p5t(t):nKs.requestProperties.refresh_token}}function RGD({responseProperties:e}){return ai_({responseProperties:e,defaultValue:nKs.responseProperties})}function ai_({responseProperties:e,defaultValue:t}){if(e==null)return t;let r=e["access-token"],i=e["expires-in"],n=e["refresh-token"];return{type:"access_token",access_token:r!=null?iXt(r):t.access_token,expires_in:i!=null?iXt(i):t.expires_in,refresh_token:n!=null?iXt(n):t.refresh_token}}function li_({rawApiFileSchema:e,file:t,propertyResolver:r,endpointResolver:i}){if(e.auth==null)return{docs:void 0,requirement:Doi.All,schemes:[]};let n=typeof e.auth!="string"?e.auth.docs:void 0;return pra(e.auth,{single:a=>{let u=oi_({reference:a,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i});return{docs:n,requirement:Doi.All,schemes:[u]}},any:({any:a})=>({docs:n,requirement:Doi.Any,schemes:a.map(u=>oi_({reference:u,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i}))})})}function oi_({reference:e,authSchemeDeclarations:t,file:r,propertyResolver:i,endpointResolver:n}){let a=(l,d)=>{let s=t?.[l];if(s==null)throw new Error("Unknown auth scheme: "+l);return Hvs(s,{header:o=>dR.header({docs:d,name:r.casingsGenerator.generateNameAndWireValue({name:o.name??l,wireValue:o.header}),valueType:r.parseTypeReference(o.type??"string"),prefix:o.prefix,headerEnvVar:o.env}),basic:o=>si_({file:r,docs:d,rawScheme:o}),bearer:o=>ui_({file:r,docs:d,rawScheme:o}),oauth:o=>ci_({file:r,docs:d,rawScheme:o,propertyResolver:i,endpointResolver:n})})},u=typeof e=="string"?e:e.scheme;switch(u){case"bearer":return ui_({file:r,docs:void 0,rawScheme:void 0});case"basic":return si_({file:r,docs:void 0,rawScheme:void 0});case"oauth":return ci_({file:r,docs:void 0,rawScheme:void 0,propertyResolver:i,endpointResolver:n});default:return a(u,typeof e!="string"?e.docs:void 0)}}function ui_({file:e,docs:t,rawScheme:r}){return dR.bearer({docs:t,token:e.casingsGenerator.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function si_({file:e,docs:t,rawScheme:r}){return dR.basic({docs:t,username:e.casingsGenerator.generateName(r?.username?.name??"username"),usernameEnvVar:r?.username?.env,password:e.casingsGenerator.generateName(r?.password?.name??"password"),passwordEnvVar:r?.password?.env})}function ci_({file:e,docs:t,rawScheme:r,propertyResolver:i,endpointResolver:n}){switch(r?.type){case"client-credentials":return dR.oauth({docs:t,configuration:Eoi.clientCredentials(ri_({propertyResolver:i,endpointResolver:n,file:e,oauthScheme:r,tokenEndpoint:ii_(r),refreshTokenEndpoint:ni_(r)}))});default:throw new Error(`Unknown OAuth type: '${r?.type}'`)}}function fi_({file:e,rawApiFileSchema:t}){if(t.version!=null)return Aoi.header({header:NGD({file:e,header:t.version.header}),value:FGD({file:e,versionDeclaration:t.version})})}function NGD({file:e,header:t}){return typeof t=="string"?rze({file:e,headerKey:t,header:{type:"string"}}):rze({file:e,headerKey:t.value,header:{type:"string",name:t.name,env:t.env}})}function FGD({file:e,versionDeclaration:t}){return _zo({_enum:{default:t.default,enum:t.values},file:e})}function di_({channel:e,typeResolver:t,exampleResolver:r,variableResolver:i,file:n,workspace:a}){let u=[];for(let[l,d]of Object.entries(e.messages??{}))u.push({type:l,availability:hie(d.availability),docs:d.docs,origin:d.origin,body:VGD({body:d.body,file:n}),displayName:d["display-name"]});return{availability:hie(e.availability),path:iV(e.path),baseUrl:e.url,auth:e.auth,name:n.fernFilepath.file??n.casingsGenerator.generateName(e["display-name"]??e.path),displayName:e["display-name"],headers:e.headers!=null?Object.entries(e.headers).map(([l,d])=>rze({headerKey:l,header:d,file:n})):[],docs:e.docs,pathParameters:e["path-parameters"]!=null?v1n({pathParameters:e["path-parameters"],location:PBe.Endpoint,file:n,variableResolver:i}):[],queryParameters:e["query-parameters"]!=null?Object.entries(e["query-parameters"]).map(([l,d])=>{let{name:s}=FQr({queryParameterKey:l,queryParameter:d}),o=n.parseTypeReference(d);return{...uG(d),name:n.casingsGenerator.generateNameAndWireValue({wireValue:l,name:s}),valueType:o,allowMultiple:typeof d!="string"&&d["allow-multiple"]!=null?d["allow-multiple"]:!1}}):[],messages:Object.values(u),examples:(e.examples??[]).map(l=>{let d=HGD({channel:e,example:l,typeResolver:t,exampleResolver:r,variableResolver:i,file:n,workspace:a});return{name:l.name!=null?n.casingsGenerator.generateName(l.name):void 0,docs:l.docs,url:GGD({channel:e,example:l,pathParams:d}),...d,...$GD({channel:e,example:l,typeResolver:t,exampleResolver:r,file:n,workspace:a}),queryParameters:l["query-parameters"]!=null?Object.entries(l["query-parameters"]).map(([s,o])=>{let c=e["query-parameters"]?.[s];if(c==null)throw new Error(`Query parameter ${s} does not exist`);return{name:n.casingsGenerator.generateNameAndWireValue({name:FQr({queryParameterKey:s,queryParameter:c}).name,wireValue:s}),value:rE({example:o,rawTypeBeingExemplified:typeof c=="string"?c:c.type,typeResolver:t,exampleResolver:r,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),shape:LGD({queryParameter:c})}}):[],messages:l.messages.map(s=>{let o=e.messages?.[s.type];if(o==null)throw new Error(`Message ${s.type} does not exist`);return{type:s.type,body:UGD({message:o,example:s.body,typeResolver:t,exampleResolver:r,file:n,workspace:a})}})}})}}function LGD({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?Q6.exploded():Q6.single()}function UGD({message:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){if(!QGD(e.body))return w4t.reference(rE({example:t,rawTypeBeingExemplified:typeof e.body!="string"?e.body.type:e.body,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}));if(!Hj(t))throw new Error("Example must be an object");let u=[];for(let[l,d]of Object.entries(t)){let s=e.body.properties?.[l];if(s!=null)u.push({name:n.casingsGenerator.generateNameAndWireValue({name:uV({propertyKey:l,property:s}).name,wireValue:l}),value:rE({example:d,rawTypeBeingExemplified:typeof s!="string"?s.type:s,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),originalTypeDeclaration:void 0});else{let o=N_a({extends_:e.body.extends,wirePropertyKey:l,typeResolver:r,file:n});if(o==null)throw new Error("Could not find original type declaration for property: "+l);u.push({name:n.casingsGenerator.generateNameAndWireValue({name:uV({propertyKey:l,property:o.rawPropertyType}).name,wireValue:l}),value:rE({example:d,rawTypeBeingExemplified:typeof o.rawPropertyType=="string"?o.rawPropertyType:o.rawPropertyType.type,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:o.file,fileContainingExample:n,workspace:a}),originalTypeDeclaration:o.typeName})}}return w4t.inlinedBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t,file:n}).resolvedExample,properties:u})}function VGD({body:e,file:t}){return typeof e=="string"?Xte.reference({docs:void 0,bodyType:t.parseTypeReference(e)}):WGD(e)?Xte.reference({docs:void 0,bodyType:t.parseTypeReference(e.type)}):Xte.inlinedBody({name:t.casingsGenerator.generateName(e.name),extends:d5t(e.extends??[]).map(r=>_5({typeName:r,file:t})),properties:[]})}function WGD(e){return e.type!=null}function HGD({channel:e,example:t,typeResolver:r,exampleResolver:i,variableResolver:n,file:a,workspace:u}){let l=[],d=({name:s,pathParameterDeclaration:o,examplePathParameter:c})=>{let b=F_a({parameter:o,variableResolver:n,file:a});return{name:s,value:rE({example:c,rawTypeBeingExemplified:b.rawType,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:b.file,fileContainingExample:a,workspace:u})}};if(t["path-parameters"]!=null){let s=_5t(e);for(let[o,c]of Object.entries(t["path-parameters"])){let b=s[o];if(b!=null)l.push(d({name:a.casingsGenerator.generateName(o),pathParameterDeclaration:b,examplePathParameter:c}));else throw new Error(`Path parameter ${o} does not exist`)}}return{pathParameters:l}}function $GD({channel:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){let u=[];if(t.headers!=null)for(let[l,d]of Object.entries(t.headers)){let s=e.headers?.[l];if(s!=null)u.push({name:n.casingsGenerator.generateNameAndWireValue({name:nXt({headerKey:l,header:s}).name,wireValue:l}),value:rE({example:d,rawTypeBeingExemplified:typeof s=="string"?s:s.type,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a})});else throw new Error(`Heder ${l} does not exist`)}return{headers:u}}function GGD({channel:e,example:t,pathParams:r}){let i=e.path;if(t["path-parameters"]!=null)for(let n of[...r.pathParameters])i=i.replaceAll(`{${n.name.originalName}}`,`${n.value.jsonExample}`);return i}function QGD(e){return typeof e=="string"?!1:e.extends!=null||e.properties!=null}function aKs({rawApiFileSchema:{"default-environment":e,environments:t},casingsGenerator:r}){if(t==null)return;let i=Object.values(t)[0];if(i!=null)return{defaultEnvironment:e??void 0,environments:o$r(i,{singleBaseUrl:()=>q1e.singleBaseUrl(JGD({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>q1e.multipleBaseUrls(KGD({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})}}function JGD({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>o$r(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:pi_(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function KGD({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>o$r(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:od(a.urls,u=>pi_(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function pi_(e){return e.endsWith("/")?e.slice(0,-1):e}function _i_({errorName:e,errorDeclaration:t,file:r,typeResolver:i,exampleResolver:n,workspace:a}){let u=[];if(t.type!=null&&t.examples!=null)for(let l of t.examples)u.push({name:l.name!=null?r.casingsGenerator.generateName(l.name):void 0,docs:l.docs,jsonExample:n.resolveAllReferencesInExampleOrThrow({example:l.value,file:r}).resolvedExample,shape:rE({example:l.value,rawTypeBeingExemplified:t.type,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})});return{name:Hfi({errorName:e,file:r}),discriminantValue:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:e}),docs:typeof t!="string"?t.docs:void 0,statusCode:t["status-code"],type:t.type!=null?r.parseTypeReference(t.type):void 0,examples:u}}var hi_="content";function yi_(e,t){if(e==null||e.strategy==="status-code")return P4t.statusCode();switch(e.strategy){case"property":return P4t.property({discriminant:t.casingsGenerator.generateNameAndWireValue({name:e["property-name"],wireValue:e["property-name"]}),contentProperty:t.casingsGenerator.generateNameAndWireValue({name:hi_,wireValue:hi_})});default:Ko(e)}}function vi_({readme:e,services:t}){let r=new oKs(t);return{apiReferenceLink:e.apiReferenceLink,bannerLink:e.bannerLink,introduction:e.introduction,defaultEndpoint:e.defaultEndpoint!=null?r.getEndpointForReadmeOrThrow(e.defaultEndpoint).id:void 0,features:e.features!=null?Object.fromEntries(Object.entries(e.features).map(([i,n])=>[i,n.map(a=>r.getEndpointForReadmeOrThrow(a).id)])):void 0}}var oKs=class{endpoints={};constructor(t){this.endpoints=this.buildEndpoints(t)}getEndpointForReadme(t){let r=XGD({endpoint:t}),i=this.getEndpointKeyForReadmeEndpoint(r);return this.endpoints[i]}getEndpointForReadmeOrThrow(t){let r=this.getEndpointForReadme(t);if(r==null)throw new Error(`Endpoint not found for ${JSON.stringify(t)}`);return r}buildEndpoints(t){let r={};for(let i of Object.values(t))for(let n of i.endpoints)r[this.getEndpointKeyForHttpEndpoint(n)]=n;return r}getEndpointKeyForReadmeEndpoint(t){return this.getEndpointKey({method:t.method,path:t.path,stream:t.stream??!1})}getEndpointKeyForHttpEndpoint(t){return this.getEndpointKey({method:t.method,path:YGD(t),stream:t.response?.body?.type==="streaming"})}getEndpointKey({method:t,path:r,stream:i}){return`${t}|${r}|${i}`}};function YGD(e){let t="";e.fullPath.head.length>0&&(t=Cv(t,e.fullPath.head));for(let r of e.fullPath.parts)t=Cv(t,"{"+r.pathParameter+"}"),r.tail.length>0&&(t=Cv(t,r.tail));return t.startsWith("/")?t:`/${t}`}function XGD({endpoint:e}){if(typeof e=="string"){let t=e.split(" ");if(t.length!==2||t[0]==null||t[1]==null)throw new Error(`invalid endpoint string: ${e}`);return{method:t[0],path:t[1]}}return e}function bi_({webhooks:e,file:t,typeResolver:r,exampleResolver:i,workspace:n}){let a=[];for(let[u,l]of Object.entries(e))a.push({id:Ng.generateWebhookId(t.fernFilepath,u),availability:hie(l.availability),displayName:l["display-name"],docs:l.docs,method:l.method,name:t.casingsGenerator.generateName(u),headers:l.headers!=null?Object.entries(l.headers).map(([d,s])=>rze({headerKey:d,header:s,file:t})):[],payload:ZGD({payload:l.payload,file:t}),examples:l.examples!=null?eQD({webhook:l,examples:l.examples,file:t,typeResolver:r,exampleResolver:i,workspace:n}):void 0});return a}function ZGD({payload:e,file:t}){return typeof e=="string"?hU.reference({docs:void 0,payloadType:t.parseTypeReference(e)}):mzo(e)?hU.reference({docs:void 0,payloadType:t.parseTypeReference(e.type)}):hU.inlinedPayload({name:t.casingsGenerator.generateName(e.name),extends:d5t(e.extends).map(r=>_5({typeName:r,file:t})),properties:e.properties!=null?Object.entries(e.properties).map(([r,i])=>kGD({propertyKey:r,propertyDefinition:i,docs:typeof i!="string"?i.docs:void 0,availability:typeof i!="string"?hie(i.availability):void 0,file:t})):[]})}function kGD({propertyKey:e,propertyDefinition:t,docs:r,availability:i,file:n}){return{docs:r,availability:i,name:n.casingsGenerator.generateNameAndWireValue({wireValue:e,name:uV({propertyKey:e,property:t}).name}),valueType:n.parseTypeReference(t)}}function eQD({webhook:e,examples:t,file:r,typeResolver:i,exampleResolver:n,workspace:a}){let u=typeof e.payload=="string"?e.payload:mzo(e.payload)?e.payload.type:void 0;if(u!=null)return t.map(l=>({docs:e.docs,name:l.name!=null?r.casingsGenerator.generateName(l.name):void 0,payload:rE({example:l.payload,rawTypeBeingExemplified:u,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}));if(!Hj(e.payload))throw new Error(`Example webhook payload is not an object. Got: ${JSON.stringify(e.payload)}`);return t.map(l=>({docs:e.docs,name:l.name!=null?r.casingsGenerator.generateName(l.name):void 0,payload:rE({example:l.payload,rawTypeBeingExemplified:"map<string, unknown>",fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}))}function mzo(e){return e.type!=null}function b1n(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}function gi_({name:e,source:t}){return oj.userDefined({file:yzo({source:t}),name:$fi.generateName(e)})}function Oi_({encoding:e}){if(e.proto!=null&&e.proto.type!=null){let t=tQD({type:e.proto.type});if(t!=null)return t}}function tQD({type:e}){switch(e){case"google.protobuf.Any":return oj.wellKnown(Xf.any());case"google.protobuf.Api":return oj.wellKnown(Xf.api());case"google.protobuf.BoolValue":return oj.wellKnown(Xf.boolValue());case"google.protobuf.BytesValue":return oj.wellKnown(Xf.bytesValue());case"google.protobuf.DoubleValue":return oj.wellKnown(Xf.doubleValue());case"google.protobuf.Duration":return oj.wellKnown(Xf.duration());case"google.protobuf.Empty":return oj.wellKnown(Xf.empty());case"google.protobuf.Enum":return oj.wellKnown(Xf.enum());case"google.protobuf.EnumValue":return oj.wellKnown(Xf.enumValue());case"google.protobuf.Field":return oj.wellKnown(Xf.field());case"google.protobuf.FieldCardinality":return oj.wellKnown(Xf.fieldCardinality());case"google.protobuf.FieldKind":return oj.wellKnown(Xf.fieldKind());case"google.protobuf.FieldMask":return oj.wellKnown(Xf.fieldMask());case"google.protobuf.FloatVlaue":return oj.wellKnown(Xf.floatValue());case"google.protobuf.Int32Value":return oj.wellKnown(Xf.int32Value());case"google.protobuf.Int64Value":return oj.wellKnown(Xf.int64Value());case"google.protobuf.ListValue":return oj.wellKnown(Xf.listValue());case"google.protobuf.Method":return oj.wellKnown(Xf.method());case"google.protobuf.Mixin":return oj.wellKnown(Xf.mixin());case"google.protobuf.NullValue":return oj.wellKnown(Xf.nullValue());case"google.protobuf.Option":return oj.wellKnown(Xf.option());case"google.protobuf.SourceContext":return oj.wellKnown(Xf.sourceContext());case"google.protobuf.StringValue":return oj.wellKnown(Xf.stringValue());case"google.protobuf.Struct":return oj.wellKnown(Xf.struct());case"google.protobuf.Syntax":return oj.wellKnown(Xf.syntax());case"google.protobuf.Timestamp":return oj.wellKnown(Xf.timestamp());case"google.protobuf.Type":return oj.wellKnown(Xf.type());case"google.protobuf.Uint32Value":return oj.wellKnown(Xf.uint32Value());case"google.protobuf.Uint64Value":return oj.wellKnown(Xf.uint64Value());case"google.protobuf.Value":return oj.wellKnown(Xf.value())}}function mi_({generic:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type,n=RI(i);if(n==null)throw new Error(`Invalid generic type definition: ${i}`);let a=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:i,file:t});if(n.arguments&&G1(a.declaration)){let u=RI(a.typeName)?.arguments??[],l=Object.entries(a.declaration.properties??{}).map(([d,s])=>{let o=s;return typeof s=="string"&&u?.includes(s)&&(o=n.arguments?.[u.indexOf(s)]??s),[d,o]});return Gj.object({extends:d5t(a.declaration.extends).map(d=>_5({typeName:d,file:t})),properties:B_a({properties:Object.fromEntries(l)},t),extraProperties:a.declaration["extra-properties"]??!1,extendedProperties:void 0})}throw new Error(`Generic type definition not supported: ${i}`)}function Pi_({alias:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type;return OBe(i)?mi_({generic:i,file:t,typeResolver:r}):Gj.alias({aliasOf:t.parseTypeReference(e),resolvedType:rQD({aliasOf:i,file:t,typeResolver:r})})}function rQD({aliasOf:e,file:t,typeResolver:r}){let i=r.resolveTypeOrThrow({type:e,file:t});switch(i._type){case"primitive":return _U.primitive(i.originalTypeReference.primitive);case"container":return _U.container(i.originalTypeReference.container);case"unknown":return _U.unknown();case"named":{let n=G1(i.declaration)?j4t.Object:Loi(i.declaration)?j4t.Union:M4t(i.declaration)?j4t.Enum:Mhn(i.declaration)?j4t.UndiscriminatedUnion:Ko(i.declaration);return _U.named({name:i.name,shape:n})}}}function ji_({union:e,file:t}){let r=e.union.filter((i,n)=>{let a=typeof i=="string"?i:i.type;return e.union.findIndex(u=>(typeof u=="string"?u:u.type)===a)===n});return Gj.undiscriminatedUnion({members:r.map(i=>typeof i=="string"?{docs:void 0,type:t.parseTypeReference(i)}:{type:t.parseTypeReference(i.type),docs:i.docs})})}function wi_(e){let t=[];if(e.extends!=null){let r=typeof e.extends=="string"?[e.extends]:e.extends;t.push(...r)}return e.properties!=null&&t.push(...Object.values(e.properties).map(r=>typeof r=="string"?r:r.type)),t}function sKs({typeDeclaration:e,file:t,typeResolver:r,seenTypeNames:i=new uKs}){let n=xN(e,{alias:u=>{let l=typeof u=="string"?u:u.type,d=RI(l);if(d!=null){let s=new Set(d.arguments??[]),o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:l,file:t}),c=RI(o.typeName)?.arguments;if(G1(o.declaration)){let b=wi_(o.declaration);c&&b.filter(g=>!c.includes(g)).forEach(g=>s.add(g))}return Array.from(s)}return[l]},object:u=>wi_(u),discriminatedUnion:u=>{let l=[];return u["base-properties"]!=null&&l.push(...Object.values(u["base-properties"]).map(d=>typeof d=="string"?d:d.type)),l.push(...Object.values(u.union).reduce((d,s)=>{let o=typeof s=="string"?s:s.type;return typeof o=="string"&&d.push(o),d},[])),l},undiscriminatedUnion:u=>Object.values(u.union).reduce((l,d)=>{let s=typeof d=="string"?d:d.type;return typeof s=="string"&&l.push(s),l},[]),enum:()=>[]}),a=[];for(let u of n){let l=yU({type:u,_default:void 0,validation:void 0,visitor:{primitive:()=>[],map:({keyType:d,valueType:s})=>[...d,...s],list:d=>d,optional:d=>d,nullable:d=>d,set:d=>d,named:d=>[d],literal:()=>[],unknown:()=>[]}});for(let d of l){let s=_5({typeName:d,file:t});if(!i.hasTypeNameBeenSeen(s)){i.addTypeName(s),a.push(s);let o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:d,file:t});if(OBe(o.typeName))continue;a.push(...sKs({typeDeclaration:o.declaration,file:o.file,typeResolver:r,seenTypeNames:i}))}}}return a}var uKs=class{cache=new Set;addTypeName(t){this.cache.add(this.computeCacheKey(t))}hasTypeNameBeenSeen(t){return this.cache.has(this.computeCacheKey(t))}computeCacheKey(t){return t.fernFilepath.allParts.map(r=>r.originalName).join("/")+":"+t.name.originalName}};function Si_({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,sourceResolver:a,workspace:u}){let l=uG(t),d=_5({typeName:e,file:r}),s=sKs({typeDeclaration:t,file:r,typeResolver:i}),o={};G1(t)&&(o=b1n(t.properties??{}));let c=nQD({file:r,typeDeclaration:t,typeName:e,sourceResolver:a});return{propertiesByAudience:o,typeDeclaration:{...l,inline:sQD(t),name:d,shape:iQD({typeDeclaration:t,file:r,typeResolver:i}),referencedTypes:new Set(s.map(b=>b.typeId)),encoding:aQD({typeDeclaration:t,source:c}),source:c,userProvidedExamples:typeof t!="string"&&t.examples!=null?t.examples.map(b=>({name:b.name!=null?r.casingsGenerator.generateName(b.name):void 0,docs:b.docs,jsonExample:n.resolveAllReferencesInExampleOrThrow({example:b.value,file:r}).resolvedExample,shape:iKs({typeName:d,example:b.value,typeResolver:i,exampleResolver:n,typeDeclaration:t,fileContainingType:r,fileContainingExample:r,workspace:u})})):[],autogeneratedExamples:[]},descendantFilepaths:new Set(s.map(b=>b.fernFilepath))}}function iQD({typeDeclaration:e,file:t,typeResolver:r}){return xN(e,{alias:i=>Pi_({alias:i,file:t,typeResolver:r}),object:i=>ar_({object:i,file:t}),discriminatedUnion:i=>Or_({union:i,file:t,typeResolver:r}),undiscriminatedUnion:i=>ji_({union:i,file:t}),enum:i=>Gj.enum(_zo({_enum:i,file:t}))})}function nQD({file:e,typeDeclaration:t,typeName:r,sourceResolver:i}){if(typeof t=="string"||t.source==null&&t.encoding==null)return;if(t.encoding!=null){let a=Oi_({encoding:t.encoding});if(a!=null)return n$r.proto(a)}if(t.source==null)return;let n=i.resolveSourceOrThrow({source:t.source,relativeFilepath:e.relativeFilepath});if(!(n==null||n.type!=="protobuf"))return n$r.proto(gi_({source:n,name:r}))}function aQD({typeDeclaration:e,source:t}){return typeof e!="string"&&e.encoding!=null?oQD(e.encoding):uQD(t)}function oQD(e){return e.proto!=null?{json:void 0,proto:{}}:{json:{},proto:void 0}}function uQD(e){return e!=null&&e.type==="proto"?{json:void 0,proto:{}}:{json:{},proto:void 0}}function sQD(e){if(typeof e!="string"&&"inline"in e)return e.inline}function Di_(e,t){let r=t[e];if(r==null)throw new THr(`Illegal Error: Failed to load type declaration for type ${e}`);return r}function Ei_(e){return{types:Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,lQD({typeDeclaration:r,ir:e})])),services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(i=>cQD({endpoint:i,ir:e}))}]))}}function cQD({endpoint:e,ir:t}){return e.requestBody?.type!=="inlinedRequestBody"?e:{...e,requestBody:{...e.requestBody,extendedProperties:e.requestBody.extends.flatMap(r=>Mi_(r,t))}}}function lQD({typeDeclaration:e,ir:t}){switch(e.shape.type){case"object":return{...e,shape:{...e.shape,extendedProperties:e.shape.extends.flatMap(r=>Mi_(r,t))}}}return e}function Mi_(e,t){let r=cKs(e.typeId,t);return Ai_({objectTypeDeclaration:r,ir:t})}function cKs(e,t){let r=Di_(e,t.types);switch(r.shape.type){case"object":return r.shape;case"alias":if(r.shape.resolvedType.type==="named")return cKs(r.shape.resolvedType.name.typeId,t)}throw new THr(`Unexpected error: ${e} is extended but has shape ${r.shape.type}`)}function Ai_({objectTypeDeclaration:e,ir:t}){let r=e.extends.flatMap(i=>{let n=cKs(i.typeId,t);return Ai_({objectTypeDeclaration:n,ir:t})});return[...e.properties,...r]}function Ti_({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:kI({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)}}:void 0;return i!==void 0?CN.samePropertiesAsObject(i):void 0},singleProperty:r=>{let i=kI({filteredIr:e,exampleTypeReference:r});return i!==void 0?CN.singleProperty(i):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function kI({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:i=>({...t,shape:mb.container(NO.list({...i,list:i.list.map(n=>kI({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:mb.container(NO.set({...i,set:i.set.map(n=>kI({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?kI({filteredIr:e,exampleTypeReference:i.optional}):void 0;return n!=null?{...t,shape:mb.container(NO.optional({optional:n,valueType:i.valueType}))}:void 0},nullable:i=>{let n=i.nullable!=null?kI({filteredIr:e,exampleTypeReference:i.nullable}):void 0;return n!=null?{...t,shape:mb.container(NO.nullable({nullable:n,valueType:i.valueType}))}:void 0},map:i=>({...t,shape:mb.container(NO.map({...i,map:i.map.map(n=>{let a=kI({filteredIr:e,exampleTypeReference:n.key}),u=kI({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=kI({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:mb.named({...r,shape:Qj.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:mb.named({...r,shape:Qj.enum(i)})}),object:i=>({...t,shape:mb.named({...r,shape:Qj.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:kI({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=Ti_({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:mb.named({...r,shape:Qj.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=kI({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:mb.named({...r,shape:Qj.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function lKs({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=kI({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function fQD({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=kI({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function qi_({filteredIr:e,headers:t}){return t.map(r=>{let i=kI({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function dQD({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=kI({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=kI({filteredIr:e,exampleTypeReference:r});return i!==void 0?y$.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function pQD({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>mq.ok(RT.body(i!=null?kI({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>mq.ok(RT.stream(i.map(n=>kI({filteredIr:e,exampleTypeReference:n})).filter(u0))),sse:i=>mq.ok(RT.sse(i.map(({event:n,data:a})=>{let u=kI({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:n,data:u}:void 0}).filter(u0))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>mq.error({error:r,body:i!=null?kI({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function fKs({filteredIr:e,example:t}){return{...t,rootPathParameters:lKs({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:lKs({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:lKs({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:qi_({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:qi_({filteredIr:e,headers:t.endpointHeaders}),queryParameters:fQD({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?dQD({filteredIr:e,requestBody:t.request}):void 0,response:pQD({filteredIr:e,response:t.response})}}function Ci_({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=kI({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:Qj.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:Qj.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:kI({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=Ti_({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:Qj.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=kI({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:Qj.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}var Pzo=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=Ng.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=Ng.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=Ng.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.name.originalName?this.channels.has(t.name.originalName):!0}hasWebhookPayloadProperty(t,r){let i=this.webhookPayloadProperties[t];return i==null?!0:i.has(r)}};var wzo=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=_QD(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let u=Ng.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=Ng.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=Ng.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&ez(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=Ng.generateServiceId(t.name),a=r.id,u=new Set,l=new Set,d=new Set;for(let s of[...t.headers,...r.headers])ez(s.valueType,u,d);for(let s of[...t.pathParameters,...r.pathParameters])ez(s.valueType,u,d);for(let s of r.queryParameters)ez(s.valueType,u,d);if(i!=null&&i.request!=null&&typeof i.request!="string"){let s=b1n(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:s}}r.requestBody!=null&&Ux._visit(r.requestBody,{inlinedRequestBody:s=>{for(let o of s.extends)jzo(o,u,d);for(let o of s.properties)ez(o.valueType,u,d);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&zT(i.request.body)){let o=b1n(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:s})=>{ez(s,u,d)},fileUpload:({properties:s})=>{for(let o of s)TN._visit(o,{file:Qo,bodyProperty:({valueType:c})=>{ez(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&&Xq._visit(r.response.body,{fileDownload:Qo,json:s=>{ez(s.responseBodyType,u,d)},streaming:s=>{s._visit({sse:o=>ez(o.payload,u,d),json:o=>ez(o.payload,u,d),text:Qo,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.type)}})},streamParameter:s=>{s.streamResponse._visit({sse:o=>ez(o.payload,u,d),json:o=>ez(o.payload,u,d),text:Qo,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.streamResponse.type)}}),s.nonStreamResponse.type==="json"&&ez(s.nonStreamResponse.value.responseBodyType,u,d)},text:Qo,bytes:Qo,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(s=>{l.add(Ng.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=Ng.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)}}addWebhook(t,r,i){let n=r.id;if(n==null)return;let a=new Set,u=new Set;r.payload!=null&&hU._visit(r.payload,{inlinedPayload:l=>{for(let d of l.extends)jzo(d,a,u);for(let d of l.properties)ez(d.valueType,a,u);if(i?.payload!=null&&typeof i.payload=="object"&&!mzo(i.payload)){let d=b1n(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:d}}},reference:({payloadType:l})=>{ez(l,a,u)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),u.add(t.fernFilepath),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.fernFilepath))}addChannel(t,r,i,n){if(r==null)return;let a=new Set,u=new Set;for(let l of i.messages)Xte._visit(l.body,{reference:({bodyType:d})=>{ez(d,a,u)},inlinedBody:d=>{for(let s of d.extends)jzo(s,a,u);for(let s of d.properties)ez(s.valueType,a,u)},_other:()=>{}});u.add(t.fernFilepath),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.fernFilepath))}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 Pzo({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:Ko(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(Ng.generateSubpackageId(i))}}};function _QD(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:Ko(e)}}function ez(e,t,r){nh._visit(e,{container:i=>{hQD(i,t,r)},named:i=>{jzo(i,t,r)},primitive:Qo,unknown:Qo,_other:Qo})}function jzo(e,t,r){t.add(Ng.generateTypeId(e)),r.add(e.fernFilepath)}function hQD(e,t,r){Tg._visit(e,{list:i=>{ez(i,t,r)},map:i=>{ez(i.keyType,t,r),ez(i.valueType,t,r)},optional:i=>{ez(i,t,r)},nullable:i=>{ez(i,t,r)},set:i=>{ez(i,t,r)},literal:Qo,_other:Qo})}function Bi_({reference:e,referencedIn:t,imports:r}){let[i,n,...a]=e.split(".");if(i==null||a.length>0)return;if(n==null)return{endpointName:i,relativeFilepath:t};let l=r[i];if(l!=null)return{endpointName:n,relativeFilepath:Wfi({referencedIn:t,importPath:l})}}var Jzi=class{workspace;constructor(t){this.workspace=t}resolveEndpointOrThrow({endpoint:t,file:r}){let i=this.resolveEndpoint({endpoint:t,file:r});if(i==null)throw new Error("Cannot resolve endpoint: "+t+" in file "+r.relativeFilepath);return i}resolveEndpointByMethodAndPath({method:t,path:r}){let i;return XN(this.workspace,(n,a,u)=>{let l=Hb({relativeFilepath:n,definitionFile:a,casingsGenerator:$fi,rootApiFile:this.workspace.definition.rootApiFile.contents,defaultUrl:u.defaultUrl});for(let[d,s]of Object.entries(a.service?.endpoints??{}))s.method===t&&s.path===r&&(i={endpointId:d,endpoint:s,file:l})}),CIi(this.workspace,(n,a)=>{let u=Hb({relativeFilepath:n,definitionFile:a,casingsGenerator:$fi,rootApiFile:this.workspace.definition.rootApiFile.contents});for(let[l,d]of Object.entries(a.service?.endpoints??{}))d.method===t&&d.path===r&&(i={endpointId:l,endpoint:d,file:u})}),i}resolveEndpoint({endpoint:t,file:r}){let n=new fTi().tryParse(t);if(n!=null)return this.resolveEndpointByMethodAndPath(n);let a=this.getDeclarationOfEndpoint({referenceToEndpoint:t,file:r});if(a==null)return;let u=a.file.definitionFile.service?.endpoints?.[a.endpointName];if(u!=null)return{endpointId:a.endpointName,endpoint:u,file:a.file}}getDeclarationOfEndpoint({referenceToEndpoint:t,file:r}){let i=Bi_({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=aie(this.workspace,i.relativeFilepath);if(!(n==null||n.service?.endpoints?.[i.endpointName]==null))return{endpointName:i.endpointName,file:Hb({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var Kzi=class{workspace;constructor(t){this.workspace=t}getDeclarationOrThrow(t,r){let i=this.getDeclaration(t,r);if(i==null)throw new Error("Error does not exist: "+t);return i}getDeclaration(t,r){let i=PSe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=aie(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.errors?.[i.typeName];if(a!=null)return{declaration:a,file:Hb({definitionFile:n,relativeFilepath:i.relativeFilepath,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var wSe=class{typeResolver;constructor(t){this.typeResolver=t}resolveAllReferencesInExample({example:t,file:r}){if(typeof t=="string"){let i=this.resolveExample({example:t,file:r});return i==null||typeof i.resolvedExample=="string"?i:this.resolveAllReferencesInExample({example:i.resolvedExample,file:i.file})}else if(Hj(t)){let i={};for(let[n,a]of Object.entries(t)){let u=this.resolveAllReferencesInExample({example:a,file:r});if(u==null)return;i[n]=u.resolvedExample}return{resolvedExample:i}}else if(Array.isArray(t)){let i=[];for(let n of t){let a=this.resolveAllReferencesInExample({example:n,file:r});if(a==null)return;i.push(a.resolvedExample)}return{resolvedExample:i}}return{resolvedExample:t}}resolveAllReferencesInExampleOrThrow({example:t,file:r}){let i=this.resolveAllReferencesInExample({example:t,file:r});if(i==null)throw new Error("Failed to resolve examples");return i}resolveExample({example:t,file:r}){if(typeof t!="string")return{resolvedExample:t,file:r};if(t.startsWith(`\\${NGt}`))return{resolvedExample:t.slice(1),file:r};if(!t.startsWith(NGt))return{resolvedExample:t,file:r};let i=this.parseExampleReference(t);if(i==null)return;let n=this.typeResolver.getDeclarationOfNamedType({referenceToNamedType:i.rawTypeReference,file:r});if(n==null||typeof n.declaration=="string"||n.declaration.examples==null)return;let a=n.declaration.examples.find(u=>u.name===i.exampleName);if(a!=null)return this.resolveExample({example:a.value,file:n.file})}resolveExampleOrThrow({example:t,file:r}){let i=this.resolveExample({example:t,file:r});if(i==null)throw new Error("Cannot resolve example: "+t);return i}parseExampleReference(t){let[r,i,n,...a]=t.split(".");if(!(r==null||i==null||a.length>0))return n==null?{rawTypeReference:r.slice(NGt.length),exampleName:i}:{rawTypeReference:`${r}.${i}`.slice(NGt.length),exampleName:n}}};var Szo=class{typeResolver;endpointResolver;constructor(t,r){this.typeResolver=t,this.endpointResolver=r,this.typeResolver=t,this.endpointResolver=r}resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:i}){let n=this.resolveRequestProperty({file:t,endpoint:r,propertyComponents:i});if(n==null)throw new Error("Cannot resolve request property from endpoint: "+r+" in file "+t.relativeFilepath);return n}resolveRequestProperty({file:t,endpoint:r,propertyComponents:i}){let n=this.endpointResolver.resolveEndpointOrThrow({endpoint:r,file:t});if(n.endpoint.request==null)return;if(typeof n.endpoint.request!="string")return this.resolveRequestPropertyFromInlinedRequest({typeResolver:this.typeResolver,file:n.file,requestType:n.endpoint.request,propertyComponents:i});let a=this.resolveObjectProperty({file:n.file,typeName:n.endpoint.request,propertyComponents:i});if(a!=null)return{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:i,file:t}),property:Kte.body(a)}}resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i}){let n=this.resolveResponseProperty({file:t,endpoint:r,propertyComponents:i});if(n==null)throw new Error("Cannot resolve response property from endpoint: "+r+" in file "+t.relativeFilepath);return n}resolveResponseProperty({file:t,endpoint:r,propertyComponents:i}){let n=this.endpointResolver.resolveEndpointOrThrow({endpoint:r,file:t}),a=this.resolveObjectProperty({file:n.file,typeName:(typeof n.endpoint.response!="string"?n.endpoint.response?.type:n.endpoint.response)??"",propertyComponents:i});if(a!=null)return{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:i,file:t}),property:a}}resolveRequestPropertyFromInlinedRequest({typeResolver:t,file:r,requestType:i,propertyComponents:n}){if(n.length===1){let a=n[0]??"",u=i["query-parameters"]?.[a]??void 0;if(u!=null)return{property:Kte.query(hzo({file:r,queryParameterKey:a,queryParameter:u})),propertyPath:void 0}}return this.resolveRequestPropertyFromInlinedRequestBody({typeResolver:t,file:r,requestType:i,propertyComponents:n})}resolveRequestPropertyFromInlinedRequestBody({typeResolver:t,file:r,requestType:i,propertyComponents:n}){if(i.body==null)return;if(typeof i.body=="string"){let u=this.resolveObjectProperty({file:r,typeName:i.body,propertyComponents:n});return u==null?void 0:{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:Kte.body(u)}}if(zT(i.body)){let u=kJs({typeResolver:t,file:r,objectSchema:i.body,propertyComponents:n});return u==null?void 0:{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:Kte.body(u)}}let a=this.resolveObjectProperty({file:r,typeName:i.body.type,propertyComponents:n});if(a!=null)return{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:Kte.body(a)}}resolveObjectProperty({file:t,typeName:r,propertyComponents:i}){let n=this.typeResolver.resolveTypeOrThrow({type:r,file:t});return ZJs({typeResolver:this.typeResolver,file:I_a(n)??t,resolvedType:n,propertyComponents:i})}propertyPathFromPropertyComponents({propertyComponents:t,file:r}){return t.length<=1?[]:t.slice(0,-1).map(i=>r.casingsGenerator.generateName(i))}};var t1=class{workspace;constructor(t){this.workspace=t}resolveTypeOrThrow({type:t,file:r}){let i=this.resolveType({type:t,file:r});if(i==null)throw new Error("Cannot resolve type: "+t+" in file "+r.relativeFilepath);return i}getDeclarationOfNamedTypeOrThrow({referenceToNamedType:t,file:r}){let i=this.getDeclarationOfNamedType({referenceToNamedType:t,file:r});if(i==null)throw new Error("Cannot find declaration of type: "+t+" in file "+r.relativeFilepath);return i}getDeclarationOfNamedType({referenceToNamedType:t,file:r}){let i=PSe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=aie(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.types?.[i.typeName];if(a==null){let u=RI(i.typeName);if(u!=null){for(let l of Object.keys(n.types??{})??[])if(u.name&&l.startsWith(u.name)&&l.endsWith(">")){let d=n.types?.[l];return d!=null?{typeName:l,declaration:d,file:Hb({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}:void 0}}return}return{typeName:i.typeName,declaration:a,file:Hb({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}resolveType({type:t,file:r,objectPath:i=[]}){return yU({type:t,_default:void 0,validation:void 0,visitor:{primitive:n=>({_type:"primitive",primitive:n,originalTypeReference:nh.primitive(n)}),unknown:()=>({_type:"unknown",originalTypeReference:nh.unknown()}),map:({keyType:n,valueType:a})=>n!=null&&a!=null?{_type:"container",container:{_type:"map",keyType:n,valueType:a},originalTypeReference:nh.container(Tg.map({keyType:n.originalTypeReference,valueType:a.originalTypeReference}))}:void 0,list:n=>n!=null?{_type:"container",container:{_type:"list",itemType:n},originalTypeReference:nh.container(Tg.list(n.originalTypeReference))}:void 0,optional:n=>n!=null?{_type:"container",container:{_type:"optional",itemType:n},originalTypeReference:nh.container(Tg.optional(n.originalTypeReference))}:void 0,nullable:n=>n!=null?{_type:"container",container:{_type:"nullable",itemType:n},originalTypeReference:nh.container(Tg.nullable(n.originalTypeReference))}:void 0,set:n=>n!=null?{_type:"container",container:{_type:"set",itemType:n},originalTypeReference:nh.container(Tg.set(n.originalTypeReference))}:void 0,literal:n=>({_type:"container",container:{_type:"literal",literal:n},originalTypeReference:nh.container(Tg.literal(n))}),named:n=>{let a=this.getDeclarationOfNamedType({referenceToNamedType:n,file:r});if(a==null)return;let u={typeName:a.typeName,file:a.file.relativeFilepath,reference:n};if(!i.some(l=>l.file===u.file&&l.typeName===u.typeName))return this.resolveNamedTypeFromDeclaration({referenceToNamedType:n,referencedIn:r,rawDeclaration:a,objectPath:[...i,u]})}}})}resolveNamedTypeOrThrow({referenceToNamedType:t,file:r}){let i=this.resolveNamedType({referenceToNamedType:t,file:r});if(i==null)throw new Error("Cannot resolve type: "+t);return i}resolveNamedType({referenceToNamedType:t,file:r}){let i=this.getDeclarationOfNamedType({referenceToNamedType:t,file:r});if(i!=null)return this.resolveNamedTypeFromDeclaration({referenceToNamedType:t,referencedIn:r,rawDeclaration:i})}resolveNamedTypeFromDeclaration({referenceToNamedType:t,referencedIn:r,rawDeclaration:i,objectPath:n=[]}){let{declaration:a,file:u}=i;if(Foi(a))return this.resolveType({type:typeof a=="string"?a:a.type,file:u,objectPath:n});let l=R_a({type:t,_default:void 0,validation:void 0,file:r});if(!(l.type!=="named"||aie(this.workspace,u.relativeFilepath)==null))return{_type:"named",rawName:i.typeName,name:l,declaration:a,filepath:u.relativeFilepath,objectPath:n,originalTypeReference:l,file:u}}};var y5t=class e{static VARIABLE_PREFIX="$";getDeclarationOrThrow(t,r){let i=this.getDeclaration(t,r);if(i==null)throw new Error("Variable does not exist: "+t);return i}getDeclaration(t,r){if(!t.startsWith(e.VARIABLE_PREFIX))return;let i=r.rootApiFile.variables?.[t.substring(1)];if(i!=null)return{declaration:i,file:NQr({casingsGenerator:r.casingsGenerator,rootApiFile:r.rootApiFile})}}getVariableIdOrThrow(t){let r=this.getVariableId(t);if(r==null)throw new Error("Variable reference does not start with "+e.VARIABLE_PREFIX);return r}getVariableId(t){if(t.startsWith(e.VARIABLE_PREFIX))return t.substring(e.VARIABLE_PREFIX.length)}};function Dzo(e,t){if(t){for(let[r,i]of Object.entries(t))if(typeof i!="string"&&r===e)return i.audiences}}function _2({workspace:e,generationLanguage:t,keywords:r,smartCasing:i,exampleGeneration:n,audiences:a,readme:u,packageName:l,version:d,context:s,fdrApiDefinitionId:o,sourceResolver:c,includeDynamicExamples:b}){let g=i5t({generationLanguage:t,keywords:r,smartCasing:i}),O=new wzo(a),m=NQr({casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents}),w=(e.definition.rootApiFile.contents.errors??[]).map(st=>({error:Hfi({errorName:st,file:m}),docs:void 0})),E=new t1(e),A=new Jzi(e),q=new Szo(E,A),D=new Kzi(e),C=new wSe(E),R=new y5t,$={fdrApiDefinitionId:o,apiVersion:fi_({file:m,rawApiFileSchema:e.definition.rootApiFile.contents}),apiName:g.generateName(e.definition.rootApiFile.contents.name),apiDisplayName:e.definition.rootApiFile.contents["display-name"],apiDocs:C_a(e.definition.rootApiFile.contents.docs),auth:li_({rawApiFileSchema:e.definition.rootApiFile.contents,file:m,propertyResolver:q,endpointResolver:A}),headers:e.definition.rootApiFile.contents.headers!=null?Object.entries(e.definition.rootApiFile.contents.headers).map(([st,ye])=>rze({headerKey:st,header:ye,file:m})):[],idempotencyHeaders:e.definition.rootApiFile.contents["idempotency-headers"]!=null?Object.entries(e.definition.rootApiFile.contents["idempotency-headers"]).map(([st,ye])=>rze({headerKey:st,header:ye,file:m})):[],types:{},errors:{},services:{},constants:kr_(g),environments:aKs({casingsGenerator:g,rawApiFileSchema:e.definition.rootApiFile.contents}),errorDiscriminationStrategy:yi_(e.definition.rootApiFile.contents["error-discrimination"],m),basePath:e.definition.rootApiFile.contents["base-path"]!=null?iV(e.definition.rootApiFile.contents["base-path"]):void 0,pathParameters:v1n({pathParameters:e.definition.rootApiFile.contents["path-parameters"],file:m,location:PBe.Root,variableResolver:R}),variables:e.definition.rootApiFile.contents.variables!=null?Object.entries(e.definition.rootApiFile.contents.variables).map(([st,ye])=>({docs:typeof ye!="string"?ye.docs:void 0,id:st,name:m.casingsGenerator.generateName(st),type:m.parseTypeReference(ye)})):[],serviceTypeReferenceInfo:{typesReferencedOnlyByService:{},sharedTypes:[]},webhookGroups:{},websocketChannels:{},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0},I=new gzo,U=st=>{I.addSubpackage(st.fernFilepath),Wj(st.definitionFile,{imports:Qo,docs:ye=>{ye!=null&&I.addDocs(st.fernFilepath,ye)},types:ye=>{if(ye!=null)for(let[Pe,Ot]of Object.entries(ye)){if(OBe(Pe))continue;let wt=Si_({typeName:Pe,typeDeclaration:Ot,file:st,typeResolver:E,exampleResolver:C,sourceResolver:c,workspace:e}),sr=wt.typeDeclaration;n.disabled&&(sr.userProvidedExamples=[],sr.autogeneratedExamples=[]);let ur=wt.descendantFilepaths,ni=Ng.generateTypeId(sr.name);$.types[ni]=sr,I.addType(ni,sr),O.addType({declaredTypeName:sr.name,descendantTypeIds:sr.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:wt.propertiesByAudience,descendantFilepaths:ur}),O.markTypeForAudiences(sr.name,nr_(Ot))}},errors:ye=>{if(ye==null)return;if(e.definition.rootApiFile.contents["error-discrimination"]==null)throw new Error("error-discrimination is missing in api.yml but there are declared errors.");for(let[Ot,wt]of Object.entries(ye)){let sr=_i_({errorName:Ot,errorDeclaration:wt,file:st,typeResolver:E,exampleResolver:C,workspace:e}),ur=Ng.generateErrorId(sr.name);$.errors[ur]=sr,I.addError(ur,sr),O.addError(sr)}},service:ye=>{if(ye==null)return;let Pe=Kr_({rootDefaultUrl:st.defaultUrl??e.definition.rootApiFile.contents["default-url"],rootPathParameters:$.pathParameters,serviceDefinition:ye,file:st,errorResolver:D,typeResolver:E,propertyResolver:q,exampleResolver:C,sourceResolver:c,globalErrors:w,variableResolver:R,workspace:e}),Ot=Ng.generateServiceId(Pe.name);$.services[Ot]=Pe,I.addService(Ot,Pe);let wt={};Pe.endpoints.forEach(sr=>{n.disabled&&(sr.autogeneratedExamples=[],sr.userSpecifiedExamples=[]);let ur=ye.endpoints[sr.name.originalName];O.addEndpoint(Pe,sr,ur),wt[sr.name.originalName]=sr}),ye.audiences!=null&&O.markEndpointForAudience(Pe.name,Pe.endpoints,ye.audiences),Object.entries(ye.endpoints).map(([sr,ur])=>{let ni=wt[sr];ni!=null&&ur.audiences!=null&&O.markEndpointForAudience(Pe.name,[ni],ur.audiences)})},webhooks:ye=>{if(ye==null)return;let Pe=Ng.generateWebhookGroupId(st.fernFilepath),Ot=bi_({webhooks:ye,file:st,typeResolver:E,exampleResolver:C,workspace:e}),wt={};for(let sr of Ot)wt[sr.name.originalName]=sr;Object.entries(ye).forEach(([sr,ur])=>{let ni=wt[sr];ni!=null&&(O.addWebhook(st,ni,ur),ur.audiences!=null&&O.markWebhookForAudiences(st,ni,ur.audiences))}),$.webhookGroups[Pe]=Ot,I.addWebhookGroup(Pe,st.fernFilepath)},channel:ye=>{if(ye==null)return;let Pe=Ng.generateWebSocketChannelId(st.fernFilepath),Ot=di_({channel:ye,file:st,variableResolver:R,typeResolver:E,exampleResolver:C,workspace:e});O.addChannel(st,Pe,Ot,ye),ye.audiences!=null&&O.markChannelForAudiences(st,Pe,ye.audiences),$.websocketChannels!=null&&($.websocketChannels[Pe]=Ot,I.addWebSocketChannel(Pe,st.fernFilepath))}})};XN(e,(st,ye,Pe)=>{U(Hb({relativeFilepath:st,definitionFile:ye,casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents,defaultUrl:Pe.defaultUrl}))}),CIi(e,(st,ye)=>{if(ye.navigation!=null)if(typeof ye.navigation=="string")I.addPackageRedirection({from:_ie({relativeFilepath:st,casingsGenerator:g}),to:_ie({relativeFilepath:sR(UCe(st),ry.of(ye.navigation)),casingsGenerator:g})});else{let Pe=ye.navigation.map(Ot=>Ng.generateSubpackageId(_ie({relativeFilepath:sR(UCe(st),ry.of(Ot)),casingsGenerator:g})));st===W1?I.sortRootPackage(Pe):I.sortSubpackage(Ng.generateSubpackageId(_ie({relativeFilepath:st,casingsGenerator:g})),Pe)}}),$.serviceTypeReferenceInfo=vQD(O);let H=n.disabled?$:fpa({ir:$,exampleGeneration:n}),k=e.definition.rootApiFile.contents,K=aKs({casingsGenerator:g,rawApiFileSchema:k}),te=K?.environments._visit({singleBaseUrl:st=>st.environments.filter(ye=>Dzo(ye.id,k.environments)!=null).length===0,multipleBaseUrls:st=>st.environments.filter(ye=>Dzo(ye.id,k.environments)!=null).length===0,_other:()=>!1});K?.environments.environments.forEach(st=>{O.markEnvironmentForAudiences(st,Dzo(st.id,k.environments)??[],te)});let fe=O.hasNoAudiences()?void 0:O.build(),me=bQD(H,fe),be=e.definition.rootApiFile.contents.auth!=null&&Object.values(me.services).every(st=>st.endpoints.every(ye=>ye.auth)),we=Object.values(me.services).some(st=>st.endpoints.some(ye=>ye.response?.body?.type==="streaming")),Ze=Object.values(me.services).some(st=>st.endpoints.some(ye=>ye.pagination!=null)),Mt=Object.values(me.services).some(st=>st.endpoints.some(ye=>ye.response?.body?.type==="fileDownload")),De={isAuthMandatory:be,hasStreamingEndpoints:we,hasPaginatedEndpoints:Ze,hasFileDownloadEndpoints:Mt,platformHeaders:{language:"X-Fern-Language",sdkName:"X-Fern-SDK-Name",sdkVersion:"X-Fern-SDK-Version",userAgent:d!=null&&l!=null?{header:"User-Agent",value:`${l}/${d}`}:void 0}},Te=u!=null?vi_({readme:u,services:$.services}):void 0,{types:xt,services:Ee}=Ei_(me),It=yQD({...me,...I.build(fe),types:xt,services:Ee,sdkConfig:De,readmeConfig:Te});return{...It,dynamic:Xr_({ir:It,includeExamples:b})}}function yQD(e){let t=r=>{if(!r||typeof r!="object")return r;if(Array.isArray(r))return r.map(t);for(let i in r){let n=r[i];i==="docs"&&typeof n=="string"?r[i]=C_a(n):n&&typeof n=="object"&&t(n)}return r};return t(e)}function vQD(e){let t={},r=[],i=e.getTypesReferencedByService();for(let[n,a]of Object.entries(i)){if(a.size===1){let u=a.values().next().value;if(u==null)break;t[u]===void 0&&(t[u]=[]),t[u]?.push(n);continue}r.push(n)}return{typesReferencedOnlyByService:t,sharedTypes:r}}function bQD(e,t){if(t==null)return e;let r=gAi(e.types,u=>t.hasType(u)),i=Object.fromEntries(Object.entries(r).map(([u,l])=>{let d=[];if(l.userProvidedExamples=l.userProvidedExamples.map(s=>Ci_({filteredIr:t,exampleType:s})).filter(s=>s!==void 0),l.shape.type==="object"){for(let s of l.shape.properties)t.hasProperty(u,s.name.wireValue)&&d.push(s);return[u,{...l,shape:Gj.object({...l.shape,properties:d})}]}return[u,l]})),n=Object.fromEntries(Object.entries(e.webhookGroups).map(([u,l])=>{let d=l.filter(s=>t.hasWebhook(s)).map(s=>{let o=s.id;return s.payload.type==="inlinedPayload"&&o!=null&&(s.payload={...s.payload,properties:s.payload.properties.filter(c=>t.hasWebhookPayloadProperty(o,c.name.wireValue))}),s});return[u,d]})),a=e.environments;if(a){switch(a.environments.type){case"singleBaseUrl":{a.environments.environments=a.environments.environments.filter(u=>t.hasEnvironmentId(u.id));break}case"multipleBaseUrls":{a.environments.environments=a.environments.environments.filter(u=>t.hasEnvironmentId(u.id));break}}a.defaultEnvironment&&(t.hasEnvironmentId(a.defaultEnvironment)||(a.defaultEnvironment=void 0))}return{...e,environments:a,types:i,errors:gAi(e.errors,u=>t.hasError(u)),services:od(gAi(e.services,u=>t.hasService(u)),u=>({...u,endpoints:u.endpoints.filter(l=>t.hasEndpoint(l)).map(l=>(l.autogeneratedExamples=l.autogeneratedExamples.map(d=>({...d,example:fKs({filteredIr:t,example:d.example})})),l.userSpecifiedExamples=l.userSpecifiedExamples.map(d=>({...d,example:d.example!=null?fKs({filteredIr:t,example:d.example}):void 0})),l.queryParameters.length>0&&(l.queryParameters=l.queryParameters.filter(d=>t.hasQueryParameter(l.id,d.name.wireValue))),l.requestBody?.type==="inlinedRequestBody"?{...l,requestBody:{...l.requestBody,properties:l.requestBody.properties.filter(d=>t.hasRequestProperty(l.id,d.name.wireValue))}}:l))})),webhookGroups:n,serviceTypeReferenceInfo:gQD(e.serviceTypeReferenceInfo,t)}}function gQD(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}}function xi_(e){throw new Error("Unexpected value: "+JSON.stringify(e))}var zi_=vi(wkn(),1);var Ii_=["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 v5t(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,zi_.default)(e,{special:Ii_}).replace(/V\s(\d)/g,"V$1")}function U_a(e,t="type"){return{_visit:r=>{let i=r[e[t]];return i!=null?i(e):(r._other==null&&xi_(e),r._other(e))}}}function aXt(e){return typeof e.subpackageId=="string"}function TC(e){return e.map(t=>t.type==="literal"?t.value:`{${t.value}}`).join("")}function ize(e){return e.map(t=>t.type==="literal"?t.value:`:${t.value}`).join("")}var dKs="__package__",Qfi=class e{api;context;static create(t,r){return new e(t,r)}#e=new Map;#t=new Map;#r=new Map;#n=new Map;#i=new Map;#a=new Map;#o=new Map;#c=new Map;#l=new Map;#u=new Map;#s=new Map;static getSubpackageId(t){return aXt(t)?t.subpackageId:dKs}getSubpackageByIdOrLocator(t){if(t==null)return;let r=p2.SubpackageId(t);return r===dKs?this.api.rootPackage:this.api.subpackages[r]??this.#s.get(r)}resolveSubpackage(t){if(t!=null){for(;t?.pointsTo!=null;)t=this.api.subpackages[t.pointsTo];return t}}constructor(t,r){this.api=t,this.context=r,[t.rootPackage,...Object.values(t.subpackages)].forEach(i=>{let n=p2.SubpackageId(e.getSubpackageId(i)),a={endpoints:new Map,webSockets:new Map,webhooks:new Map};this.#o.set(n,a),i.endpoints.forEach(u=>{a.endpoints.set(u.id,u);let l=e.createEndpointId(u,n);this.#e.set(l,u);let d=[],s=[u.method];u.response?.type.type==="stream"&&s.push("STREAM"),s.forEach(o=>{d.push(`${o} ${TC(u.path.parts)}`),d.push(`${o} ${ize(u.path.parts)}`),u.environments.forEach(c=>{d.push(`${o} ${Cv(c.baseUrl,TC(u.path.parts))}`),d.push(`${o} ${Cv(c.baseUrl,ize(u.path.parts))}`);let b=Ezo(c);b!=null&&(d.push(`${o} ${Cv(b,TC(u.path.parts))}`),d.push(`${o} ${Cv(b,ize(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.trace(`Registering endpoint locator: ${o}`),this.#c.set(o,u)})}),i.websockets.forEach(u=>{a.webSockets.set(u.id,u);let l=e.createWebSocketId(u,n);this.#t.set(l,u);let d=[];["GET","WSS"].forEach(o=>{d.push(`${o} ${TC(u.path.parts)}`),d.push(`${o} ${ize(u.path.parts)}`),u.environments.forEach(c=>{d.push(`${o} ${Cv(c.baseUrl,TC(u.path.parts))}`),d.push(`${o} ${Cv(c.baseUrl,ize(u.path.parts))}`);let b=Ezo(c);b!=null&&(d.push(`${o} ${Cv(b,TC(u.path.parts))}`),d.push(`${o} ${Cv(b,ize(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.trace(`Registering websocket locator: ${o}`),this.#l.set(o,u)})}),i.webhooks.forEach(u=>{a.webhooks.set(u.id,u),this.#r.set(e.createWebhookId(u,n),u)})}),this.#e.forEach((i,n)=>{this.#n.set(i,n)}),this.#t.forEach((i,n)=>{this.#i.set(i,n)}),this.#r.forEach((i,n)=>{this.#a.set(i,n)}),this.#f(t.rootPackage,[])}#f(t,r){if(t==null)return;let i=aXt(t)?[...r,t.name]:r,n=i.length===0?[dKs]:i;if([n.join("."),n.join("/"),`${n.join(".")}.yml`].forEach(u=>{this.context?.logger.trace(`Registering subpackage locator: ${u}`),this.#s.set(u,t)}),t.pointsTo!=null)return this.#f(this.api.subpackages[t.pointsTo],i);t.endpoints.forEach(u=>{let l=[...i,u.id];[l.join("."),l.join("/")].forEach(s=>{this.context?.logger.trace(`Registering endpoint locator: ${s}`),this.#c.set(s,u)})}),t.websockets.forEach(u=>{let l=[...i,u.id];[l.join("."),l.join("/")].forEach(s=>{this.context?.logger.trace(`Registering websocket locator: ${s}`),this.#l.set(s,u)})}),t.webhooks.forEach(u=>{let l=[...i,u.id];[l.join("."),l.join("/")].forEach(s=>{this.context?.logger.trace(`Registering webhook locator: ${s}`),this.#u.set(s,u)})}),t.subpackages.forEach(u=>{this.#f(this.api.subpackages[u],i)})}get endpoints(){return this.#e}get webSockets(){return this.#t}get webhooks(){return this.#r}get endpointsByLocator(){return this.#c}get webSocketsByLocator(){return this.#l}get webhooksByLocator(){return this.#u}get subpackages(){return this.#o}get subpackagesByLocator(){return this.#s}getEndpointId(t){return this.#n.get(t)}getWebSocketId(t){return this.#i.get(t)}getWebhookId(t){return this.#a.get(t)}static createEndpointId(t,r){return zo.EndpointId(t.originalEndpointId??`${r}.${t.id}`)}static createWebSocketId(t,r){return zo.WebSocketId(`${r}.${t.id}`)}static createWebhookId(t,r){return zo.WebhookId(`${r}.${t.id}`)}};function Ezo(e){if(e!=null){if(e.baseUrl.startsWith("/"))return e.baseUrl;if(e.baseUrl.startsWith("http")||e.baseUrl.startsWith("ws"))try{return new URL(e.baseUrl).pathname}catch{return}}}var g1n=vi(pIo(),1),Ni_=vi(_Io(),1);function Ri_(e){let t=e.split(".")[0];if(t==null)return;let i=/(^\d{1,4})-(\d{1,2})-(\d{1,4})/.exec(t)?.[0];if(i!=null)try{return new Date(i)}catch{}}g1n.default.extend(Ni_.default);var OQD="Changelog",mQD=["summary","index","overview"],LQr=class{markdownToFullSlug;markdownToNoIndex;changelogFiles;docsWorkspace;idgen;constructor(t,r,i,n,a){this.markdownToFullSlug=t,this.markdownToNoIndex=r,this.changelogFiles=i,this.docsWorkspace=n,this.idgen=a}toChangelogNode(t){let r=t.title??OQD,i=[],n;for(let b of this.changelogFiles??[]){let g=Bus(b.split("/"));if(g==null)continue;let O=Ri_(g);if(O==null){let w=g.split(".")[0]?.toLowerCase();w!=null&&mQD.includes(w)&&(n=b);continue}let m=this.toRelativeFilepath(b);i.push({date:O,pageId:zo.PageId(m),absoluteFilepath:b})}let a=t.parentSlug.apply({fullSlug:n!=null?this.markdownToFullSlug.get(n)?.split("/"):void 0,skipUrlSlug:!1,urlSlug:t.slug??Oq(r)}),u=n!=null?this.markdownToNoIndex.get(n):void 0,l=i.map(b=>{let g=g1n.default.utc(b.date);return{id:this.idgen.get(b.pageId),type:"changelogEntry",title:g.format("MMMM D, YYYY"),slug:a.apply({fullSlug:this.markdownToFullSlug.get(b.absoluteFilepath)?.split("/"),urlSlug:g.format("YYYY/M/D")}).get(),icon:void 0,hidden:void 0,date:b.date.toISOString(),pageId:b.pageId,noindex:this.markdownToNoIndex.get(b.absoluteFilepath),authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}),d=pKs(l,b=>b.date,"desc"),s=n!=null?zo.PageId(this.toRelativeFilepath(n)):void 0,o=this.idgen.get(s??"changelog"),c=this.groupByYear(o,d,a);return{id:o,type:"changelog",title:r,slug:a.get(),icon:t.icon,hidden:t.hidden,children:c,overviewPageId:s,noindex:u,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:void 0}}orUndefined(){return this.changelogFiles!=null&&this.changelogFiles.length>0?this:void 0}groupByYear(t,r,i){let n=new Map;for(let a of r){let u=g1n.default.utc(a.date).year(),l=n.get(u)??[];l.push(a),n.set(u,l)}return pKs(Array.from(n.entries()).map(([a,u])=>{let l=i.append(a.toString()).get(),d=this.idgen.get(`${t}/year/${a}`);return{id:d,type:"changelogYear",title:a.toString(),year:a,slug:l,icon:void 0,hidden:void 0,children:this.groupByMonth(d,u,i),authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}),"year","desc")}groupByMonth(t,r,i){let n=new Map;for(let a of r){let u=g1n.default.utc(a.date).month()+1,l=n.get(u)??[];l.push(a),n.set(u,l)}return pKs(Array.from(n.entries()).map(([a,u])=>{let l=(0,g1n.default)(new Date(0,a-1));return{id:this.idgen.get(`${t}/month/${a}`),type:"changelogMonth",title:l.format("MMMM YYYY"),month:a,slug:i.append(a.toString()).get(),icon:void 0,hidden:void 0,children:u,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}),"month","desc")}toRelativeFilepath(t){if(t!=null)return Qq(this.docsWorkspace.absoluteFilePath,t)}};function pKs(e,t,r="asc"){return e.concat().sort((i,n)=>{let a=typeof t=="function"?t(i):i[t],u=typeof t=="function"?t(n):n[t];return a<u?r==="asc"?-1:1:a>u?r==="asc"?1:-1:0})}function Mzo(e){if(e)return{disabled:void 0,environments:e.environments!=null&&e.environments.length>0?e.environments.map(t=>zo.V1.EnvironmentId(t)):void 0,button:e.button!=null&&e.button.href?{href:zo.V1.Url(e.button.href)}:void 0,"limit-websocket-messages-per-connection":e.limitWebsocketMessagesPerConnection!=null?e.limitWebsocketMessagesPerConnection:void 0}}function V_a({child:e,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i}){if(e.type==="apiPackage"){let n=zo.V1.SlugGenerator.init(e.slug),u=(t.get(e.id)??[]).flatMap(s=>r(s,n)),l=e.children.map(s=>V_a({child:s,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i})),d=i(l,u);return{...e,children:d,pointsTo:void 0}}return e}function O1n({children:e,findEndpointById:t,stringifyEndpointPathParts:r,disableEndpointPairs:i,apiDefinitionId:n}){if(i)return e;let a=[],u=new Map;return e.forEach(l=>{if(l.type!=="endpoint"){a.push(l);return}let d=t(l.endpointId);if(d==null)throw new Error(`Endpoint ${l.endpointId} not found`);let s=`${d.method} ${r(d)}`,o=u.get(s);if(u.set(s,l),o==null||o.isResponseStream===l.isResponseStream){a.push(l);return}let c=a.indexOf(o),b=l.isResponseStream?l:o,g=l.isResponseStream?o:l,O={id:zo.V1.NodeId(`${n}:${g.endpointId}+${b.endpointId}`),type:"endpointPair",stream:b,nonStream:g};a[c]=O}),a}function Azo({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}){return O1n({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}).filter(u=>u.type==="apiPackage"?u.children.length>0:!0)}function oXt(e,t){if(t!=null)return Qq(e.absoluteFilePath,t)}function qzo({docsWorkspace:e,page:t,parentSlug:r,idgen:i,markdownFilesToFullSlugs:n,markdownFilesToNoIndex:a,hideChildren:u}){let l=zo.V1.PageId(oXt(e,t.absolutePath)),d=r.apply({fullSlug:n.get(t.absolutePath)?.split("/"),urlSlug:t.slug??Oq(t.title)});return{id:i.get(l),type:"page",pageId:l,title:t.title,slug:d.get(),icon:t.icon,hidden:u||t.hidden,noindex:t.noindex||a.get(t.absolutePath),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}var Tzo=class{apiSection;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;workspace;hideChildren;apiDefinitionId;#e;#t=new Set;#r=new Set;#n=new Set;#i=new Set;#a=new Map;#o=[];#c;#l;#u;disableEndpointPairs;constructor(t,r,i,n,a,u,l,d,s,o){this.apiSection=t,this.docsWorkspace=n,this.taskContext=a,this.markdownFilesToFullSlugs=u,this.markdownFilesToNoIndex=l,this.workspace=s,this.hideChildren=o,this.disableEndpointPairs=n.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=zo.V1.ApiDefinitionId(r.id),this.#e=Qfi.create(r,a),this.#u=d,this.#c=this.apiSection.overviewAbsolutePath!=null?zo.V1.PageId(oXt(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let c=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#l=i.apply({fullSlug:c?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??Oq(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#o=this.#s(this.apiSection.navigation,this.#e.api.rootPackage,this.#l)),this.#o=this.#y(this.#o.map(b=>this.#g(b)),this.#j(this.#e.api.rootPackage,this.#l))}get(){let t=zo.V1.followRedirects(this.#o),r=new LQr(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#u).orUndefined();return{id:this.#u.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#c,paginated:this.apiSection.paginated,slug:this.#l.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#l,viewers:void 0,hidden:this.hideChildren}),children:this.#o,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#O(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#s(t,r,i){r=this.#e.resolveSubpackage(r);let n=r!=null?Qfi.getSubpackageId(r):void 0;return t.map(a=>U_a(a)._visit({link:u=>({id:this.#u.get(u.url),type:"link",title:u.text,icon:u.icon,url:zo.Url(u.url)}),page:u=>this.#f(u,i),package:u=>this.#h(u,i),section:u=>this.#_(u,i),item:({value:u})=>this.#p(u,n,i),endpoint:u=>this.#b(u,n,i)})).filter(u0)}#f(t,r){return qzo({page:t,parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex,idgen:this.#u,hideChildren:this.hideChildren})}#h(t,r){let i=t.overviewAbsolutePath!=null?zo.V1.PageId(oXt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#e.getSubpackageByIdOrLocator(t.package);if(a!=null){let u=Qfi.getSubpackageId(a),l=this.#u.get(i??`${this.apiDefinitionId}:${u}`);this.#i.has(u)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${u}`),this.#i.add(u),this.#a.set(l,[u]);let d=t.slug??(aXt(a)?a.urlSlug:this.apiSection.slug??Oq(this.apiSection.title)),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#s(t.contents,a,s);return{id:l,type:"apiPackage",children:o,title:t.title??(aXt(a)?a.displayName??v5t(a.name):this.apiSection.title),slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}else{this.taskContext.logger.warn(`Subpackage ${t.package} not found in ${this.apiDefinitionId}, treating it as a section`);let u=t.slug??Oq(t.package),l=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#s(t.contents,void 0,l);return{id:this.#u.get(i??`${this.apiDefinitionId}:${Oq(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#_(t,r){let i=t.overviewAbsolutePath!=null?zo.V1.PageId(oXt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(t.overviewAbsolutePath):void 0,u=this.#u.get(i??n??r.get()),l=t.referencedSubpackages.map(c=>{let b=this.#e.getSubpackageByIdOrLocator(c);return b!=null?Qfi.getSubpackageId(b):void 0}).filter(c=>(c==null&&this.taskContext.logger.error(`Subpackage ${c} not found in ${this.apiDefinitionId}`),c!=null)).filter(u0);this.#a.set(u,l),l.forEach(c=>{this.#i.has(c)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${c}`),this.#i.add(c)});let d=t.slug??Oq(t.title),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#s(t.contents,void 0,s);return{id:u,type:"apiPackage",children:o,title:t.title,slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:a,playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}#p(t,r,i){t=t.trim();let n=this.#e.getSubpackageByIdOrLocator(t);if(n!=null){let a=Qfi.getSubpackageId(n),u=this.#u.get(`${this.apiDefinitionId}:${a}`);this.#i.has(a)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a}`),this.#i.add(a),this.#a.set(u,[a]);let l=aXt(n)?n.urlSlug:"",d=i.apply({urlSlug:l});return{id:u,type:"apiPackage",children:[],title:aXt(n)?n.displayName??v5t(n.name):this.apiSection.title,slug:d.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}return this.#b({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i)}#b(t,r,i){let n=(r!=null?this.#e.subpackages.get(p2.SubpackageId(r))?.endpoints.get(p2.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(n!=null){let l=this.#e.getEndpointId(n);if(l==null)throw new Error(`Expected Endpoint ID for ${n.id}. Got undefined.`);this.#t.has(l)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${l}`),this.#t.add(l);let d=t.slug!=null?i.append(t.slug):i.apply(n);return{id:this.#u.get(`${this.apiDefinitionId}:${l}`),type:"endpoint",method:n.method,endpointId:l,apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:t.title??n.name??TC(n.path.parts),slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let a=(r!=null?this.#e.subpackages.get(p2.SubpackageId(r))?.webSockets.get(p2.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(a!=null){let l=this.#e.getWebSocketId(a);if(l==null)throw new Error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return this.#r.has(l)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${l}`),this.#r.add(l),{id:this.#u.get(`${this.apiDefinitionId}:${l}`),type:"webSocket",webSocketId:l,title:t.title??a.name??TC(a.path.parts),slug:(t.slug!=null?i.append(t.slug):i.apply(a)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(a.availability),playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let u=(r!=null?this.#e.subpackages.get(p2.SubpackageId(r))?.webhooks.get(p2.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(zo.V1.WebhookId(t.endpoint));if(u!=null){let l=this.#e.getWebhookId(u);if(l==null)throw new Error(`Expected Webhook ID for ${u.id}. Got undefined.`);return this.#n.has(l)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${l}`),this.#n.add(l),{id:this.#u.get(`${this.apiDefinitionId}:${l}`),type:"webhook",webhookId:l,method:u.method,title:t.title??u.name??Cv("/",...u.path),slug:(t.slug!=null?i.append(t.slug):i.apply(u)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#y(t,r){return Azo({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>TC(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#g(t){return V_a({child:t,nodeIdToSubpackageId:this.#a,convertApiDefinitionPackageId:(r,i)=>this.#P(r,i),mergeAndFilterChildren:this.#y.bind(this)})}#j(t,r){let i=[];return t.endpoints.forEach(n=>{let a=this.#e.getEndpointId(n);if(a==null)throw new Error(`Expected Endpoint ID for ${n.id}. Got undefined.`);if(this.#t.has(a))return;let u=r.apply(n);i.push({id:zo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:n.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:n.name??TC(n.path.parts),slug:u.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.websockets.forEach(n=>{let a=this.#e.getWebSocketId(n);if(a==null)throw new Error(`Expected WebSocket ID for ${n.id}. Got undefined.`);this.#r.has(a)||i.push({id:zo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:n.name??TC(n.path.parts),slug:r.apply(n).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(n.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.webhooks.forEach(n=>{let a=this.#e.getWebhookId(n);if(a==null)throw new Error(`Expected Webhook ID for ${n.id}. Got undefined.`);this.#n.has(a)||i.push({id:zo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:n.method,title:n.name??v5t(n.id),slug:r.apply(n).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.subpackages.forEach(n=>{if(this.#i.has(n))return;let a=this.#e.getSubpackageByIdOrLocator(n);if(a==null){this.taskContext.logger.error(`Subpackage ${n} not found in ${this.apiDefinitionId}`);return}let u=aXt(a)?r.apply(a):r,l=this.#P(n,u);l.length>0&&i.push({id:zo.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"apiPackage",children:l,title:aXt(a)?a.displayName??v5t(a.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&(i=i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,l=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(l)})),i}#P(t,r){let i=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return i==null?(this.taskContext.logger.error(`Subpackage ${t} not found in ${this.apiDefinitionId}`),[]):this.#j(i,r)}#O(t){return Mzo(t)}mergeEndpointPairs(t){return O1n({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>TC(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var Czo=class{#e={};#t={};#r={};#n={};constructor(t){for(let[r,i]of Object.entries(t.subpackages))this.#e[r]=i,this.#e[`subpackage_${r}`]=i;for(let[r,i]of Object.entries(t.endpoints)){this.#r[r]=i,this.#r[r.replace("endpoint_","")]=i,this.#r[r.replace("endpoint_","subpackage_")]=i;for(let n of[i.method,"STREAM"])i.environments?.forEach(a=>{this.#r[`${n} ${Cv(a.baseUrl,TC(i.path))}`]=i,this.#r[`${n} ${Cv(a.baseUrl,ize(i.path))}`]=i;let u=Ezo(a);u!=null&&(this.#r[`${n} ${Cv(u,TC(i.path))}`]=i,this.#r[`${n} ${Cv(u,ize(i.path))}`]=i)}),this.#r[`${i.method} ${TC(i.path)}`]=i,this.#r[`${i.method} ${ize(i.path)}`]=i}for(let[r,i]of Object.entries(t.webhooks))this.#t[r]=i,this.#t[r.replace("webhook_","")]=i,this.#t[r.replace("webhook_","subpackage_")]=i,this.#t[`${i.method} ${i.path.join("/")}`]=i;for(let[r,i]of Object.entries(t.websockets))this.#n[r]=i,this.#n[r.replace("websocket_","")]=i,this.#n[r.replace("websocket_","subpackage_")]=i,this.#n[`STREAM ${TC(i.path)}`]=i,this.#n[`STREAM ${ize(i.path)}`]=i}getSubpackageByLocator(t){if(["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","CONNECT","TRACE"].some(i=>t.includes(i)))return;let r=t.replace(".yml","").replace(".yaml","");return this.#e[r]}getWebhookByLocator(t,r){return this.#t[t]??this.#t[`${r}.${t}`]??this.#t[`webhook_${r}.${t}`]}getEndpointByLocator(t,r){return this.#r[t]??this.#r[`${r}.${t}`]??this.#r[`endpoint_${r}.${t}`]}getWebSocketByLocator(t,r){return this.#n[t]??this.#n[`${r}.${t}`]??this.#n[`websocket_${r}.${t}`]}};function W_a({item:e,parentSlug:t}){return t.apply({urlSlug:Oq(e.id.split(".").pop()??"")}).get()}var H_a=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;hideChildren;apiDefinitionId;#e;#t;#r=new Set;#n=new Set;#i=new Set;#a=new Set;#o=new Map;#c=[];#l;#u;#s;#f=new Map;disableEndpointPairs;constructor(t,r,i,n,a,u,l,d,s,o){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=l,this.markdownFilesToNoIndex=d,this.hideChildren=o,this.#e=r,this.#t=new Czo(r),this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=zo.V1.ApiDefinitionId(r.id),this.#s=s,this.#l=this.apiSection.overviewAbsolutePath!=null?zo.V1.PageId(oXt(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let c=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#u=i.apply({fullSlug:c?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??Oq(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#c=this.#h(this.apiSection.navigation,void 0,this.#u)),this.#c=this.#j(this.#c.map(b=>this.#P(b)),this.#O(this.#e,this.#u))}get(){let t=zo.V1.followRedirects(this.#c),r=new LQr(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#s).orUndefined();return{id:this.#s.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#l,paginated:this.apiSection.paginated,slug:this.#u.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#u,viewers:void 0,hidden:this.hideChildren}),children:this.#c,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#S(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#h(t,r,i){return t.map(n=>U_a(n)._visit({link:a=>({id:this.#s.get(a.url),type:"link",title:a.text,icon:a.icon,url:zo.Url(a.url)}),page:a=>this.#_(a,i),package:a=>this.#p(a,i),section:a=>this.#b(a,i),item:({value:a})=>this.#y(a,r,i),endpoint:a=>this.#g(a,r,i)})).filter(u0)}#_(t,r){return qzo({docsWorkspace:this.docsWorkspace,page:t,parentSlug:r,idgen:this.#s,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex})}#p(t,r){let i=t.overviewAbsolutePath!=null?zo.V1.PageId(oXt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#t.getSubpackageByLocator(t.package);if(a!=null){let u=this.#s.get(i??`${this.apiDefinitionId}:${a.id}`);this.#a.has(a.id)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a.id}`),this.#a.add(a.id),this.#o.set(u,[a.id]);let l=t.slug??Oq(a.name),d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#h(t.contents,a.id,d),o={id:u,type:"apiPackage",children:s,title:t.title??a.displayName??v5t(a.name),slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#f.set(a.id,o),o}else{this.taskContext.logger.warn(`Subpackage ${t.package} not found in ${this.apiDefinitionId}, treating it as a section`);let u=t.slug??Oq(t.package),l=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#h(t.contents,t.package,l),s={id:this.#s.get(i??`${this.apiDefinitionId}:${Oq(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#f.set(t.package,s),s}}#b(t,r){let i=t.overviewAbsolutePath!=null?zo.V1.PageId(oXt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#s.get(i??n??r.get()),u=t.referencedSubpackages.map(c=>{let b=this.#t.getSubpackageByLocator(c);return b?.id}).filter(c=>(c==null&&this.taskContext.logger.error(`Subpackage ${c} not found in ${this.apiDefinitionId}`),c!=null)).filter(u0);this.#o.set(a,u),u.forEach(c=>{this.#a.has(c)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${c}`),this.#a.add(c)});let l=t.slug??Oq(t.title),d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#h(t.contents,t.title,d),o={id:a,type:"apiPackage",children:s,title:t.title,slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return u.forEach(c=>{this.#f.set(c,o)}),o}#y(t,r,i){t=t.trim();let n=this.#t.getSubpackageByLocator(t);if(n!=null){let a=n.id,u=this.#s.get(`${this.apiDefinitionId}:${a}`);this.#a.has(a)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a}`),this.#a.add(a),this.#o.set(u,[a]);let l=Oq(n.name),d=i.apply({urlSlug:l}),s={id:u,type:"apiPackage",children:[],title:n.displayName??v5t(n.name),slug:d.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};return this.#f.set(a,s),s}return this.#g({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i)}#g(t,r,i){let n=this.#t.getEndpointByLocator(t.endpoint,r);if(n!=null){if(n.id==null)throw new Error(`Expected Endpoint ID for ${n.id}. Got undefined.`);this.#r.has(n.id)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${n.id}`),this.#r.add(n.id);let l=t.slug!=null?i.append(t.slug).get():W_a({item:n,parentSlug:i});return{id:this.#s.get(`${this.apiDefinitionId}:${n.id}`),type:"endpoint",method:n.method,endpointId:n.id,apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(n.availability),isResponseStream:n.responses?.[0]?.body.type==="stream",title:t.title??n.displayName??TC(n.path),slug:l,icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let a=this.#t.getWebSocketByLocator(t.endpoint,r);if(a!=null){if(a.id==null)throw new Error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return this.#n.has(a.id)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${a.id}`),this.#n.add(a.id),{id:this.#s.get(`${this.apiDefinitionId}:${a.id}`),type:"webSocket",webSocketId:a.id,title:t.title??a.displayName??TC(a.path),slug:t.slug!=null?i.append(t.slug).get():W_a({item:a,parentSlug:i}),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(a.availability),playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let u=this.#t.getWebhookByLocator(t.endpoint,r);if(u!=null){if(u.id==null)throw new Error(`Expected Webhook ID for ${u.id}. Got undefined.`);return this.#i.has(u.id)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${u.id}`),this.#i.add(u.id),{id:this.#s.get(`${this.apiDefinitionId}:${u.id}`),type:"webhook",webhookId:u.id,method:u.method,title:t.title??u.displayName??Cv("/",...u.path),slug:t.slug!=null?i.append(t.slug).get():W_a({item:u,parentSlug:i}),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#j(t,r){return Azo({left:t,right:r,findEndpointById:i=>this.#t.getEndpointByLocator(i,void 0),stringifyEndpointPathParts:i=>TC(i.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#P(t){return V_a({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(r,i)=>this.#w(r,i),mergeAndFilterChildren:this.#j.bind(this)})}#O(t,r){let i=[];return Object.entries(t.subpackages).forEach(([n,a])=>{if(!this.#a.has(n)){let u=this.#D(n,a,r);u!=null&&i.push(u)}}),Object.entries(t.endpoints).forEach(([n,a])=>{if(n==null)throw new Error(`Expected Endpoint ID for ${a.id}. Got undefined.`);!this.#r.has(KM.EndpointId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#M(n,a,r,i)}),Object.entries(t.websockets).forEach(([n,a])=>{if(n==null)throw new Error(`Expected WebSocket ID for ${a.id}. Got undefined.`);!this.#n.has(KM.WebSocketId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#E(n,a,r,i)}),Object.entries(t.webhooks).forEach(([n,a])=>{if(n==null)throw new Error(`Expected Webhook ID for ${a.id}. Got undefined.`);!this.#i.has(KM.WebhookId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#d(n,a,r,i)}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,l=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(l)}),i}#D(t,r,i){let n=zo.V1.SlugGenerator.init(i.get()).apply({urlSlug:Oq(r.name)}),a=this.#w(t,n),u={id:zo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"apiPackage",children:a,title:r.displayName??v5t(r.name),slug:n.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};return this.#f.set(t,u),a.length>0?u:void 0}#m(t,r,i,n){r.slug=W_a({item:t,parentSlug:i}),n.push(r)}#M(t,r,i,n){let a={id:zo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"endpoint",method:r.method,endpointId:KM.EndpointId(t),apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(r.availability),isResponseStream:r.responses?.[0]?.body.type==="stream",title:r.displayName??TC(r.path),slug:i.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#m(r,a,i,n)}#E(t,r,i,n){let a={id:zo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webSocket",webSocketId:KM.WebSocketId(t),title:r.displayName??TC(r.path),slug:i.get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(r.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#m(r,a,i,n)}#d(t,r,i,n){let a={id:zo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webhook",webhookId:KM.WebhookId(t),method:r.method,title:r.displayName??v5t(r.id),slug:i.get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#m(r,a,i,n)}#T(t){let r=Object.fromEntries(Object.entries(this.#e?.subpackages??{}).filter(([u,l])=>t===this.#e.id?l.id.split(".").length===1:l.id!=null&&l.id.includes(t)&&l.id!==t&&l.id.split(".").length===t.split(".").length+1)),i=Object.fromEntries(Object.entries(this.#e?.endpoints??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===KM.api.v1.SubpackageId(t))),n=Object.fromEntries(Object.entries(this.#e?.websockets??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===KM.api.v1.SubpackageId(t))),a=Object.fromEntries(Object.entries(this.#e?.webhooks??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===KM.api.v1.SubpackageId(t)));return{id:KM.ApiDefinitionId(t),endpoints:i,websockets:n,webhooks:a,types:{},subpackages:r,auths:{},globalHeaders:void 0,snippetsConfiguration:void 0}}#w(t,r){let i=t!=null?this.#T(t):void 0;return i==null?(this.taskContext.logger.error(`Subpackage ${t} not found in ${this.apiDefinitionId}`),[]):this.#O(i,r)}#S(t){return Mzo(t)}mergeEndpointPairs(t){return O1n({children:t,findEndpointById:r=>this.#e?.endpoints[r],stringifyEndpointPathParts:r=>TC(r.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var Fi_=vi(require("crypto"),1);function PQD(e){return Fi_.default.createHash("sha256").update(e).digest("hex")}var Bzo=class e{static init(){return new e}constructor(){}#e=new Map;#t=new Set;#r(t){let r=this.#e.get(t)??0;return this.#e.set(t,r+1),PQD(r===0?t:`${t}-${r}`)}#n(t){let r=this.#r(t),i=0;for(;this.#t.has(r);)if(r=this.#r(t),i++,i>100)throw new Error(`Infinite loop detected for id: ${t}`);return r}get(t){return zo.V1.NodeId(this.#n(t))}};function xzo(e){return e==null?{}:{pythonSdk:e.python!=null?{package:typeof e.python=="string"?e.python:e.python.package,version:typeof e.python=="string"?void 0:e.python.version}:void 0,typescriptSdk:e.typescript!=null?{package:typeof e.typescript=="string"?e.typescript:e.typescript.package,version:typeof e.typescript=="string"?void 0:e.typescript.version}:void 0,goSdk:e.go!=null?{githubRepo:typeof e.go=="string"?e.go:e.go.package,version:typeof e.go=="string"?void 0:e.go.version}:void 0,javaSdk:e.java!=null?{coordinate:typeof e.java=="string"?e.java:e.java.package,version:typeof e.java=="string"?void 0:e.java.version}:void 0,rubySdk:e.ruby!=null?{gem:typeof e.ruby=="string"?e.ruby:e.ruby.package,version:typeof e.ruby=="string"?void 0:e.ruby.version}:void 0,csharpSdk:e.csharp!=null?{package:typeof e.csharp=="string"?e.csharp:e.csharp.package,version:typeof e.csharp=="string"?void 0:e.csharp.version}:void 0}}var Izo=vi(zte(),1);var _Ks=vi(zte(),1);function Li_(e,t,r){let i=e.schemes[0];if(e.schemes.length===1&&i!=null)switch(i.type){case"basic":return{type:"basicAuth",passwordName:i.password.originalName,usernameName:i.username.originalName};case"bearer":return{type:"bearerAuth",tokenName:i.token.originalName};case"header":return{type:"header",headerWireValue:i.name.wireValue,nameOverride:i.name.name.originalName,prefix:i.prefix};case"oauth":{let n=i.configuration.tokenEndpoint.responseProperties.accessToken.propertyPath?.map(a=>a.originalName).join(".")||"$.body.access_token";return r?.oauth?{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:_Ks.FernRegistry.EndpointId(i.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:_Ks.FernRegistry.JqString(n),headerName:i.configuration.tokenHeader,tokenPrefix:i.configuration.tokenPrefix}}}:{type:"bearerAuth",tokenName:"token"}}default:Ko(i)}}var VP=vi(zte(),1);var Jfi=vi(zte(),1);function Vi_(e){return e._visit({alias:t=>({type:"alias",value:qD(t.aliasOf)}),enum:t=>({type:"enum",default:t.default!=null?t.default.name.wireValue:void 0,values:t.values.map(r=>({description:r.docs??void 0,value:r.name.wireValue,availability:g7(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>Jfi.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:Jfi.FernRegistry.PropertyKey(r.name.wireValue),valueType:qD(r.valueType),availability:g7(r.availability)})),extraProperties:SQD(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:Jfi.FernRegistry.PropertyKey(i.name.wireValue),valueType:qD(i.valueType),availability:g7(i.availability),description:i.docs}));return{type:"discriminatedUnion",discriminant:t.discriminant.wireValue,variants:t.types.map(i=>({description:i.docs??void 0,discriminantValue:i.discriminantValue.wireValue,displayName:i.displayName,availability:i.availability!=null?g7(i.availability):void 0,additionalProperties:Tc.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[Jfi.FernRegistry.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:Jfi.FernRegistry.PropertyKey(n.name.wireValue),valueType:qD(n.type),description:void 0,availability:void 0},...r],extraProperties:void 0}),noProperties:()=>({extends:[],properties:r,extraProperties:void 0}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+i.shape.propertiesType)}})}))}},undiscriminatedUnion:t=>({type:"undiscriminatedUnion",variants:t.members.map(r=>({typeName:r.type.type==="named"?r.type.name.originalName:void 0,description:r.docs??void 0,type:qD(r.type),availability:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function qD(e){return e._visit({container:t=>Tc.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:qD(r)}),map:({keyType:r,valueType:i})=>({type:"map",keyType:qD(r),valueType:qD(i)}),optional:r=>({type:"optional",itemType:qD(r),defaultValue:void 0}),nullable:r=>({type:"optional",itemType:qD(r),defaultValue:void 0}),set:r=>({type:"set",itemType:qD(r)}),literal:r=>Tc.types.Literal._visit(r,{boolean:i=>({type:"literal",value:{type:"booleanLiteral",value:i}}),string:i=>({type:"literal",value:{type:"stringLiteral",value:i}}),_other:()=>{throw new Error("Unknown literal type: "+r.type)}}),_other:()=>{throw new Error("Unknown container reference: "+t.type)}}),named:t=>({type:"id",value:Jfi.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:Tc.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>wQD(t.v2),float:()=>Ui_(t.v2),double:()=>Ui_(t.v2),string:()=>jQD(t.v2),long:()=>({type:"long",default:t.v2?.type==="long"?t.v2.default:void 0,minimum:void 0,maximum:void 0}),boolean:()=>({type:"boolean",default:t.v2?.type==="boolean"?t.v2.default:void 0}),dateTime:()=>({type:"datetime",default:void 0}),date:()=>({type:"date",default:void 0}),uuid:()=>({type:"uuid",default:void 0}),base64:()=>({type:"base64",mimeType:void 0,default:void 0}),bigInteger:()=>({type:"bigInteger",default:t.v2?.type==="bigInteger"?t.v2.default:void 0}),uint:()=>({type:"uint"}),uint64:()=>({type:"uint64"}),_other:()=>{throw new Error("Unknown primitive: "+t.v1)}})}),unknown:()=>({type:"unknown"}),_other:()=>{throw new Error("Unknown Type reference: "+e.type)}})}function jQD(e){let t=e!=null&&e.type==="string"?e.validation:void 0;return{type:"string",format:t?.format,regex:t?.pattern,minLength:t?.minLength,maxLength:t?.maxLength,default:e!=null&&e.type==="string"?e.default:void 0}}function wQD(e){let t=e!=null&&e.type==="integer"?e.validation:void 0;return{type:"integer",minimum:t?.min,maximum:t?.max,default:e!=null&&e.type==="integer"?e.default:void 0}}function Ui_(e){let t=e!=null&&e.type==="double"?e.validation:void 0;return{type:"double",minimum:t?.min,maximum:t?.max,default:e!=null&&e.type==="double"?e.default:void 0}}function SQD(e){return typeof e=="boolean"?e?nh.unknown():void 0:typeof e=="string"?{type:"id",value:Jfi.FernRegistry.TypeId(e),default:void 0}:qD(e)}function yKs(e,t){let r=e.service!=null?t.services[e.service]:void 0,i=e.webhooks!=null?t.webhookGroups[e.webhooks]:void 0,n=e.websocket!=null&&t.websocketChannels!=null?t.websocketChannels[e.websocket]:void 0;return{endpoints:r!=null?EQD(r,t):[],webhooks:i!=null?DQD(i):[],websockets:n!=null?[MQD(n,t)]:[],types:e.types.map(a=>VP.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>VP.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?VP.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function DQD(e){return e.map(t=>({description:t.docs??void 0,id:VP.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??jkn(t.name.originalName),headers:t.headers.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:qD(r.valueType),availability:g7(r.availability)})),payload:zQD(t.payload),examples:t.examples!=null?t.examples.map(r=>({payload:r.payload.jsonExample})):[]}))}function EQD(e,t){let r=[];for(let i of e.endpoints){let n=i.autogeneratedExamples[0],a=[];if(i.userSpecifiedExamples.length>0)a.push(...i.userSpecifiedExamples.map(l=>hKs({userSpecifiedExample:l,...n!=null&&{autogeneratedExample:n},irEndpoint:i,ir:t})).filter(u0));else if(n!=null){let l=hKs({autogeneratedExample:n,irEndpoint:i,ir:t});l!=null&&a.push(l)}else if(i.response?.body?.type==="fileDownload"){let l=lpa({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(l.type==="success"){let d=hKs({autogeneratedExample:l,irEndpoint:i,ir:t});if(d!=null){let s={...d,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let u={availability:g7(i.availability??e.availability),auth:i.auth,description:i.docs??void 0,method:CQD(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?VP.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?AQD({environmentsConfig:t.environments,endpoint:i}):void 0,id:VP.FernRegistry.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.displayName??jkn(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(l=>({description:l.docs??void 0,key:VP.FernRegistry.PropertyKey(l.name.originalName),type:qD(l.valueType),availability:void 0})),parts:[...m1n(i.basePath),...m1n(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(l=>({description:l.docs??void 0,key:VP.FernRegistry.PropertyKey(l.name.originalName),type:qD(l.valueType),availability:void 0})),parts:[...t.basePath!=null?m1n(t.basePath):[],...m1n(e.basePath),...m1n(i.path)]},queryParameters:i.queryParameters.map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:qD(l.valueType),availability:g7(l.availability)})),headers:[...e.headers,...i.headers].map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:qD(l.valueType),availability:g7(l.availability)})),request:i.requestBody!=null?BQD(i.requestBody):void 0,response:i.response!=null?xQD(i.response):void 0,errors:void 0,errorsV2:IQD(i.errors,t),examples:a};r.push(u)}return r}function MQD(e,t){return{auth:e.auth,availability:g7(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?VP.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?qQD({environmentsConfig:t.environments,channel:e}):[],id:VP.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??jkn(e.name.originalName),path:{pathParameters:e.pathParameters.map(r=>({description:r.docs??void 0,key:VP.FernRegistry.PropertyKey(r.name.originalName),type:qD(r.valueType),availability:void 0})),parts:m1n(e.path)},headers:e.headers.map(r=>({key:r.name.wireValue,type:qD(r.valueType),description:r.docs,availability:g7(r.availability)})),queryParameters:e.queryParameters.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:qD(r.valueType),availability:g7(r.availability)})),messages:e.messages.map(r=>({type:VP.FernRegistry.api.v1.WebSocketMessageId(r.type),displayName:r.displayName,origin:r.origin,body:RQD(r.body),description:r.docs,availability:g7(r.availability)})),examples:e.examples.map(r=>({name:r.name?.originalName,description:r.docs,path:r.url,pathParameters:r.pathParameters.reduce((i,n)=>(i[VP.FernRegistry.PropertyKey(n.name.originalName)]=n.value.jsonExample,i),{}),queryParameters:r.queryParameters.reduce((i,n)=>(i[n.name.wireValue]=n.value.jsonExample,i),{}),headers:r.headers.reduce((i,n)=>(i[n.name.wireValue]=n.value.jsonExample,i),{}),messages:r.messages.map(i=>({type:VP.FernRegistry.api.v1.WebSocketMessageId(i.type),body:i.body.jsonExample}))}))}}function g7(e){if(e!=null)switch(e.status){case"DEPRECATED":return VP.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return VP.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return VP.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return VP.FernRegistry.Availability.Beta;default:Ko(e.status)}}function AQD({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:VP.FernRegistry.EnvironmentId(n.id),baseUrl:n.url}));case"multipleBaseUrls":if(i==null)throw new Error(`Expected endpoint ${t.name.originalName} to have base url.`);return r.environments.map(n=>{let a=n.urls[i];if(a==null)throw new Error(`Expected environment ${n.id} to contain url for ${i}`);return{id:VP.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:Ko(r)}}function qQD({environmentsConfig:e,channel:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:VP.FernRegistry.EnvironmentId(n.id),baseUrl:TQD(n.url,"wss")}));case"multipleBaseUrls":if(i==null)throw new Error(`Expected channel ${t.name.originalName} to have base url.`);return r.environments.map(n=>{let a=n.urls[i];if(a==null)throw new Error(`Expected environment ${n.id} to contain url for ${i}`);return{id:VP.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:Ko(r)}}function TQD(e,t){return e.replace(/^[^:]+/,t)}function CQD(e){return Tc.http.HttpMethod._visit(e,{get:()=>VP.FernRegistry.HttpMethod.Get,post:()=>VP.FernRegistry.HttpMethod.Post,put:()=>VP.FernRegistry.HttpMethod.Put,patch:()=>VP.FernRegistry.HttpMethod.Patch,delete:()=>VP.FernRegistry.HttpMethod.Delete,_other:()=>{throw new Error("Unknown http method: "+e)}})}function m1n(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:VP.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function BQD(e){let t=Tc.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??zB.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>VP.FernRegistry.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:VP.FernRegistry.PropertyKey(i.name.wireValue),valueType:qD(i.valueType),availability:g7(i.availability)})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??zB.APPLICATION_JSON,shape:{type:"reference",value:qD(r.requestBodyType)},description:r.docs??void 0}),fileUpload:r=>({type:"fileUpload",value:{name:r.name.originalName,description:void 0,availability:void 0,properties:r.properties.map(i=>i._visit({file:n=>{let a=n._visit({file:u=>({type:"file",key:VP.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:VP.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:void 0,availability:void 0}),_other:()=>{}});if(a!=null)return{type:"file",value:a}},bodyProperty:n=>({type:"bodyProperty",key:VP.FernRegistry.PropertyKey(n.name.wireValue),valueType:qD(n.valueType),contentType:n.contentType,description:n.docs,availability:g7(n.availability),exploded:n.style==="exploded"}),_other:()=>{}})).filter(u0)},description:r.docs??void 0}),bytes:r=>({type:"bytes",description:r.docs??void 0,availability:void 0,isOptional:r.isOptional,contentType:r.contentType}),_other:()=>{throw new Error("Unknown HttpRequestBody: "+e.type)}});return t!=null?{type:t,description:e.docs}:void 0}function xQD(e){if(e.body==null)return;let t,r=Tc.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:qD(i.responseBodyType)}),text:()=>{},bytes:()=>{},streamParameter:()=>{},streaming:i=>{if(i.type==="text")return t=i.docs,{type:"streamingText"};if(i.type==="json")return t=i.docs,{type:"stream",shape:{type:"reference",value:qD(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:qD(i.payload)},terminator:i.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});return r!=null?{type:r,statusCode:e.statusCode,description:t}:e.statusCode!=null?{statusCode:e.statusCode,description:t,type:{type:"object",extends:[],properties:[],extraProperties:void 0}}:void 0}function IQD(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let i of e){let n=t.errors[i.error.errorId];n&&r.push({type:n.type==null?void 0:{type:"alias",value:qD(n.type)},statusCode:n.statusCode,description:n.docs??void 0,name:n.name.name.originalName,availability:void 0,examples:n.examples.map(a=>({name:a.name?.originalName,responseBody:{type:"json",value:a.jsonExample},description:a.docs}))})}else for(let i of e){let n=t.errors[i.error.errorId];if(n){let a=[{key:VP.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.discriminant.wireValue),valueType:{type:"literal",value:{type:"stringLiteral",value:n.discriminantValue.name.originalName}},description:n.docs,availability:void 0}];n.type!=null&&a.push({key:VP.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:qD(n.type),description:n.docs,availability:void 0}),r.push({type:n.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},statusCode:n.statusCode,description:n.docs??void 0,availability:void 0,name:n.name.name.originalName,examples:n.examples.map(u=>({name:u.name?.originalName,responseBody:{type:"json",value:u.jsonExample},description:u.docs}))})}}return r}function hKs({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:i}){let n=i.headers.map(l=>{let d=l.valueType.type==="container"&&l.valueType.container.type==="literal"?l.valueType.container.literal._visit({boolean:s=>`${s}`,string:s=>s,_other:()=>{}}):void 0;if(d!=null)return{name:l.name,value:{jsonExample:d,shape:Tc.ExampleTypeReferenceShape.primitive(Tc.ExamplePrimitive.string({original:d}))}}}).filter(u0),a=e?.example??t?.example;if(a==null)return;let{codeSamples:u}=e??{codeSamples:[]};return{name:a.name?.originalName,description:a.docs,path:a.url,pathParameters:[...a.rootPathParameters,...a.servicePathParameters,...a.endpointPathParameters].reduce((l,d)=>(l[VP.FernRegistry.PropertyKey(d.name.originalName)]=d.value.jsonExample,l),{}),queryParameters:a.queryParameters.reduce((l,d)=>(l[d.name.wireValue]=d.value.jsonExample,l),{}),headers:[...n,...a.serviceHeaders,...a.endpointHeaders].reduce((l,d)=>(l[d.name.wireValue]=d.value.jsonExample,l),{}),requestBody:a.request?.jsonExample,requestBodyV3:r.requestBody?._visit({inlinedRequestBody:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,reference:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,fileUpload:l=>{if(a.request==null)return;let d={};if(Hj(a.request.jsonExample)){let s=a.request.jsonExample;for(let o of l.properties)o._visit({file:c=>{let b=s[c.key.wireValue];if(c.type==="file")d[c.key.wireValue]={type:"filename",value:typeof b=="string"?b:"<file1>"};else if(c.type==="fileArray"){let g=(Array.isArray(b)?b:[b]).filter(O=>typeof O=="string");d[c.key.wireValue]={type:"filenames",value:g}}},bodyProperty:c=>{if(c.style==="exploded"){let b=s[c.name.wireValue];d[c.name.wireValue]={type:"exploded",value:Array.isArray(b)?b:[b]}}else d[c.name.wireValue]={type:"json",value:s[c.name.wireValue]}},_other:L2t})}return{type:"form",value:d}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??Tc.http.ExampleResponse._visit(a.response,{ok:l=>l._visit({body:d=>d!=null?200:204,stream:d=>d.length>0?200:204,sse:d=>d.length>0?200:204,_other:()=>{throw new Error("Unknown ExampleResponseBody: "+l.type)}}),error:({error:l})=>{let d=i.errors[l.errorId];if(d==null)throw new Error("Cannot find error "+l.errorId);return d.statusCode},_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),responseBody:a.response._visit({ok:l=>l._visit({body:d=>d?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:l=>l.body?.jsonExample,_other:()=>{}}),responseBodyV3:a.response._visit({ok:l=>l._visit({body:d=>d!=null?{type:"json",value:d.jsonExample}:void 0,stream:d=>({type:"stream",value:d.map(s=>s.jsonExample)}),sse:d=>({type:"sse",value:d.map(({event:s,data:o})=>({event:s,data:o.jsonExample}))}),_other:()=>{throw new Error("Unknown ExampleResponseBody: "+l.type)}}),error:l=>l.body!=null?{type:"json",value:l.body.jsonExample}:void 0,_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),codeSamples:u?.map(l=>C1e._visit(l,{language:d=>({language:d.language,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:d.install}),sdk:d=>({language:d.sdk,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:void 0}),_other:()=>{}})).filter(u0)}}function zQD(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>VP.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:VP.FernRegistry.PropertyKey(t.name.wireValue),valueType:qD(t.valueType),availability:g7(t.availability)})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:qD(e.payloadType)},description:e.docs};default:Ko(e)}}function RQD(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>VP.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:VP.FernRegistry.PropertyKey(t.name.wireValue),valueType:qD(t.valueType),availability:g7(t.availability)})),extraProperties:void 0};case"reference":return{type:"reference",value:qD(e.bodyType)};default:Ko(e)}}function SSe({ir:e,snippetsConfig:t,playgroundConfig:r}){let i={types:{},subpackages:{},rootPackage:yKs(e.rootPackage,e),auth:Li_(e.auth,e,r),snippetsConfiguration:t,globalHeaders:e.headers.map(n=>({availability:g7(n.availability),description:n.docs??void 0,key:n.name.wireValue,type:qD(n.valueType)})),navigation:void 0};for(let[n,a]of Object.entries(e.types))i.types[Izo.FernRegistry.TypeId(n)]={description:a.docs??void 0,name:a.name.name.originalName,shape:Vi_(a.shape),availability:g7(a.availability)};for(let[n,a]of Object.entries(e.subpackages)){let u=a.service!=null?e.services[a.service]:void 0;i.subpackages[Izo.FernRegistry.api.v1.SubpackageId(n)]={subpackageId:Izo.FernRegistry.api.v1.SubpackageId(n),displayName:u?.displayName,name:a.name.originalName,description:a.docs??void 0,...yKs(a,e)}}return i}var vKs=vi(zte(),1);async function bKs({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:u}){let l=_2({workspace:t,audiences:n,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new d2(r,t)}),d=zTi({token:i.value}),s=SSe({ir:l,snippetsConfig:a,playgroundConfig:u}),o=await d.api.v1.register.registerApiDefinition({orgId:vKs.FernRegistry.OrgId(e),apiId:vKs.FernRegistry.ApiId(l.apiName.originalName),definition:s});if(o.ok)return r.logger.debug(`Registered API Definition ${o.body.apiDefinitionId}`),{id:o.body.apiDefinitionId,ir:l};switch(o.error.error){case"UnauthorizedError":case"UserNotInOrgError":return r.failAndThrow("You do not have permissions to register the docs. Reach out to support@buildwithfern.com");default:return r.failAndThrow("Failed to register API",o.error)}}var NQD=new Fzi({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function $_a(e,t,r){return g_a(y_a(SSe({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:r}),p2.ApiDefinitionId(t),NQD))}var I_={};Io(I_,{AlgoliaSearchIndex:()=>Wi_,ApiDefinitionId:()=>ln_,ApiId:()=>_n_,Availability:()=>An_,DocsConfigId:()=>hn_,EndpointId:()=>vn_,EndpointPathLiteral:()=>En_,EnvironmentId:()=>yn_,FileId:()=>Pn_,HttpMethod:()=>Mn_,IndexSegmentId:()=>Hi_,JqString:()=>wn_,OrgId:()=>dn_,PageId:()=>mn_,PayloadLocation:()=>ra_,PropertyKey:()=>Sn_,PullRequestState:()=>Xn_,RoleId:()=>Dn_,TokenId:()=>pn_,TypeId:()=>On_,Url:()=>jn_,VersionId:()=>fn_,WebSocketId:()=>bn_,WebhookId:()=>gn_,algolia:()=>gKs,api:()=>AKs,commons:()=>qKs,diff:()=>qn_,docs:()=>FKs,generators:()=>UKs,git:()=>VKs,navigation:()=>$Ks,sdks:()=>QKs,snippets:()=>ea_,snippetsFactory:()=>ta_,templates:()=>JKs,tokens:()=>ia_});var gKs={};Io(gKs,{AlgoliaSearchIndex:()=>Wi_,IndexSegmentId:()=>Hi_});function Wi_(e){return e}function Hi_(e){return e}var AKs={};Io(AKs,{latest:()=>PKs,v1:()=>MKs});var PKs={};Io(PKs,{AuthSchemeId:()=>$i_,WebhookHttpMethod:()=>Ki_,auth:()=>OKs,commons:()=>Gi_,endpoint:()=>Qi_,type_:()=>Ji_,webhook:()=>mKs,websocket:()=>Yi_});var OKs={};Io(OKs,{AuthSchemeId:()=>$i_});function $i_(e){return e}var Gi_={};var Qi_={};var Ji_={};var mKs={};Io(mKs,{WebhookHttpMethod:()=>Ki_});var Ki_={Get:"GET",Post:"POST"};var Yi_={};var MKs={};Io(MKs,{SubpackageId:()=>on_,WebSocketMessageId:()=>un_,WebSocketMessageOrigin:()=>sn_,WebhookHttpMethod:()=>cn_,commons:()=>EKs,db:()=>jKs,read:()=>SKs,register:()=>DKs});var jKs={};Io(jKs,{endpoint:()=>Xi_});var Xi_={};var SKs={};Io(SKs,{SupportedLanguage:()=>Zi_,endpoint:()=>wKs,type_:()=>ki_,webhook:()=>en_,websocket:()=>tn_});var wKs={};Io(wKs,{SupportedLanguage:()=>Zi_});var Zi_={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var ki_={};var en_={};var tn_={};var DKs={};Io(DKs,{SourceId:()=>FQD,endpoint:()=>rn_,type_:()=>in_,webhook:()=>nn_,websocket:()=>an_});var rn_={};var in_={};var nn_={};var an_={};function FQD(e){return e}var EKs={};Io(EKs,{SubpackageId:()=>on_,WebSocketMessageId:()=>un_,WebSocketMessageOrigin:()=>sn_,WebhookHttpMethod:()=>cn_});function on_(e){return e}function un_(e){return e}var sn_={Client:"client",Server:"server"};var cn_={Get:"GET",Post:"POST"};var qKs={};Io(qKs,{ApiDefinitionId:()=>ln_,ApiId:()=>_n_,Availability:()=>An_,DocsConfigId:()=>hn_,EndpointId:()=>vn_,EndpointPathLiteral:()=>En_,EnvironmentId:()=>yn_,FileId:()=>Pn_,HttpMethod:()=>Mn_,JqString:()=>wn_,OrgId:()=>dn_,PageId:()=>mn_,PropertyKey:()=>Sn_,RoleId:()=>Dn_,TokenId:()=>pn_,TypeId:()=>On_,Url:()=>jn_,VersionId:()=>fn_,WebSocketId:()=>bn_,WebhookId:()=>gn_});function ln_(e){return e}function fn_(e){return e}function dn_(e){return e}function pn_(e){return e}function _n_(e){return e}function hn_(e){return e}function yn_(e){return e}function vn_(e){return e}function bn_(e){return e}function gn_(e){return e}function On_(e){return e}function mn_(e){return e}function Pn_(e){return e}function jn_(e){return e}function wn_(e){return e}function Sn_(e){return e}function Dn_(e){return e}function En_(e){return e}var Mn_={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var An_={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var qn_={};var FKs={};Io(FKs,{latest:()=>BKs,v1:()=>RKs,v2:()=>NKs});var BKs={};Io(BKs,{Layout:()=>Cn_,MdxEngine:()=>LQD,TwitterCardSetting:()=>Bn_,commons:()=>Tn_,frontmatter:()=>TKs,seo:()=>CKs});var LQD={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var Tn_={};var TKs={};Io(TKs,{Layout:()=>Cn_});var Cn_={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var CKs={};Io(CKs,{TwitterCardSetting:()=>Bn_});var Bn_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var RKs={};Io(RKs,{commons:()=>zKs,db:()=>xn_,read:()=>In_,write:()=>xKs});var xn_={};var In_={};var xKs={};Io(xKs,{DocsRegistrationId:()=>VQD,FilePath:()=>UQD});function UQD(e){return e}function VQD(e){return e}var zKs={};Io(zKs,{ContentAlignment:()=>Fn_,FontDisplay:()=>Hn_,FontStyle:()=>Wn_,HeaderPosition:()=>Ln_,JsScriptStrategy:()=>Vn_,ProgrammingLanguage:()=>zn_,SearchbarPlacement:()=>Rn_,TabsPlacement:()=>Nn_,TwitterCardSetting:()=>Un_,commons:()=>IKs});var IKs={};Io(IKs,{ContentAlignment:()=>Fn_,FontDisplay:()=>Hn_,FontStyle:()=>Wn_,HeaderPosition:()=>Ln_,JsScriptStrategy:()=>Vn_,ProgrammingLanguage:()=>zn_,SearchbarPlacement:()=>Rn_,TabsPlacement:()=>Nn_,TwitterCardSetting:()=>Un_});var zn_={Typescript:"typescript",Javascript:"javascript",Python:"python",Java:"java",Go:"go",Ruby:"ruby",Csharp:"csharp",Nodets:"nodets",Nodejs:"nodejs",Dotnet:"dotnet",Curl:"curl",Jvm:"jvm",Ts:"ts",Js:"js"};var Rn_={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var Nn_={Header:"HEADER",Sidebar:"SIDEBAR"};var Fn_={Center:"CENTER",Left:"LEFT"};var Ln_={Fixed:"FIXED",Absolute:"ABSOLUTE"};var Un_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var Vn_={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var Wn_={Normal:"normal",Italic:"italic"};var Hn_={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var NKs={};Io(NKs,{read:()=>$n_,write:()=>Gn_});var $n_={};var Gn_={};var UKs={};Io(UKs,{ChangelogEntryType:()=>Jn_,GeneratorId:()=>WQD,GeneratorLanguage:()=>HQD,ReleaseType:()=>Kn_,cli:()=>Qn_,commons:()=>LKs,versions:()=>Yn_});var Qn_={};var LKs={};Io(LKs,{ChangelogEntryType:()=>Jn_,ReleaseType:()=>Kn_});var Jn_={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var Kn_={Ga:"GA",Rc:"RC"};var Yn_={};function WQD(e){return e}var HQD={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var VKs={};Io(VKs,{PullRequestState:()=>Xn_});var Xn_={Open:"open",Closed:"closed",Merged:"merged"};var $Ks={};Io($Ks,{latest:()=>WKs,v1:()=>HKs});var WKs={};Io(WKs,{NodeId:()=>QQD,ProductId:()=>JQD,Slug:()=>$QD,TabId:()=>GQD});function $QD(e){return e}function GQD(e){return e}function QQD(e){return e}function JQD(e){return e}var HKs={};Io(HKs,{NavigationV1Availability:()=>kQD,NodeId:()=>XQD,ProductId:()=>ZQD,Slug:()=>KQD,TabId:()=>YQD});function KQD(e){return e}function YQD(e){return e}function XQD(e){return e}function ZQD(e){return e}var kQD={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var QKs={};Io(QKs,{Language:()=>Zn_,VersionBump:()=>kn_,versions:()=>GKs});var GKs={};Io(GKs,{Language:()=>Zn_,VersionBump:()=>kn_});var Zn_={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var kn_={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var ea_={};var ta_={};var JKs={};Io(JKs,{PayloadLocation:()=>ra_});var ra_={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var ia_={};var P1n=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function xd(e){return e!=null}var aa_=vi(wkn(),1);var na_=["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 uXt(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,aa_.default)(e,{special:na_}).replace(/V\s(\d)/g,"V$1")}function zzo({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let u=[...n,a],l=I_.api.v1.SubpackageId(u.join("."));r[l]={id:l,name:a,displayName:uXt(a)},n.push(a)})}),r}var Rzo=class{errors=new P1n},j1n=class{input;context;constructor(t,r){this.input=t,this.context=r}errors(){return this.context.errors.errors}warnings(){return this.context.errors.warnings}};function oa_(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var Nzo=class extends Rzo{},Rp=class extends j1n{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){if(super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,n!=null){let a=Array.isArray(this.pathId)?this.pathId:[this.pathId];a.every((u,l)=>u===this.accessPath[this.accessPath.length-a.length+l])||this.accessPath.push(...a)}r.logger.debug(`Processing ${oa_(this.accessPath)}`)}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}},nF=class extends Rp{},yie=class extends nF{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var ua_="x-fern-base-path",sa_="x-fern-availability",Fzo="x-fern-sdk-group-name",ca_="x-fern-global-headers",la_="x-fern-sdk-method-name";var fa_="x-fern-webhook",da_="x-fern-access-token-locator",pa_="x-fern-basic",_a_="x-fern-username-variable-name",ha_="x-fern-password-variable-name",ya_="x-fern-bearer",va_="x-fern-token-variable-name",ba_="x-fern-header",ga_="x-fern-header-variable-name",Oa_="x-fern-server-name",ma_="x-fern-examples";var Lzo=class extends Rp{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[Oa_]}convert(){if(this.serverName!=null)return this.serverName}};var Uzo=class extends Rp{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,i])=>t.replace(`{${r}}`,i.default),this.input.url)??this.input.url,this.serverName=new Lzo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.serverName?.convert()??this.url;if(!(this.url==null||t==null))return{id:I_.EnvironmentId(t),baseUrl:this.url}}};function sXt(e,t,r,i){let n=e??[],a=new Set(n.map(l=>l.url)),u=(t??[]).filter(l=>!a.has(l.url)).map((l,d)=>new Uzo({input:l,context:r,accessPath:i,pathId:["servers",`${d}`]}));return[...n,...u]}function Y1(e){return typeof e=="object"&&xd(e)&&"$ref"in e&&typeof e.$ref=="string"}function sV(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(Y1(n)&&(n=sV(n,t,r)),n)}function Vzo(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return Y1(r)?sV(r,t,void 0):r}var Ba_=vi(ex());var Wzo=class extends Rp{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[pa_];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var Hzo=class extends Rp{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[ha_]}convert(){return this.passwordVariableName}};var $zo=class extends Rp{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[_a_]}convert(){return this.usernameVariableName}};var Gzo=class extends Rp{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[ya_];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var Qzo=class extends Rp{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[va_]}convert(){return this.tokenVariableName}};function Pa_(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var ja_="x-bearer-format",wa_="x-code-samples",Sa_="x-codeSamples";var Jzo=class extends Rp{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[ja_]}convert(){return this.bearerFormat}};var Kzo=class extends Rp{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[ba_];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var Yzo=class extends Rp{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[ga_]}convert(){return this.headerVariableName}};function Da_(e){return e.type==="apiKey"}var w1n=class extends Rp{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){Da_(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new Kzo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new Yzo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new Jzo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.headerAuthNode?.convert();if(t!=null)return{type:"header",nameOverride:t?.name,headerWireValue:this.headerName??"Authorization",prefix:t?.prefix??this.headerBearerFormatNode?.convert()}}};function Ea_(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function Ma_(e){return Object.is(e,-0)?"-0":e.toString()}function Aa_(e){let t=[],r=e.length;if(r===0)return t;let i=0,n="",a="",u=!1;for(e.charCodeAt(0)===46&&(t.push(""),i++);i<r;){let l=e[i];a?l==="\\"&&i+1<r?(i++,n+=e[i]):l===a?a="":n+=l:u?l==='"'||l==="'"?a=l:l==="]"?(u=!1,t.push(n),n=""):n+=l:l==="["?(u=!0,n&&(t.push(n),n="")):l==="."?n&&(t.push(n),n=""):n+=l,i++}return n&&t.push(n),t}function KKs(e,t,r){if(e==null)return r;switch(typeof t){case"string":{let i=e[t];return i===void 0?Ea_(t)?KKs(e,Aa_(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=Ma_(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return eJD(e,t,r);Object.is(t?.valueOf(),-0)?t="-0":t=String(t);let i=e[t];return i===void 0?r:i}}}function eJD(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null)return r;i=i[t[n]]}return i===void 0?r:i}function qa_(e){return function(t){return KKs(t,e)}}function Xzo(e,t){switch(t=t??qe_,typeof t){case"string":case"symbol":case"number":case"object":return f5(e,qa_(t));case"function":return f5(e,t)}}function YKs(e){if(e==null)return"";if(Array.isArray(e))return e.map(YKs).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function Ta_(e){return typeof e!="string"&&(e=YKs(e)),e.replace(/['\u2019]/g,"")}function b5t(e){return ae_(Ta_(e))}function mM(e){if(e!=null)return Array.isArray(e)?e:[e]}function Zzo({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,displayName:a,isWebhook:u}){if(t==null)return;let l=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(i==null&&n==null&&a==null&&l==null))return`${tJD(u)}${rJD(e)}.${iJD(i,n,a,l)}`}function tJD(e){return e?"webhook_":"endpoint_"}function rJD(e){return e!=null?mM(e)?.map(t=>b5t(t)).join("/"):""}function iJD(e,t,r,i){return e||t||b5t(r??"")||b5t(i??"")}function Ca_(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var kzo=class extends Rp{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[da_],this.accessTokenLocator!=null&&(Ca_(this.accessTokenLocator)||(this.context.errors.error({message:"Invalid access token locator, must be a valid jq path",path:this.accessPath}),this.accessTokenLocator=void 0))}convert(){return this.accessTokenLocator}};var eRo=class extends Rp{authorizationUrl;headerAuthNode;accessTokenLocatorNode;constructor(t){super(t),this.safeParse()}parse(){if(this.input.flows.clientCredentials!=null){let t=this.input.flows.clientCredentials;this.authorizationUrl=t.tokenUrl,this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.headerAuthNode=new w1n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new kzo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.accessTokenLocatorNode?.accessTokenLocator==null&&this.context.errors.error({message:"Expected 'x-fern-access-token-locator' property to be specified",path:this.accessPath})}}convert(){let t=this.accessTokenLocatorNode?.convert();if(t==null||this.authorizationUrl==null)return{type:"bearerAuth",tokenName:void 0};let r=Zzo({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,displayName:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:I_.EndpointId(r),accessTokenLocator:I_.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var S1n=class extends Rp{authScheme;headerAuthNode;bearerTokenNode;bearerTokenVariableNameNode;basicAuthNode;basicUsernameVariableNameNode;basicPasswordVariableNameNode;oauth2Node;constructor(t){super(t),this.safeParse()}parse(){switch(this.input.type){case"http":switch(this.input.scheme){case"basic":{this.authScheme="basic",this.basicAuthNode=new Wzo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new $zo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new Hzo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),(this.basicAuthNode==null||this.basicAuthNode.username==null&&this.basicUsernameVariableNameNode?.usernameVariableName==null||this.basicAuthNode.password==null&&this.basicPasswordVariableNameNode?.passwordVariableName==null)&&this.context.errors.warning({message:"Basic auth should specify either a username or a username variable name",path:this.accessPath});break}case"bearer":{this.authScheme="bearer",this.bearerTokenNode=new Gzo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new Qzo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}default:{this.context.errors.warning({message:`Unsupported HTTP auth scheme: ${this.input.scheme}`,path:this.accessPath});break}}break;case"apiKey":{Pa_(this.input)?(this.authScheme="header",this.headerAuthNode=new w1n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})):this.context.errors.error({message:`Unsupported API key location: ${this.input.in}`,path:this.accessPath});break}case"oauth2":{this.authScheme="oauth",this.oauth2Node=new eRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}case"openIdConnect":{this.authScheme="bearer";break}}}convert(){switch(this.authScheme){case"basic":{let t=this.basicAuthNode?.convert();return{type:"basicAuth",usernameName:t?.username?.name??this.basicUsernameVariableNameNode?.convert(),passwordName:t?.password?.name??this.basicPasswordVariableNameNode?.convert()}}case"bearer":return{type:"bearerAuth",tokenName:this.bearerTokenNode?.convert()?.tokenVariableName??this.bearerTokenVariableNameNode?.convert()};case"header":return this.headerAuthNode?.convert();case"oauth":return this.oauth2Node?.convert();case void 0:return;default:new Ba_.UnreachableCaseError(this.authScheme);return}}};var D1n=class extends Rp{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=Vzo(i,this.context.document);if(n==null){this.context.errors.warning({message:`No auth scheme found for ${i}. Inline security schemes are not supported.`,path:this.accessPath});return}let a=new S1n({input:n,context:this.context,accessPath:this.accessPath,pathId:["security",`${r}`]});a.convert()!=null?(this.authNodesMap??={},this.authNodesMap[i]=a):this.context.errors.warning({message:`No auth scheme found for ${i}`,path:this.accessPath})}))}convert(){return Object.fromEntries(Object.entries(this.authNodesMap??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[t,i]}).filter(xd))}};var tRo=class extends Rp{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[ua_],this.basePath!=null?(this.basePath.startsWith("/")&&(this.basePath=this.basePath.slice(1)),this.basePath.endsWith("/")&&(this.basePath=this.basePath.slice(0,-1))):this.basePath=void 0}convert(){return this.basePath}};function xa_(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function Ia_(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function E1n(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>mM(n.convert())?.map(u=>((t!=null&&!t.includes(i)||t==null&&!xa_(n))&&(u=Ia_(u,u.type==="enum"?u.default:void 0)),{key:I_.PropertyKey(i),valueShape:u,description:n.description,availability:n.availability?.convert()})).filter(xd)).filter(xd).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]])}function rRo(e,t){return Y1(e)?sV(e,t,void 0):e}function Kfi(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function za_(e,t){let r={...e};for(let[i,n]of Object.entries(t??{}))r[i]=[...r[i]??[],...n];return Object.keys(r).length>0?r:void 0}function Ra_(e,t){if(e==null)return t;if(t==null)return e;let r=[];for(let i of e)for(let n of t)r.push({path:i.path??n.path,responseStatusCode:i.responseStatusCode??n.responseStatusCode,name:i.name??n.name,description:i.description??n.description,pathParameters:i.pathParameters??n.pathParameters,queryParameters:i.queryParameters??n.queryParameters,headers:i.headers??n.headers,requestBody:i.requestBody??n.requestBody,responseBody:i.responseBody??n.responseBody,snippets:{...n.snippets,...i.snippets}});return r}var Na_=vi(ex());var XKs=["decimal","decimal128","double-int","double","float","sf-decimal"],ZKs=["int16","int32","int64","int8","sf-integer","uint8"],kKs=["base64url","binary","byte","char","commonmark","date-time","date","decimal","decimal128","duration","email","hostname","html","http-date","idn-email","idn-hostname","int64","ipv4","ipv6","iri-reference","iri","json-pointer","media-range","password","regex","relative-json-pointer","sf-binary","sf-boolean","sf-string","sf-token","time","uri-reference","uri-template","uri","uuid"],eYs=["beta","pre-release","in-development","generally-available","deprecated"];function aF(e,t){return Y1(e)?sV(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var nze=class extends Rp{availability;constructor(t){super(t),this.safeParse()}parse(){if(aF(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[sa_];r!=null&&(eYs.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${eYs.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return I_.Availability.Beta;case"in-development":return I_.Availability.InDevelopment;case"generally-available":return I_.Availability.GenerallyAvailable;case"deprecated":return I_.Availability.Deprecated;case void 0:return;default:new Na_.UnreachableCaseError(this.availability);return}}};var nRo=vi(ex());function Fa_(e){return typeof e=="object"&&e!=null&&"language"in e}function La_(e){return typeof e=="object"&&e!=null&&"sdk"in e}function Ua_(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function Va_(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function iRo(e){return typeof e=="object"&&e!=null&&"event"in e}function tYs(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(iRo)}function Yfi(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function Wa_(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var aRo=class extends Rp{path;successResponseStatusCode;requestBodyByContentType;responseBodies;examples;constructor(t,r,i,n,a){super(t),this.path=r,this.successResponseStatusCode=i,this.requestBodyByContentType=n,this.responseBodies=a,this.safeParse()}parse(){this.examples=this.input[ma_]}convertFormDataExampleRequest(t,r){if(t.fields!=null)switch(t.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(t.fields).map(([n,a])=>{let u=typeof r=="object"?r[n]:void 0;switch(a.multipartType){case"file":return Yfi(u)?[n,{type:"filenameWithData",filename:u.filename,data:I_.FileId(u.data)}]:u!=null?[n,{type:"filename",value:u}]:void 0;case"files":{if(Array.isArray(u)){if(u.every(l=>Yfi(l)))return[n,{type:"filenamesWithData",value:u.map(l=>({filename:l.filename,data:I_.FileId(l.data)}))}];if(u.every(l=>typeof l=="string"))return[n,{type:"filenames",value:u}]}return}case"property":return[n,{type:"json",value:u}];case void 0:return;default:new nRo.UnreachableCaseError(a.multipartType);return}}).filter(xd))};case"json":return{type:"json",value:r};case"bytes":return typeof r=="string"?{type:"bytes",value:{type:"base64",value:r}}:void 0;default:return}}convert(){if(this.examples==null)return;this.requestBodyByContentType!=null&&Object.keys(this.requestBodyByContentType).length>1&&this.context.logger.warn(`Multiple request bodies found for #/${[this.accessPath,this.pathId,"x-fern-examples"].join("/")}. Coercing to first request body until supported.`);let t=Object.keys(this.requestBodyByContentType??{})[0];return this.examples.flatMap(r=>(this.responseBodies??[]).map(i=>{let n=t!=null?this.requestBodyByContentType?.[t]:void 0,a;if(n!=null)switch(n.contentType){case"form-data":a=Wa_(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a=r.request!=null?{type:"json",value:r.request}:void 0;break;case"bytes":a=typeof r.request=="string"&&r.request!=null?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new nRo.UnreachableCaseError(n.contentType);break}let u;switch(i.contentType){case"application/json":{Ua_(r.response)&&(u={type:"json",value:r.response.body});break}case"text/event-stream":{tYs(r.response)&&(u={type:"sse",value:r.response.stream.map(c=>({event:c.event,data:c.data}))});break}case"application/octet-stream":!tYs(r.response)&&Va_(r.response)&&(u={type:"stream",value:r.response.stream});break;case void 0:break;default:new nRo.UnreachableCaseError(i.contentType);break}let l={};r["code-samples"]?.forEach(c=>{Fa_(c)?c.language!=null&&(l[c.language]??=[],l[c.language]?.push({name:c.name,language:c.language,install:c.install,code:c.code,generated:!1,description:c.docs})):La_(c)&&c.sdk!=null&&(l[c.sdk]??=[],l[c.sdk]?.push({name:c.name,language:c.sdk,install:void 0,code:c.code,generated:!1,description:c.docs}))});let d=Object.fromEntries(Object.entries(r["path-parameters"]??{}).map(([c,b])=>[I_.PropertyKey(c),b])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([c,b])=>[I_.PropertyKey(c),b])),o=Object.fromEntries(Object.entries(r.headers??{}).map(([c,b])=>[I_.PropertyKey(c),b]));return{path:this.path,responseStatusCode:this.successResponseStatusCode,name:r.name,description:r.docs,pathParameters:Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,headers:Object.keys(o).length>0?o:void 0,requestBody:a,responseBody:u,snippets:l}}))}};var G_a=class extends Rp{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[Fzo]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>I_.api.v1.SubpackageId(b5t(r)))}};var oRo=class extends Rp{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[la_]}convert(){return this.sdkMethodName}};var uRo=class extends Rp{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[fa_]}convert(){return this.isWebhook}};var sRo=class extends Rp{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[wa_]??[],...this.input[Sa_]??[]],this.codeSamples.forEach(t=>{[...Object.values(I_.api.v1.read.SupportedLanguage),"Kotlin","Swift","PHP"].map(r=>r.toLowerCase()).includes(t.lang.toLowerCase())||this.context.errors.warning({message:`Unsupported language: ${t.lang}. This may not render correctly.`,path:this.accessPath})})}convert(){let t={};if(this.codeSamples?.forEach(r=>{t[r.lang.toLowerCase()]??=[],t[r.lang.toLowerCase()]?.push({name:r.label,language:r.lang,code:r.source,install:void 0,generated:!1,description:void 0})}),Object.keys(t).length!==0)return t}};var Yzi=vi(ex());function rYs(e,t){return Y1(e)?sV(e,t,void 0):e}function Ha_(e,t){return e.replace(/{(\w+)}/g,(r,i)=>t[i]!=null&&typeof t[i]=="string"||typeof t[i]=="number"||typeof t[i]=="boolean"?`${t[i]}`:r)}var y5="",cXt=class extends Rp{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,i,n,a){super(t),this.path=r,this.responseStatusCode=i,this.name=n,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,i])=>{let n=this.resolvedRequestInput?.value[r];switch(i.multipartType){case"file":return t&&(Yfi(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>Yfi(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new Yzi.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=rYs(this.input?.requestExample,this.context.document)??(t!=null?{value:t}:void 0);let r=this.shapes.responseBody?.schema?.example({includeOptionals:!1,override:void 0});if(this.resolvedResponseInput=rYs(this.input?.responseExample,this.context.document)??(r!=null?{value:r}:void 0),this.summary=this.input?.requestExample?.summary??this.input?.responseExample?.summary,this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody?.contentType){case"json":{if(typeof this.resolvedRequestInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break}case"bytes":{if(typeof this.resolvedRequestInput.value!="string"){this.context.errors.error({message:"Invalid example, expected string for bytes",path:this.accessPath});return}break}case"form-data":{if(!this.validateFormDataRequestExample()){this.context.errors.error({message:"Invalid example, expected valid form-data",path:this.accessPath});return}break}case void 0:break;default:new Yzi.UnreachableCaseError(this.shapes.requestBody?.contentType),this.context.errors.error({message:"Invalid example, unsupported content type",path:this.accessPath});return}if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody?.contentType){case"application/json":if(this.resolvedResponseInput!=null&&typeof this.resolvedResponseInput!="object"||this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break;case"text/event-stream":if(this.resolvedResponseInput.value!=null&&!Array.isArray(this.resolvedResponseInput.value)&&!this.resolvedResponseInput.value.every(iRo)){this.context.errors.error({message:"Invalid example, expected array of SSE events for event-stream",path:this.accessPath});return}break;case"application/octet-stream":if(this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="string"&&!Array.isArray(this.resolvedResponseInput.value)){this.context.errors.error({message:"Invalid example, expected string or array for octet-stream",path:this.accessPath});return}break;case void 0:break;default:new Yzi.UnreachableCaseError(this.shapes.responseBody?.contentType);return}}convertFormDataExampleRequest(){if(!(this.resolvedRequestInput==null||this.shapes.requestBody?.fields==null))switch(this.shapes.requestBody?.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(this.shapes.requestBody.fields).map(([r,i])=>{let n=this.resolvedRequestInput?.value?.[r];switch(i.multipartType){case"file":return Yfi(n)?[r,{type:"filenameWithData",filename:n.filename,data:I_.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>Yfi(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:I_.FileId(a.data)}))}];if(n.every(a=>typeof a=="string"))return[r,{type:"filenames",value:n}]}return}case"property":return[r,{type:"json",value:n}];case void 0:return;default:new Yzi.UnreachableCaseError(i.multipartType);return}}).filter(xd))};case"json":return{type:"json",value:this.resolvedRequestInput.value};case"bytes":return typeof this.resolvedRequestInput.value=="string"?{type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}}:void 0;default:return}}convertDescription(){if(this.resolvedRequestInput!=null&&this.resolvedResponseInput!=null)return this.resolvedResponseInput.description;if(this.resolvedRequestInput!=null)return this.resolvedRequestInput.description;if(this.resolvedResponseInput!=null)return this.resolvedResponseInput.description}convert(){let t;if(this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody.contentType){case"form-data":t=this.convertFormDataExampleRequest();break;case"json":t={type:"json",value:this.resolvedRequestInput.value};break;case"bytes":t={type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}};break;case void 0:break;default:new Yzi.UnreachableCaseError(this.shapes.requestBody?.contentType);break}let r;if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody.contentType){case"application/json":{r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break}case"text/event-stream":r={type:"sse",value:this.resolvedResponseInput?.value};break;case"application/octet-stream":r={type:typeof this.resolvedResponseInput?.value=="string"?"filename":"stream",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;case void 0:r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;default:new Yzi.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([u,l])=>[u,l.example({includeOptionals:!1,override:u})]));i=Object.keys(i).length>0?i:void 0;let n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([u,l])=>l.required||l.inputExample!=null?[u,l.example({includeOptionals:!1,override:u})]:void 0).filter(xd));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([u,l])=>l.required||l.inputExample!=null?[u,l.example({includeOptionals:!1,override:u})]:void 0).filter(xd));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&n==null&&i==null))return{path:Ha_(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?uXt(this.name):this.summary!=null?uXt(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function $a_(e,t){return Y1(e)?sV(e,t,void 0):e}var no_=vi(ex());var Ga_="#/components/schemas/";function M1n(e){if(e.$ref.startsWith(Ga_))return e.$ref.replace(Ga_,"")}function UQr(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function Xfi(e){return typeof e.type=="string"&&e.type==="array"}function Qa_(e){return e.type==="boolean"}function Ja_(e){return e.type==="integer"}function Zfi(e){return!Array.isArray(e.type)&&!Xfi(e)}function Ka_(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||Zfi(t)||Xfi(t))}function Ya_(e){return"nullable"in e&&typeof e.nullable=="boolean"}function Xa_(e){return e.type==="null"}function Za_(e){return e.type==="number"}function iYs(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function ka_(e){return e.type==="string"}var cRo=class extends yie{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new FA({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items",seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return mM(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(t){return this.input.example??this.input.examples?.[0]??[this.item?.example(t)]}};var lRo=class extends nF{constValue;description;availability;constructor(t){super(t),this.safeParse()}parse(){this.input.const!=null&&(typeof this.input.const=="string"||typeof this.input.const=="number"||typeof this.input.const=="boolean")?this.constValue=this.input.const.toString():this.context.errors.warning({message:`Unsupported const type: ${typeof this.input}`,path:this.accessPath}),this.description=this.input.description,this.availability=new nze({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"})}convert(){if(this.constValue!=null)return{type:"enum",default:this.constValue,values:[{value:this.constValue,description:this.description,availability:this.availability?.convert()}]}}example(){return this.input.example??this.input.examples?.[0]??this.constValue}};var fRo=class extends yie{typeNodes;nullable;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new FA({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(xd)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>mM(n.convert())?.map(u=>({displayName:n.name,shape:u,description:n.description,availability:n.availability?.convert()}))).filter(xd).reduce((n,a)=>n.flatMap(u=>a.length>0?a.map(l=>[...u,l]):[[...u]]),[[]]).map(n=>({type:"undiscriminatedUnion",variants:n}));return this.nullable?i.map(UQr).filter(xd):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function dRo(e){return e!=null&&e.length>0?e:[void 0]}var A1n=class extends yie{description;extends=[];properties;extraProperties;requiredProperties;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new FA({input:r,context:this.context,accessPath:this.accessPath,pathId:["properties",t],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new FA({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:["additionalProperties"],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map((t,r)=>{if(Y1(t))return M1n(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new FA({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(xd))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return E1n(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:{type:"alias",value:{type:"unknown",displayName:this.extraProperties}}}]:mM(this.extraProperties.convert())?.map(r=>({type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:r})).filter(xd)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>dRo(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:n}:{type:"object",extends:this.extends.map(a=>I_.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=aF(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,u])=>[a,new FA({input:u,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))})}),this.input.example??this.input.examples?.[0]??(!t&&this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((i,n)=>{let a=r?.[n];return i[n]=a?.example({includeOptionals:t,override:n}),i},{}):Object.entries(r).reduce((i,[n,a])=>(i[n]=a?.example({includeOptionals:t,override:n}),i),{}))}};var pRo=class extends yie{isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>aF(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>aF(t,this.context.document)?.type!=="null"?new FA({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(xd);else{let t=this.input.discriminator.mapping;if(t!=null){this.discriminated=!0,this.discriminant=this.input.discriminator.propertyName,this.discriminatedMapping={};let r=this.discriminatedMapping;Object.entries(t).map(([i,n])=>{let a=aF({$ref:n},this.context.document);if(a==null){this.context.errors.warning({message:`Expected schema reference. Received undefined reference: ${n}`,path:[...this.accessPath,"discriminator","mapping",i]});return}r[i]=new FA({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let n=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(xd);return this.isNullable&&n!=null?n.map(UQr).filter(xd):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:I_.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>mM(a.convert())?.map(l=>{if(!(l==null||l.type!=="object"))return{discriminantValue:n,displayName:a.name??uXt(n),availability:a.availability?.convert(),description:a.description,...l}}).filter(xd)).filter(xd)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>mM(n.convert())?.map(u=>{if(u==null)return;t+=1;let l=u.type==="object"?uXt(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(u.type==="alias"&&u.value.type==="id"?uXt(u.value.id):l),shape:u,description:n.description,availability:n.availability?.convert()}}).filter(xd)).filter(xd)}:void 0,i=this.isNullable?UQr(r):r;return i!=null?[i]:void 0}example(t){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example(t)??Object.values(this.discriminatedMapping??{})[0]?.example(t)}};var _Ro=class extends nF{default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.input.default!=null&&typeof this.input.default!="boolean"&&this.context.errors.warning({message:`Expected default value to be a boolean. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default}convert(){return{type:"alias",value:{type:"primitive",value:{type:"boolean",default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:!1)}};var kfi=class extends nF{default;values=[];nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(Y1(r)){let n=aF(r,this.context.document);r=typeof n=="string"?n:typeof n?.default=="string"?n?.default:typeof n?.example=="string"?n.example:void 0}if(typeof r!="string"){this.context.errors.error({message:`Expected enum values to be strings. Received ${r}`,path:[...this.accessPath,`enum[${i}]`]}),t=!1;return}return r}}).filter(xd),this.values=Array.from(new Set(this.values))}this.default=this.input.default}convert(){return{type:"enum",values:this.values.map(t=>({value:t,description:void 0,availability:void 0})),default:this.default}}example(){return this.input.example??this.input.examples?.[0]??this.default??this.values[0]??(this.nullable?null:void 0)}};var eo_=vi(ex());function nJD(e){return ZKs.includes(e)}var hRo=class extends nF{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be an integer. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(nJD(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${ZKs.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="integer";if(this.format!=null)switch(this.format){case"int64":t="long";break;case"int8":case"int16":case"int32":case"uint8":case"sf-integer":case void 0:t="integer";break;default:new eo_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var yRo=class extends nF{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return UQr({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var to_=vi(ex());function aJD(e){return XKs.includes(e)}var vRo=class extends nF{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be a number. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(aJD(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${XKs.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="double";if(this.format!=null)switch(this.format){case"decimal":case"decimal128":case"double-int":case"double":case"float":case"sf-decimal":case void 0:t="double";break;default:new to_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var ro_=vi(ex());function oJD(e){return kKs.includes(e)}var bRo=class extends nF{format;regex;default;minLength;maxLength;enum;mimeType;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}mapToFdrType(t){switch(t){case"base64url":case"binary":case"byte":case"sf-binary":return"base64";case"date-time":return"datetime";case"int64":return"bigInteger";case"date":return"date";case"uuid":return"uuid";case"char":case"commonmark":case"decimal":case"decimal128":case"duration":case"email":case"hostname":case"html":case"http-date":case"idn-email":case"idn-hostname":case"ipv4":case"ipv6":case"iri-reference":case"iri":case"json-pointer":case"media-range":case"password":case"regex":case"relative-json-pointer":case"sf-boolean":case"sf-string":case"sf-token":case"time":case"uri-reference":case"uri-template":case"uri":case void 0:return"string";default:return new ro_.UnreachableCaseError(t),"string"}}parse(){this.regex=this.input.pattern,this.minLength=this.input.minLength,this.maxLength=this.input.maxLength,this.mimeType=this.input.contentMediaType,this.input.default!=null&&typeof this.input.default!="string"&&this.context.errors.warning({message:`Expected default value to be a string. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(oJD(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${kKs.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new kfi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum",nullable:this.nullable}))}convert(){if(this.enum!=null)return this.enum.convert();let t="string";return this.format!=null&&(t=this.mapToFdrType(this.format)),{type:"alias",value:{type:"primitive",value:t==="base64"?{type:t,mimeType:this.mimeType,default:this.default}:{type:t,format:t==="string"?this.format:void 0,regex:this.regex,minLength:this.minLength,maxLength:this.maxLength,default:this.default}}}}example({override:t}){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:t??"string")}};var io_=vi(ex());var gRo=class extends nF{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,io_.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var Xzi=class extends yie{description;availability;schemaId;maybeEnumConverterNode;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.description=t.description,this.availability=t.availability,this.safeParse()}parse(){this.schemaId=M1n(this.input);let t=aF(this.input,this.context.document);t?.enum!=null&&Zfi(t)&&(this.maybeEnumConverterNode=new kfi({input:t,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",nullable:this.nullable})),this.schemaId==null&&this.context.errors.error({message:`Unprocessable reference: ${this.input.$ref}`,path:this.accessPath})}convert(){if(this.schemaId!=null)return{type:"alias",value:{type:"id",id:I_.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=aF(this.input,this.context.document);if(r!=null)return new FA({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var FA=class e extends yie{typeShapeNode;description;name;examples;availability;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new nze({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),Zfi(this.input)&&Ya_(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),Y1(this.input)){let t=M1n(this.input);if(t==null){this.context.errors.error({message:"Reference object does not have a valid schema ID",path:this.accessPath});return}if(this.seenSchemas.has(t)){this.context.errors.warning({message:"Circular or deeply nested schema found, terminating",path:this.accessPath});return}this.seenSchemas.add(t),this.typeShapeNode=new Xzi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName,description:this.description,availability:this.availability})}else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new lRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(Ka_(this.input))this.typeShapeNode=new fRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(Zfi(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new pRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(iYs(this.input)&&this.input.allOf!=null)this.typeShapeNode=new A1n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(Zfi(this.input)&&this.input.enum!=null)this.typeShapeNode=new kfi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string"||Array.isArray(this.input.type)&&this.input.type.length===1){if(this.input.type=Array.isArray(this.input.type)?this.input.type[0]:this.input.type,!Array.isArray(this.input.type))switch(this.input.type){case"object":iYs(this.input)&&(this.typeShapeNode=new A1n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":Xfi(this.input)&&(this.typeShapeNode=new cRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":Qa_(this.input)&&(this.typeShapeNode=new _Ro({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":Ja_(this.input)&&(this.typeShapeNode=new hRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":Za_(this.input)&&(this.typeShapeNode=new vRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":ka_(this.input)&&(this.typeShapeNode=new bRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":Xa_(this.input)&&(this.typeShapeNode=new yRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new no_.UnreachableCaseError(this.input.type);break}}else if(Array.isArray(this.input.type)&&this.input.type.includes("null")&&this.input.type.length===2){let t=this.input.type.filter(r=>r!=="null")[0];t!=="array"&&(this.typeShapeNode=new e({input:{...this.input,type:t},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:!0,schemaName:this.schemaName}))}else this.input.properties!=null&&(this.typeShapeNode=new A1n({input:{...this.input,type:"object"},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));this.typeShapeNode==null&&(this.typeShapeNode=new gRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!Y1(this.input)&&(!Xfi(this.input)&&this.input==null||Xfi(this.input)&&this.input.items==null)&&this.context.errors.error({message:"Expected type declaration. Received: null",path:this.accessPath}))}convert(){let t=this.typeShapeNode?.convert();if(t==null)return;let r=mM(t)?.map(i=>this.nullable?UQr(i):i).filter(xd);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function edi(e){if(e!=null)return E1n(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(xd))}var lXt=class extends nF{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;Y1(this.input)?r=this.input:this.input.schema!=null?(r=this.input.schema,this.required=this.input.required):(r={type:"string"},this.required=!1),this.availability=new nze({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new FA({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=$a_(this.input,this.context.document);this.inputExample=i?.example??Object.values(i?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function ao_(e,t){return Y1(e)?sV(e,t,void 0):e}var nYs=vi(ex());function ORo(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[I_.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var oo_=vi(jus(),1),q1n=class e{type;subtype;essence;parameters;mimeType;input;constructor(t,r,i,n,a,u){this.type=t,this.subtype=r,this.essence=i,this.parameters=n,this.mimeType=a,this.input=u}static APPLICATION_JSON="application/json";static APPLICATION_OCTET_STREAM="application/octet-stream";static MULTIPART_FORM_DATA="multipart/form-data";static parse(t){if(t==null)return null;let r=oo_.default.parse(t);return r==null?null:new e(r.type,r.subtype,r.essence,r.parameters,r,t)}toString(){return this.input}isText(){return this.type==="text"}isImage(){return this.type==="image"}isAudio(){return this.type==="audio"}isVideo(){return this.type==="video"}isFont(){return this.type==="font"}isMultipart(){return this.type==="multipart"}isApplication(){return this.type==="application"}isMessage(){return this.type==="message"}isModel(){return this.type==="model"}isCSS(){return this.isText()&&this.subtype==="css"}isCSV(){return this.isText()&&this.subtype==="csv"}isMarkdown(){return this.isText()&&this.subtype==="markdown"}isPlainText(){return this.isText()&&this.subtype==="plain"}isEventStream(){return this.isText()&&this.subtype==="event-stream"}isMultiPartFormData(){return this.isMultipart()&&this.subtype==="form-data"}isJSON(){return this.isApplication()&&this.subtype==="json"}containsJSON(){return this.isApplication()&&this.subtype.includes("json")}isURLEncoded(){return this.isApplication()&&this.subtype==="x-www-form-urlencoded"}isOctetStream(){return this.isApplication()&&this.subtype==="octet-stream"}isPDF(){return this.isApplication()&&this.subtype==="pdf"}isZip(){return this.isApplication()&&this.subtype==="zip"}isGzip(){return this.isApplication()&&this.subtype==="gzip"}isTar(){return this.isApplication()&&this.subtype==="tar"}isBrotli(){return this.isApplication()&&this.subtype==="br"}isDeflate(){return this.isApplication()&&this.subtype==="deflate"}isProtobuf(){return this.isApplication()&&this.subtype==="protobuf"}isAvif(){return this.isImage()&&this.subtype==="avif"}isWebP(){return this.isImage()&&this.subtype==="webp"}isSVG(){return this.isImage()&&this.subtype==="svg+xml"}isPNG(){return this.isImage()&&this.subtype==="png"}isJPEG(){return this.isImage()&&this.subtype==="jpeg"}isGIF(){return this.isImage()&&this.subtype==="gif"}isMPEG(){return this.isAudio()&&this.subtype==="mpeg"}isWAV(){return this.isAudio()&&this.subtype==="wav"}isHTML(){return this.mimeType.isHTML()}isXML(){return this.mimeType.isXML()}isJavaScript(){return this.mimeType.isJavaScript()}};function uJD(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var T1n=class extends Rp{typeSchemas;securitySchemes;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas!=null&&(this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new FA({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),uJD(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(Y1(r)?n=Vzo(r.$ref,this.context.document):n=r,n!=null)return[t,new S1n({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(xd)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[I_.api.latest.AuthSchemeId(t),i]}).filter(xd)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=mM(r.convert());return n==null?[t,void 0]:[I_.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>xd(r))):void 0}}};var mRo=class extends FA{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=aF(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${Y1(this.input)?`Received undefined reference: ${this.input.$ref}`:""}`,path:this.accessPath});return}if(t.type==="string"&&t.format==="binary")this.multipartType="file",this.contentType=t.contentMediaType;else if(t.type==="array"){let r=aF(t.items,this.context.document);r?.type==="string"&&r?.format==="binary"?(this.multipartType="files",this.contentType=r?.contentMediaType):(this.context.errors.warning({message:"Expected multipart form data files definition with array type with internal string type and binary format.",path:this.accessPath}),this.multipartType=void 0,this.contentType=void 0)}else this.multipartType="property",this.contentType=t.contentMediaType}};var PRo=class extends Rp{description;method;path;schema;isOptional;contentType;availability;requiredFields;fields;examples;constructor(t){super(t),this.method=t.method,this.path=t.path,this.safeParse(t)}parse({contentType:t}){if(this.input.schema!=null){let i=aF(this.input.schema,this.context.document);this.availability=new nze({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=Y1(this.input.schema)?new Xzi({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:!1,schemaName:"Request Body",description:this.input.schema.description,availability:this.availability}):void 0;let n=q1n.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new FA({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):n?.isOctetStream()?(this.contentType="bytes",this.isOptional=i?.required==null):n?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=i?.required,this.fields=Object.fromEntries(Object.entries(i?.properties??{}).map(([a,u])=>{if(u!=null)return[a,new mRo({input:u,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(xd))):this.context.errors.warning({message:`Expected request body of reference or object with json, streaming or form-data content types. Received: ${t}`,path:this.accessPath})}let r=this.schema?.example({includeOptionals:!0,override:void 0});this.examples={...this.input.example!=null?{[y5]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[y5]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:mM(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=b5t([this.method,this.path,this.contentType,"request"].join("_"));return ORo({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:I_.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new nYs.UnreachableCaseError(n);return}}).filter(xd)}convert(){if(this.schema instanceof Xzi)return this.schema.convert();switch(this.contentType){case"json":return this.convertJsonLike();case"bytes":return{type:"bytes",isOptional:this.isOptional??!1,contentType:this.contentType};case"form-data":return Object.entries(this.fields??{}).map(([i,n])=>{switch(n.multipartType){case"file":return[{type:n.multipartType,key:I_.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"files":return[{type:n.multipartType,key:I_.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=mM(n.convert()),u=n.multipartType;return a?.map(l=>({type:u,key:I_.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:l,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new nYs.UnreachableCaseError(n.multipartType),[]}}).filter(xd).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]]).map(i=>({type:"formData",fields:i,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var jRo=class extends Rp{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=ao_(this.input,this.context.document);if(i==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(i.content).forEach(([n,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[n]=new PRo({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:n,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>mM(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(xd)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>mM(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(xd)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var uo_={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"};function so_(e,t){if(Y1(e)){let r=sV(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var wRo=vi(ex());var co_="application/json";var lo_="application/octet-stream";function fo_(e,t){return e===t||t===y5||e===y5}var Q_a=class extends Rp{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,u,l,d){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=u,this.requests=l,this.shapes=d,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,u]of Object.entries(n?.examples??{}))for(let[l,d]of Object.entries(r))for(let s of d)fo_(l,a)&&(i.add(l),this.examples?.push(new cXt({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,Kfi(a,l),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let i=0;for(let n of t){let a=0;for(let[u,l]of r){if(a===i){let[d,s,o]=n??[void 0,void 0,void 0];this.examples?.push(...l.map(c=>new cXt({input:{requestExample:o,responseExample:c},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,Kfi(s,u),{requestBody:d,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}i++}if(t.length>r.length)for(let n of t.slice(r.length)){let[a,u]=r[r.length-1]??[void 0,void 0],[l,d,s]=n??[void 0,void 0,void 0];this.examples?.push(...(u??[void 0]).map(o=>new cXt({input:{requestExample:s,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:d!=null&&d!==""?["examples",d]:"examples"},this.path,this.statusCode,Kfi(d,a),{requestBody:l,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[n,a,u]=t[t.length-1]??[void 0,void 0,void 0];for(let[l,d]of r.slice(t.length))this.examples?.push(...d.map(s=>new cXt({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,Kfi(a,l),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,i,n){let a=t[y5];if(a!=null)for(let u of a)this.examples?.push(new cXt({input:{requestExample:n,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,Kfi(i,void 0),{requestBody:r,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}))}addGlobalFallbackExample(t,r){if(t==null||t.length===0)this.pushResponseExample(r,void 0,void 0,void 0);else for(let i of t)if(Object.keys(i.examples??{}).length===0)this.pushResponseExample(r,i,void 0,void 0);else for(let[n,a]of Object.entries(i.examples??{}))this.pushResponseExample(r,i,n,a)}parse(t){if(t==="empty")this.empty=!0;else{let l=q1n.parse(t);if(l?.isJSON()||l?.isEventStream())this.contentType=co_,this.input.schema==null?(this.streamingFormat==null||this.streamingFormat==="json")&&this.context.errors.error({message:"Expected schema for JSON response body. Received null",path:this.accessPath}):this.schema=new FA({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type",seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"});else if(l?.isOctetStream())this.contentType=lo_,this.contentSubtype=aF(this.input.schema,this.context.document)?.contentMediaType;else if(this.unsupportedContentType=t,this.input.schema==null){this.context.errors.error({message:"Expected schema for plain text response body. Received null",path:this.accessPath});return}else this.schema=new FA({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"})}let r={};this.input.examples!=null&&(r=Xzo(this.input.examples,l=>[l])),this.input.example!=null&&Object.keys(r).length===0&&(r[y5]??=[],r[y5]=[{value:this.input.example}]);let i=aF(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=Xzo(i.examples,l=>[l])),i.example!=null&&Object.keys(r).length===0&&(r[y5]??=[],r[y5]?.push({value:i.example}))),Object.keys(r).length===0){let l=this.schema?.example({includeOptionals:!0,override:void 0});r[y5]??=[],r[y5]?.push(l!=null?{value:l}:void 0)}this.examples??=[];let n=new Set;this.matchRequestResponseExamplesByName(this.requests,r,n);let a=[];for(let l of this.requests)a.push(...Object.entries(l.examples??{}).filter(([d])=>!n.has(d)&&d!==y5).map(([d,s])=>[l,d,s]));let u=Object.entries(r).filter(([l,d])=>!n.has(l)&&xd(d)&&l!==y5);Object.keys(r).every(l=>l===y5)||this.matchExamplesByIndex(a,u),!n.has(y5)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return mM(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new wRo.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return mM(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=b5t([this.method,this.path,this.statusCode,"response"].join("_"));return ORo({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:I_.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new wRo.UnreachableCaseError(i);return}}).filter(xd)}convert(){if(this.empty)return{type:"empty"};if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?this.convertJsonLike():this.convertStreamingFormat();case"application/octet-stream":return{type:"fileDownload",contentType:this.contentSubtype};case"text/event-stream":return this.convertStreamingFormat();case void 0:return;default:new wRo.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var J_a=class extends Rp{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a,u){super(t),this.path=r,this.method=i,this.statusCode=n,this.requests=a,this.shapes=u,this.safeParse()}parse(t){this.description=this.input.description;let r=so_(this.input,this.context.document);if(r==null){this.context.errors.error({message:Y1(this.input)?`Undefined reference: ${this.input.$ref}`:"Expected response, received null",path:this.accessPath});return}Object.entries(r.headers??{}).forEach(([i,n])=>{this.headers??={},this.headers[i]=new lXt({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new Q_a({input:{},context:this.context,accessPath:this.accessPath,pathId:["content"]},"empty",t,this.path,this.method,this.statusCode,this.requests,this.shapes))):Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new Q_a({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(xd)}};var SRo=class extends Rp{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n,a){super(t),this.path=r,this.method=i,this.requests=n,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new J_a({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new J_a({input:i,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,parseInt(r),this.requests,this.shapes)))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return dRo(edi(r.headers)).flatMap(n=>i?.map(a=>({headers:n,response:{statusCode:parseInt(t),body:a,description:r.description},examples:(r.responses??[]).flatMap(u=>(u.examples??[]).map(l=>l.convert()).filter(xd))})))}).filter(xd)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=mM(n?.convert());if(n!=null)return a?.map(u=>({statusCode:parseInt(t),shape:u,description:r.description??n.description,availability:n.availability?.convert(),name:n.name??uo_[parseInt(t)]??"UNKNOWN ERROR",examples:i.examples?.map(l=>{let d=l.convert();if(d!=null&&d.responseBody?.type==="json")return{name:d.name,description:d.description,responseBody:d.responseBody}}).filter(xd)})).filter(xd)})).filter(xd)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var tdi=class extends Rp{servers;globalAuth;path;method;basePath;isWebhook;endpointIds;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespaces;xFernExamplesNode;redocExamplesNode;emptyResponseExamples;constructor(t){super(t),this.servers=t.servers,this.globalAuth=t.globalAuth,this.path=t.path,this.method=t.method,this.basePath=t.basePath,this.isWebhook=t.isWebhook,this.safeParse()}pushEmptyResponseExample(t,r,i){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new cXt({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,Kfi(i,void 0),{requestBody:r,pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}))}parse(){if(this.isWebhook&&this.method!=="POST"&&this.method!=="GET"){this.context.errors.error({message:`Webhook method must be POST or GET. Received: ${this.method}`,path:this.accessPath});return}this.description=this.input.description,this.displayName=this.input.summary,this.operationId=this.input.operationId,this.availability=new nze({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=sXt(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new uRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(Y1(i)){let a=rRo(i,this.context.document);if(a!=null)i=a;else{this.context.errors.warning({message:`Expected parameter reference to resolve to an object. Received undefined reference: ${i.$ref}`,path:[...this.accessPath,`parameters[${n}]`]});return}}i.in==="path"?i.schema!=null&&(this.pathParameters??={},this.pathParameters[i.name]=new lXt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new lXt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new lXt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new sRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new jRo({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody",method:this.method,path:this.path}):void 0,this.responses=this.input.responses!=null?new SRo({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0,this.responses==null){let i=this.requests?.requestBodiesByContentType;i==null||Object.keys(i).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(i).forEach(n=>{if(Object.keys(n.examples??{}).length===0){let a=n.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},n,void 0)}else Object.entries(n.examples??{}).forEach(([a,u])=>{this.pushEmptyResponseExample(u,n,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(i=>Number(i)>=200&&Number(i)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new D1n({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new G_a({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(i=>i.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((i,n)=>new G_a({input:{[Fzo]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new oRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>Zzo({namespace:mM(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(xd),this.xFernExamplesNode=new aRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-examples"},this.path,t,this.requests?.requestBodiesByContentType,this.responses?.responsesByStatusCode?.[t]?.responses)}extractPathParameterIds(){if(this.path!=null)return this.path.split("/").map(t=>{if(t.startsWith("{")&&t.endsWith("}"))return t.slice(1,-1).trim()}).filter(xd)}convertPathToPathParts(){if(this.path===void 0)return;let t=this.path.startsWith("/")?this.path.slice(1):this.path,r=this.basePath?.convert();return(r?[r,...t.split("/")]:t.split("/")).reduce((n,a)=>(n.push({type:"literal",value:"/"}),a.startsWith("{")&&a.endsWith("}")?n.push({type:"pathParameter",value:I_.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=this.emptyResponseExamples?.map(o=>o.convert()).filter(xd),n=Ra_(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(o=>o.examples)??[]])?.map(o=>({...o,snippets:za_(o.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((o,c)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:I_.WebhookId(o),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[c]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(b=>b.value.toString())??[],queryParameters:edi(this.queryParameters)?.flat(),headers:edi(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(xd)}}).filter(xd);let a=this.servers?.map(o=>o.convert()).filter(xd),u=this.convertPathToPathParts();if(u==null)return;let l,d=this.auth?.convert();d!=null&&(l=Object.keys(d));let s=t?.flatMap(o=>o.headers).filter(xd);return this.endpointIds.map((o,c)=>({id:I_.EndpointId(o),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[c]?.convert()?.map(b=>I_.api.v1.SubpackageId(b)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:u,auth:l?.map(b=>I_.api.latest.AuthSchemeId(b)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:edi(this.pathParameters)?.flat(),queryParameters:edi(this.queryParameters)?.flat(),requestHeaders:edi(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(b=>b.response),errors:r,examples:n,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var C1n=class extends Rp{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i,isWebhook:n}){this.description=this.input.description;let a=sXt(t,this.input.servers,this.context,this.accessPath),u=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new tdi({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:u,method:"GET",basePath:i,isWebhook:n})),this.input.post!=null&&(this.post=new tdi({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:u,method:"POST",basePath:i,isWebhook:n})),this.input.put!=null&&(this.put=new tdi({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:u,method:"PUT",basePath:i,isWebhook:!1})),this.input.patch!=null&&(this.patch=new tdi({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:u,method:"PATCH",basePath:i,isWebhook:!1})),this.input.delete!=null&&(this.delete=new tdi({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:u,method:"DELETE",basePath:i,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(xd)}};function DRo(e){return"payloads"in e}var ERo=class extends Rp{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.paths=Object.entries(this.input).map(([n,a])=>{if(a!=null)return new C1n({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:sXt(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(xd)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{DRo(a)?r[I_.WebhookId(a.id)]=a:t[I_.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var MRo=class extends Rp{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[ca_]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||rRo(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new lXt({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return E1n(this.globalHeaders,this.requiredProperties)?.flat()}};function do_(e,t){if(Y1(e)){let r=sV(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var ARo=class extends Rp{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.webhooks=Object.entries(this.input??{}).map(([n,a])=>{let u=do_(a,this.context.document);if(u!=null)return new C1n({input:u,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(xd)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{DRo(i)&&(t[I_.WebhookId(i.id)]=i)}),t),{})}};var qRo=class extends Rp{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=sXt(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new D1n({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new tRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});this.input.paths==null&&this.input.webhooks==null&&this.context.errors.warning({message:"Expected 'paths' or 'webhooks' property to be specified",path:this.accessPath}),this.input.paths!=null&&(this.paths=new ERo({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths",basePath:r,servers:t,globalAuth:this.auth})),this.input.webhooks!=null&&(this.webhooks=new ARo({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks",basePath:r,servers:t,globalAuth:this.auth})),this.input.components!=null&&(this.components=new T1n({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new MRo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=zre(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=zzo({endpoints:i,webhookEndpoints:n}),{types:u,auths:l}=this.components?.convert()??{};return{id:I_.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:{...u,...this.context.generatedTypes},subpackages:a,auths:{...l,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};var B1n=class extends j1n{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,this.pathId&&this.pathId!==this.accessPath[this.accessPath.length-1]&&(this.accessPath.push(this.pathId),r.logger.debug(`Processing #/${this.accessPath.join("/")}`))}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}};function aze(e){return typeof e=="object"&&xd(e)&&"$ref"in e&&typeof e.$ref=="string"}function g5t(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(aze(n)&&(n=g5t(n,t,r)),n)}function po_(e,t){return aze(e)?g5t(e,t,{name:"",params:[],result:{name:"",schema:{type:"object"}}}):e}var vo_=vi(ex());function VQr(e){if(typeof e=="boolean")return e;if(e.enum!=null&&e.enum.length>0)return e.enum[0];if(e.const!=null)return e.const;if(e.examples!=null&&e.examples.length>0)return e.examples[0];if(e.type==="object"){let t={};if(e.properties!=null)for(let[r,i]of Object.entries(e.properties))t[r]=VQr(i);return t}if(e.type==="array")return e.items==null?[]:Array.isArray(e.items)?e.items.map(t=>VQr(t)):[VQr(e.items)];if(e.type==="string")return e.default??"string";if(e.type==="number"||e.type==="integer")return e.default??0;if(e.type==="boolean")return e.default??!1;if(e.type==="null")return null;if(e.oneOf?.[0]!=null)return VQr(e.oneOf[0]);if(e.anyOf?.[0]!=null)return VQr(e.anyOf[0]);if(e.allOf!=null&&e.allOf.length>0){let t={};for(let r of e.allOf)r!=null&&Object.assign(t,VQr(r));return t}}function K_a(e,t){return aze(e)?g5t(e,t,{name:"",schema:{type:"object"}}):e}function _o_(e,t){return aze(e)?g5t(e,t,void 0):e}function ho_(e,t){return aze(e)?g5t(e,t,void 0):e}function yo_(e,t){return aze(e)?g5t(e,t,void 0):e}var sJD={key:I_.PropertyKey("apiKey"),description:void 0,availability:void 0,valueShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}}},TRo=class extends B1n{method;servers=[];constructor(t,r){super(t),this.method=t.input,this.servers=r,this.safeParse()}parse(){}convert(){try{let t=this.method.result?K_a(this.method.result,this.context.openrpc):void 0,r=t?new FA({input:t.schema,context:this.context,accessPath:this.accessPath,pathId:"result",seenSchemas:new Set,nullable:void 0,schemaName:"Result"}).convert():void 0,n=this.method.params?.map(l=>K_a(l,this.context.openrpc)).filter(xd)?.map(l=>{let d=new FA({input:l.schema,context:this.context,accessPath:this.accessPath,pathId:["params",l.name],seenSchemas:new Set,nullable:void 0,schemaName:l.name}).convert();if(!d)return;let s=Array.isArray(d)?d[0]:d;if(s)return{key:I_.PropertyKey(l.name),valueShape:l.required?s:{type:"alias",value:{type:"optional",shape:s,default:void 0}},description:l.description,availability:void 0}}).filter(xd),a=n.length>0?{contentType:"application/json",body:{type:"object",extends:[],properties:n,extraProperties:void 0},description:void 0}:void 0,u=this.method.examples?.map(l=>{let d=ho_(l,this.context.openrpc);if(d)return{name:d.name??"Example",path:"",description:void 0,snippets:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:d.params.length>0?{type:"json",value:Object.fromEntries(d.params.map(s=>{let o=_o_(s,this.context.openrpc);if(o)return[o.name??"",o.value]}).filter(xd))}:void 0,responseStatusCode:200,responseBody:d.result?{type:"json",value:d.result}:void 0}}).filter(xd)??[];if(u.length<=0){let l=VQr({type:"object",properties:Object.fromEntries(this.method.params?.map(s=>{let o=K_a(s,this.context.openrpc);return[o?.name??"",o?.schema??{}]})??[])}),d={name:"Example",path:"",pathParameters:{},queryParameters:{},headers:{},requestBody:{type:"json",value:l},responseStatusCode:200,responseBody:{type:"json",value:VQr(K_a(this.method.result,this.context.openrpc)?.schema??{})},snippets:void 0,description:void 0};u.push(d)}return{protocol:{type:"openrpc",methodName:this.input.name},id:I_.EndpointId(this.input.name),displayName:this.input.name,method:"POST",path:[{type:"pathParameter",value:I_.PropertyKey("apiKey")}],auth:void 0,pathParameters:[sJD],queryParameters:[],requests:a!=null?[a]:void 0,responses:r!=null?[this.convertToHttpResponse(r,this.input.description)].filter(xd):[],errors:[],examples:u,description:this.input.description??this.input.summary,operationId:this.input.name,defaultEnvironment:void 0,environments:this.servers.map(l=>l.convert()).filter(xd),availability:this.method.deprecated?"Deprecated":void 0,requestHeaders:[],responseHeaders:[],snippetTemplates:void 0,namespace:this.getNamespace()}}catch{this.context.errors.error({message:"Failed to convert method",path:this.accessPath});return}}getNamespace(){if(this.method.tags?.[0]==null)return;let t=yo_(this.method.tags[0],this.context.openrpc);if(t?.name!=null)return[I_.api.v1.SubpackageId(t.name)]}convertToHttpResponse(t,r){if(t==null)return;let n=mM(t)?.map(a=>{let u=a.type;switch(u){case"alias":return a;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":return;case"object":return a;default:new vo_.UnreachableCaseError(u);return}}).filter(xd)[0];if(n)return{statusCode:200,body:n,description:r}}};var Y_a=class extends B1n{servers=[];methods=[];components;constructor(t){super(t),this.safeParse()}parse(){if(this.context.openrpc.servers!=null&&(this.servers=sXt(this.servers,this.input.servers,this.context,this.accessPath)),this.input.methods!=null)for(let t of this.input.methods){let r=po_(t,this.context.openrpc);r!=null&&this.methods.push(new TRo({input:r,context:this.context,accessPath:this.accessPath,pathId:"methods"},this.servers))}this.context.openrpc.components!=null&&(this.components=new T1n({input:this.context.openrpc.components,context:this.context,accessPath:this.accessPath,pathId:"components"}))}convert(){let t=zre(),{types:r}=this.components?.convert()??{},i=this.methods?.map(u=>u.convert()).filter(xd),n=Object.fromEntries(i?.map(u=>[u.id,u])??[]),a=zzo({endpoints:n});return{id:I_.ApiDefinitionId(t),types:r??{},endpoints:n,websockets:{},webhooks:{},subpackages:a,auths:{},globalHeaders:[],snippetsConfiguration:void 0}}};var X_a=class extends Nzo{openrpc;logger;generatedTypes;constructor(t){super(),this.openrpc=t.openrpc,this.logger=t.logger,this.generatedTypes={}}get document(){return{openapi:"3.1.0",info:{title:"Mock API",version:"1.0.0"},paths:{},components:this.openrpc.components}}};async function Z_a(e,t){if(e instanceof gfi){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof y7))return;let r=new e5t(e.absoluteFilePath),i=await $Ie({context:t,specs:e.specs}),n=await r.loadDocuments({context:t,specs:i}),a;for(let u of n){if(u.type!=="openapi")continue;let l={document:u.value,logger:t.logger,errors:new P1n,generatedTypes:{}},d=new qRo({input:u.value,context:l,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=Fus(a,d.convert())}return a}var bo_=require("fs/promises");async function go_(e,t){let r=await(0,bo_.readFile)(e,"utf-8"),i=JSON.parse(r),n=new X_a({openrpc:i,logger:t.logger});return new Y_a({input:i,context:n,accessPath:[],pathId:"openrpc"}).convert()}function Oo_(e){let t=new Set;return e.logo?.dark!=null&&t.add(e.logo.dark),e.logo?.light!=null&&t.add(e.logo.light),e.favicon!=null&&t.add(e.favicon),e.backgroundImage?.dark!=null&&t.add(e.backgroundImage.dark),e.backgroundImage?.light!=null&&t.add(e.backgroundImage.light),e.metadata?.["og:image"]!=null&&e.metadata["og:image"].type==="filepath"&&t.add(e.metadata["og:image"].value),e.metadata?.["og:logo"]!=null&&e.metadata["og:logo"].type==="filepath"&&t.add(e.metadata["og:logo"].value),e.metadata?.["twitter:image"]!=null&&e.metadata["twitter:image"].type==="filepath"&&t.add(e.metadata["twitter:image"].value),e.typography?.bodyFont!=null&&e.typography.bodyFont.variants.forEach(r=>{t.add(r.absolutePath)}),e.typography?.headingsFont!=null&&e.typography.headingsFont.variants.forEach(r=>{t.add(r.absolutePath)}),e.typography?.codeFont!=null&&e.typography.codeFont.variants.forEach(r=>{t.add(r.absolutePath)}),e.js!=null&&e.js.files.forEach(r=>{t.add(r.absolutePath)}),t}async function mo_({navigation:e,fernWorkspaces:t,visitor:r,context:i}){lJD(e)?await Promise.all(e.map(async n=>{n.layout!=null&&await Promise.all(n.layout.map(async a=>{await aYs({navigationItem:a,visitor:r,fernWorkspaces:t,context:i})}))})):await Promise.all(e.map(async n=>{await aYs({navigationItem:n,visitor:r,fernWorkspaces:t,context:i})}))}async function aYs({navigationItem:e,visitor:t,fernWorkspaces:r,context:i}){if(await RHt(e,{alphabetized:Qo,api:Qo,apiName:Qo,audiences:Qo,displayErrors:Qo,snippets:Qo,summary:Qo,title:Qo,layout:Qo,icon:Qo,slug:Qo,hidden:Qo,skipSlug:Qo,paginated:Qo,playground:Qo,flattened:Qo,path:Qo,page:Qo,featureFlag:Qo,openrpc:Qo,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await aYs({navigationItem:a,visitor:t,fernWorkspaces:r,context:i})}))},viewers:Qo,orphaned:Qo}),cJD(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function cJD(e){return e.api!=null}function lJD(e){return e[0]?.tab!=null}function DSe(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}Po_.default.extend(jo_.default);var fJD=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),CRo=0,dJD=async({ir:e})=>(CRo++,`${e.apiName.snakeCase.unsafeName}-${CRo}`),pJD=async({api:e})=>(CRo++,`${e.id}-${CRo}`),O5t=class{domain;docsWorkspace;ossWorkspaces;fernWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;registerApiV2;constructor(t,r,i,n,a,u,l=fJD,d=dJD,s=pJD){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.fernWorkspaces=n,this.taskContext=a,this.editThisPage=u,this.uploadFiles=l,this.registerApi=d,this.registerApiV2=s}#e=Bzo.init();_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;markdownFilesToNoIndex=new Map;async resolve(){this._parsedDocsConfig=await P_s({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig}),this.docsWorkspace.config.navigation!=null&&await mo_({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:s})=>{(await s.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1})).changelog?.files.forEach(c=>{let b=Qq(this.docsWorkspace.absoluteFilePath,c.absoluteFilepath);this.parsedDocsConfig.pages[b]=c.contents})}},fernWorkspaces:this.fernWorkspaces,context:this.taskContext}),this.markdownFilesToFullSlugs=await this.getMarkdownFilesToFullSlugs(this.parsedDocsConfig.pages),this.markdownFilesToNoIndex=await this.getMarkdownFilesToNoIndex(this.parsedDocsConfig.pages);for(let[s,o]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Xa.of(s)]=await W$s({markdown:o,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(s),context:this.taskContext});for(let[s,o]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Xa.of(s)]=await V$s({markdown:o,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(s),context:this.taskContext});let t=Oo_(this.parsedDocsConfig);for(let[s,o]of Object.entries(this.parsedDocsConfig.pages)){let{filepaths:c,markdown:b}=d_a(o,{absolutePathToMarkdownFile:this.resolveFilepath(s),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[Xa.of(s)]=b;for(let g of c)t.add(g)}let r=Array.from(t).map(s=>({absoluteFilePath:s,relativeFilePath:this.toRelativeFilepath(s)}));(await this.uploadFiles(r)).forEach(s=>{this.collectedFileIds.set(s.absoluteFilePath,s.fileId)});let n=this.getDocsBasePath(),a=await this.getMarkdownFilesToFullyQualifiedPathNames(n);for(let[s,o]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Xa.of(s)]=U$s(o,this.collectedFileIds,a,{absolutePathToMarkdownFile:this.resolveFilepath(s),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let u={};Object.entries(this.parsedDocsConfig.pages).forEach(([s,o])=>{let c=_JD(this.editThisPage,s);u[f5t.PageId(s)]={markdown:o,editThisPageUrl:c?f5t.Url(c):void 0}});let l=await this.convertDocsConfiguration(),d={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){let s=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async o=>{let c=OO(this.docsWorkspace.absoluteFilePath,o);(await(0,BRo.stat)(c)).isDirectory()?(await $Ce(c,"{js,ts,jsx,tsx,md,mdx}")).forEach(O=>{s.add(O)}):c.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&s.add(c)})),d=Object.fromEntries(await Promise.all([...s].map(async o=>{let c=this.toRelativeFilepath(o),b=(await(0,BRo.readFile)(o)).toString();return[c,b]})))}return{config:l,pages:u,jsFiles:d}}resolveFilepath(t){if(t!=null)return OO(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return Qq(this.docsWorkspace.absoluteFilePath,t)}async getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,oYs.default)(n).data.slug;typeof u=="string"&&u.trim().length>0&&r.set(this.resolveFilepath(i),u.trim())}return r}async getMarkdownFilesToNoIndex(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,oYs.default)(n).data.noindex;typeof u=="boolean"&&r.set(this.resolveFilepath(i),u)}return r}async getMarkdownFilesToFullyQualifiedPathNames(t){let r={},i=zo.migrate.FernNavigationV1ToLatest.create().root(await this.toRootNode());return zo.NodeCollector.collect(i).slugMap.forEach((a,u)=>{if(a==null||!zo.isPage(a))return;let l=zo.getPageId(a);if(l==null)return;let d=Xu(this.docsWorkspace.absoluteFilePath,Xa.of(l));r[d]=Cv(t,u)}),r}getDocsBasePath(){return new URL(DSe(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.toRootNode();return{hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?f5t.Url(this.parsedDocsConfig.logo?.href):void 0,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:void 0,root:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(i=>({...i,url:f5t.Url(i.url)})),typographyV2:this.convertDocsTypographyConfiguration(),layout:this.parsedDocsConfig.layout,css:this.parsedDocsConfig.css,js:this.convertJavascriptConfiguration(),metadata:this.convertMetadata(),redirects:this.parsedDocsConfig.redirects,integrations:this.parsedDocsConfig.integrations,footerLinks:this.parsedDocsConfig.footerLinks?.map(i=>({...i,value:f5t.Url(i.value)})),defaultLanguage:this.parsedDocsConfig.defaultLanguage,analyticsConfig:{...this.parsedDocsConfig.analyticsConfig,segment:this.parsedDocsConfig.analyticsConfig?.segment,fullstory:this.parsedDocsConfig.analyticsConfig?.fullstory,intercom:this.parsedDocsConfig.analyticsConfig?.intercom?{appId:this.parsedDocsConfig.analyticsConfig.intercom.appId,apiBase:this.parsedDocsConfig.analyticsConfig.intercom.apiBase}:void 0,posthog:this.parsedDocsConfig.analyticsConfig?.posthog?{apiKey:this.parsedDocsConfig.analyticsConfig.posthog.apiKey,endpoint:this.parsedDocsConfig.analyticsConfig.posthog.endpoint}:void 0,gtm:this.parsedDocsConfig.analyticsConfig?.gtm?{containerId:this.parsedDocsConfig.analyticsConfig.gtm.containerId}:void 0,ga4:this.parsedDocsConfig.analyticsConfig?.ga4?{measurementId:this.parsedDocsConfig.analyticsConfig.ga4.measurementId}:void 0,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},announcement:this.parsedDocsConfig.announcement!=null?{text:this.parsedDocsConfig.announcement.message}:void 0,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0}}getFernWorkspaceForApiSection(t){if(this.fernWorkspaces.length===1&&this.fernWorkspaces[0]!=null)return this.fernWorkspaces[0];if(t.apiName!=null){let r=this.fernWorkspaces.find(i=>i.workspaceName===t.apiName);if(r!=null)return r}throw new Error("Failed to load API Definition referenced in docs")}getOpenApiWorkspaceForApiSection(t){if(this.ossWorkspaces.length===1&&this.ossWorkspaces[0]!=null)return this.ossWorkspaces[0];if(t.apiName!=null){let r=this.ossWorkspaces.find(i=>i.workspaceName===t.apiName);if(r!=null)return r}throw new Error("Failed to load API Definition referenced in docs")}async toRootNode(){let t=zo.V1.SlugGenerator.init(zo.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),i=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:i,slug:t.get(),title:this.parsedDocsConfig.title??"Documentation",hidden:!1,icon:void 0,pointsTo:void 0,authed:void 0,viewers:void 0,orphaned:void 0,roles:this.parsedDocsConfig.roles?.map(n=>zo.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return Rfn(this.parsedDocsConfig.navigation)._visit({untabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),tabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),versioned:r=>this.toVersionedNode(r,t)})}toLandingPageNode(t,r){let i=zo.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??Oq(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:i}){let n=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,i):void 0,u=r.type==="tabbed"?await this.convertTabbedNavigation(n,r.items,i):await this.toSidebarRootNode(n,r.items,i);return{type:"unversioned",id:n,landingPage:a,child:u}}async toVersionedNode(t,r){return{id:this.#e.get("versioned"),type:"versioned",children:await Promise.all(t.versions.map((n,a)=>this.toVersionNode(n,r,a===0)))}}async toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??Oq(t.version)),u=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(n,t.navigation.items,a):await this.toSidebarRootNode(n,t.navigation.items,a);return{type:"version",id:n,versionId:zo.VersionId(t.version),title:t.version,slug:a.get(),child:u,default:i,availability:t.availability!=null?hJD(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,r):void 0,hidden:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),a=await Promise.all(r.map(l=>this.toNavigationChild(n,l,i))),u=[];return a.forEach(l=>{if(l.type==="apiReference"){u.push(l);return}if(l.type==="section"&&!l.collapsed){u.push(l);return}let d=u.length>0?u[u.length-1]:void 0,s;d?.type==="sidebarGroup"?s=d:(s={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},u.push(s)),s.children.push(l)}),{type:"sidebarRoot",id:n,children:u}}async toNavigationChild(t,r,i,n){return Rfn(r)._visit({page:async a=>this.toPageNode(a,i,n),apiSection:async a=>this.toApiSectionNode(a,i,n),section:async a=>this.toSectionNode(t,a,i,n),link:async a=>this.toLinkNode(a),changelog:async a=>this.toChangelogNode(a,i,n)})}async toApiSectionNode(t,r,i){if(t.openrpc!=null){let o=OO(this.docsWorkspace.absoluteFilePath,Xa.of(t.openrpc));if(!await Cf(o))throw new Error(`OpenRPC file does not exist at path: ${o}`);let c=await go_(o,this.taskContext);if(c==null)throw new Error("Failed to generate API Definition from OpenRPC document");return await this.registerApiV2({api:c,apiName:t.apiName,snippetsConfig:xzo(t.snippetsConfiguration)}),new H_a(t,c,r,void 0,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,i).get()}if(this.parsedDocsConfig.experimental?.openapiParserV2){let o=this.getOpenApiWorkspaceForApiSection(t),c=xzo(t.snippetsConfiguration),b=await Z_a(o,this.taskContext);if(b==null)throw new Error("Failed to generate API Definition from OpenAPI workspace");return await this.registerApiV2({api:b,snippetsConfig:c,apiName:t.apiName}),new H_a(t,b,r,o,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,i).get()}let n=xzo(t.snippetsConfiguration),a,u;this.parsedDocsConfig.experimental?.openapiParserV3?a=await this.getOpenApiWorkspaceForApiSection(t).getIntermediateRepresentation({context:this.taskContext}):(u=this.getFernWorkspaceForApiSection(t),a=_2({workspace:u,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1,skipAutogenerationIfManualExamplesExist:!0},readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new d2(this.taskContext,u)}));let l=await this.registerApi({ir:a,snippetsConfig:n,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName}),d=$_a(a,l,{oauth:t.playground?.oauth});return new Tzo(t,d,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,u,i).get()}async toChangelogNode(t,r,i){return new LQr(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:t.icon,viewers:t.viewers,hidden:i||t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:zo.V1.Url(t.url),icon:t.icon}}async toPageNode(t,r,i){let n=zo.PageId(this.toRelativeFilepath(t.absolutePath)),a=r.apply({urlSlug:t.slug??Oq(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(n),type:"page",slug:a.get(),title:t.title,icon:t.icon,hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:n,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toSectionNode(t,r,i,n){let a=this.toRelativeFilepath(r.overviewAbsolutePath),u=a?zo.PageId(a):void 0,l=this.#e.get(u??`${t}/section`),d=i.apply({urlSlug:r.slug??Oq(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),s=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,o=n||r.hidden;return{id:l,type:"section",overviewPageId:u,slug:d.get(),title:r.title,icon:r.icon,collapsed:r.collapsed,hidden:o,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(c=>this.toNavigationChild(l,c,d,o))),authed:void 0,pointsTo:void 0,noindex:s,featureFlags:r.featureFlags}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return Rfn(r.child)._visit({link:({href:n})=>this.toTabLinkNode(r,n),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i)})}async toTabChangelogNode(t,r,i){return new LQr(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r){return{type:"link",id:this.#e.get(r),title:t.title,url:zo.V1.Url(r),icon:t.icon}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),u=n.apply({urlSlug:r.slug??Oq(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:u.get(),icon:r.icon,hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,i,u),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):f5t.FileId(r)}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(u0),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:f5t.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return Rfn(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:f5t.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function _JD(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${DSe(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function hJD(e){switch(e){case"beta":return zo.V1.NavigationV1Availability.Beta;case"deprecated":return zo.V1.NavigationV1Availability.Deprecated;case"ga":return zo.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return zo.V1.NavigationV1Availability.Stable;default:Ko(e)}}async function vie(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof y7?t:null))).filter(u0)}var rXs=vi(Oos(),1),Ol_=vi(aNo(),1),_Xt=require("fs/promises"),PNo=require("os"),ml_=vi(fte(),1),Pl_=vi(gl_(),1);var oXD="etag",iXs="preview",uXD="bundle",nXs=".fern";function sXD(){return Xu(Wl.of((0,PNo.homedir)()),Xa.of(nXs),Xa.of(iXs))}function jNo(){return Xu(Wl.of((0,PNo.homedir)()),Xa.of(nXs),Xa.of(iXs),Xa.of(uXD))}function cXD(){return Xu(Wl.of((0,PNo.homedir)()),Xa.of(nXs),Xa.of(iXs),Xa.of(oXD))}async function jl_({bucketUrl:e,logger:t,preferCached:r}){t.debug("Setting up docs preview bundle...");let i=await(0,rXs.fetcher)({url:e,method:"GET",responseType:"text",duplex:"half"});if(!i.ok)return{type:"failure"};let n=i.body,u=await new Pl_.default.Parser().parseStringPromise(n),l=u?.ListBucketResult?.Contents?.[0]?.ETag?.[0],d=u?.ListBucketResult?.Contents?.[0]?.Key?.[0],s=cXD();if(r){let q=await Cf(s),D;if(q&&(t.debug("Reading existing ETag"),D=(await(0,_Xt.readFile)(s)).toString()),D!=null&&D===l)return t.debug("ETag matches. Using already downloaded bundle"),{type:"success"};t.debug("ETag is different. Downloading latest preview bundle")}t.debug("Creating tmp directory to download docs preview bundle");let o=await ml_.default.dir({prefix:"fern"}),c=Wl.of(o.path),b=new URL(d,e).href;t.debug(`Downloading docs preview bundle from ${b}`);let g=await(0,rXs.fetcher)({url:b,method:"GET",responseType:"arrayBuffer",duplex:"half"});if(!g.ok){let q;return g.error.reason==="status-code"?q=`Failed to download docs preview bundle. Status code: ${g.error.statusCode}`:g.error.reason==="unknown"?q=`Failed to download docs preview bundle. Error: ${g.error.errorMessage}`:q=`Failed to download docs preview bundle. Error: ${g.error.reason}`,t.error(q),{type:"failure"}}let O=Xu(c,Xa.of("output.zip")),m=g.body;if(m==null)return{type:"failure"};let w=Buffer.from(m);await(0,_Xt.writeFile)(O,new Uint8Array(w)),t.debug(`Wrote output.zip to ${O}`);let E=sXD();await Cf(E)&&await(0,_Xt.rm)(E,{recursive:!0}),await(0,_Xt.mkdir)(E,{recursive:!0}),t.debug(`rm -rf ${E}`);let A=jNo();return await(0,_Xt.mkdir)(A,{recursive:!0}),await(0,Ol_.default)(O,A),await(0,_Xt.writeFile)(s,l),t.debug(`Downloaded bundle to ${A}`),{type:"success"}}var Rl_=require("fs/promises");var sXs=vi(u8t(),1),ql_=require("path");var G1n=vi(zte(),1);function wNo(e){if(e==null)return;let t=[],r=!1;if(XYt(e,{enter(i){(i.type==="FunctionDeclaration"||i.type==="ArrowFunctionExpression"||i.type==="JSXOpeningElement"||i.type==="JSXOpeningFragment"||i.type==="Identifier")&&(r=!0,this.skip()),i.type==="Literal"&&t.push(i.value)}}),!r)return t.length===1?t[0]:void 0}function aXs(e){if(typeof e=="string")return e;if(e?.type==="mdxJsxAttributeValueExpression")return wNo(e.data?.estree)}function wl_(e){return e.type==="mdxJsxFlowElement"||e.type==="mdxJsxTextElement"}function Sl_(e){return e.type==="mdxFlowExpression"||e.type==="mdxTextExpression"}function oXs(e){return e.type==="mdxJsxAttribute"}function Dl_(e){return e.type==="mdxJsxExpressionAttribute"}var El_=vi(u8t(),1);function Ml_(e){let{content:t}=(0,El_.default)(e);return s_a(t,{extensions:[Mmn(),gmn(),l_a()],mdastExtensions:[Exi(),Pxi(),c_a()]})}function Al_(e,t){XYt(e,{enter(r){r.type==="JSXElement"&&r.openingElement.attributes.forEach(i=>{i.type==="JSXAttribute"&&i.name.type==="JSXIdentifier"&&t[i.name.name]&&t[i.name.name]?.(i,r)})}})}function Tl_(e,{absolutePathToFernFolder:t,absolutePathToMarkdownFile:r}){return e==null||Cl_(e)||Bl_(e)?void 0:OO(e.startsWith("/")?t:fp(r),Xa.of(e.replace(/^\//,"")))}function Cl_(e){return/^(https?:)?\/\//.test(e)}function Bl_(e){return e.startsWith("data:")}function xl_({href:e,metadata:t,markdownFilesToPathName:r}){if(e!=null&&(e.endsWith(".md")||e.endsWith(".mdx"))){let i=Tl_(e,t);if(i!=null){let n=r[i];return n!=null?{type:"replace",slug:n,href:e}:{type:"missing-reference",path:i,href:e}}}}function cXs(e,t,r,i,n){let{content:a,data:u}=(0,sXs.default)(e,{}),l=a,d=Ml_(a),s=0;function o(c){if(c==null||Cl_(c)||Bl_(c))return;if((0,ql_.isAbsolute)(c)){let g=Wl.of(c),O=t.get(g);return O?`file:${O}`:void 0}let b=Tl_(c,i);if(b){let g=t.get(b);return g?`file:${g}`:void 0}}return fXD(u,["image","og:image","og:logo","twitter:image"],o),pXD(u,o),Rf(d,c=>{if(c.position==null)return;let{start:b,length:g}=lXD(a,c.position),O=l.slice(b+s,b+s+g),m=O;function w(q){let D=o(q);q&&D&&(m=m.replace(q,D))}function E(q){let D=xl_({href:q,markdownFilesToPathName:r,metadata:i});q!=null&&D!=null&&D.type==="replace"&&(m=m.replace(q,D.slug))}function A(q){Al_(q,{src:D=>w(udi(wNo(D.value))),href:D=>E(udi(wNo(D.value)))})}if(c.type==="image"){let q=udi(c.url);w(udi(q))}if(c.type==="link"&&E(udi(c.url)),wl_(c)){let q=c.attributes.filter(oXs).find(C=>C.name==="src");w(udi(aXs(q?.value)));let D=c.attributes.find(C=>C.type==="mdxJsxAttribute"&&C.name==="href");E(udi(aXs(D?.value))),c.attributes.forEach(C=>{oXs(C)&&typeof C.value!="string"&&C.value!=null&&C.value.data?.estree?A(C.value.data.estree):Dl_(C)&&C.data?.estree&&A(C.data.estree)})}if(Sl_(c)&&c.data?.estree&&A(c.data.estree),m!==O)return l=l.slice(0,b+s)+m+l.slice(b+s+g),s+=m.length-g,Pp}),sXs.default.stringify(l,u)}function lXD(e,t){let r=e.split(`
|
|
1972
1972
|
`),i=t.start.column-1;for(let a=0;a<t.start.line-1;a++){let u=r[a];if(u==null)break;i+=u.length+1}let n=0-t.start.column+t.end.column;for(let a=t.start.line-1;a<t.end.line-1;a++){let u=r[a];if(u==null)break;n+=u.length+1}return{start:i,length:n}}function udi(e){if(typeof e=="string")return e.replace(/#.*$/,"")}function fXD(e,t,r){for(let i of t){let n=e[i];if(n!=null){if(typeof n=="object")n.type==="fileId"&&(e[i]={type:"fileId",value:G1n.FernRegistry.FileId(r(n.value)??n.value)});else if(typeof n=="string"){let a=r(n);e[i]=a?{type:"fileId",value:G1n.FernRegistry.FileId(a)}:{type:"url",value:G1n.FernRegistry.Url(n)}}}}}var dXD=Yu.union([Yu.string(),Yu.object({light:Yu.string().optional(),dark:Yu.string().optional()})]);function uXs(e,t){let r=t(e);return r?{type:"fileId",value:G1n.FernRegistry.FileId(r)}:{type:"url",value:G1n.FernRegistry.Url(e)}}function pXD(e,t){let r=dXD.safeParse(e.logo);if(!r.success)return;let i=r.data;typeof i=="string"?e.logo=uXs(i,t):(i.light!=null&&(e.logo.light=uXs(i.light,t)),i.dark!=null&&(e.logo.dark=uXs(i.dark,t)))}var Il_=require("fs/promises"),zl_=vi(u8t(),1);async function _XD(e){let{content:t}=(0,zl_.default)(await(0,Il_.readFile)(e));return t}async function lXs({markdown:e,absolutePathToFernFolder:t,absolutePathToMarkdownFile:r,context:i,markdownLoader:n=_XD}){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=OO(o.startsWith("/")?t:fp(r),Xa.of(o.replace(/^\//,"")));try{let b=await n(c);b=b.split(`
|
|
1973
1973
|
`).map(g=>s+g).join(`
|
|
1974
1974
|
`),u=u.replace(d,b)}catch{i.logger.warn(`Failed to read markdown file "${o}" referenced in ${r}`);break}}return u}async function Nl_({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 w=n.every(E=>E.endsWith(".mdx")||E.endsWith(".md"));for(let E of n){let A=Qq(a.absoluteFilePath,E),q=(await(0,Rl_.readFile)(E)).toString(),D=await lXs({markdown:q,absolutePathToFernFolder:a.absoluteFilePath,absolutePathToMarkdownFile:E,context:r}),C=i.pages[KM.PageId(A)];if(C==null)continue;let R=new Map(Object.entries(i.filesV2??{}).map(([I,U])=>{let H="/"+U.url.replace("/_local/","");return[Wl.of(H),I]})),$=cXs(D,R,{},{absolutePathToFernFolder:a.absoluteFilePath,absolutePathToMarkdownFile:E},r);i.pages[KM.PageId(A)]={markdown:$,editThisPageUrl:C.editThisPageUrl}}if(w)return i}let l=await Promise.all(u.map(async w=>await w.toFernWorkspace({context:r},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0}))),d=await vie(t),s=new fXs(r),o=new dXs(r),c={},g=await new O5t(e,a,d,l,r,void 0,async w=>w.map(E=>{let A=zre();return c[A]={type:"url",url:zo.Url(`/_local${Sls(E.absoluteFilePath)}`)},{absoluteFilePath:E.absoluteFilePath,relativeFilePath:E.relativeFilePath,fileId:A}}),async w=>s.addReferencedAPI(w),async w=>o.addReferencedAPI(w)).resolve(),O=cJs({writeShape:g,files:{}}),m=fJs({dbShape:O.config});return{apis:s.getAPIsForDefinition(),apisV2:o.getAPIsForDefinition(),config:m,files:{},filesV2:c,pages:O.pages,search:{type:"legacyMultiAlgoliaIndex",algoliaIndex:void 0},algoliaSearchIndex:void 0,jsFiles:void 0,id:void 0}}var fXs=class{context;apis={};constructor(t){this.context=t}addReferencedAPI({ir:t,snippetsConfig:r,playgroundConfig:i}){try{let n=zre(),a=y_a(SSe({ir:t,snippetsConfig:r,playgroundConfig:i}),KM.ApiDefinitionId(n),new Fzi({snippetsConfigWithSdkId:{},snippetsBySdkId:{},snippetTemplatesByEndpoint:{},snippetTemplatesByEndpointId:{},snippetsBySdkIdAndEndpointId:{}})),u=g_a(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}},dXs=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 hXD={pages:{},apis:{},apisV2:{},files:{},filesV2:{},config:{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 _Xs({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 jl_({bucketUrl:$,logger:i.logger,preferCached:!0})}catch($){let I=jNo();if($ instanceof Error&&i.logger.debug(`Failed to download latest docs bundle: ${$.message}`),await Cf(I))i.logger.warn("Falling back to cached bundle...");else{i.logger.warn("Please reach out to support@buildwithfern.com.");return}}let u=fp(e.config._absolutePath),l=(0,pXs.default)(),d=Ll_.default.createServer(l),s=new T$s.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,Fl_.default)());let b=new URL(DSe(e.docsWorkspaces?.config.instances[0]?.url??`http://localhost:${n}`)),g=e,O,m=null,w=!1,E=1e3,A=async $=>{i.logger.info("Reloading docs...");let I=Date.now();try{g=await t(),i.logger.info("Validating docs..."),await r(g);let U=await Nl_({domain:`${b.host}${b.pathname}`,project:g,context:i,previousDocsDefinition:O,editedAbsoluteFilepaths:$});return i.logger.info(`Reload completed in ${Date.now()-I}ms`),U}catch(U){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."),U instanceof Error&&(i.logger.error(U.message),U instanceof Error&&U.stack&&i.logger.debug(`Stack Trace:
|