fern-api 0.60.19 → 0.60.21
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
|
@@ -1701,7 +1701,7 @@ ${c.indent}`:""}${EGf(o)}:${l.indent?" ":""}`;return u=!1,s=!0,l.objectItem=void
|
|
|
1701
1701
|
`}),r.replaceAll(/\n$/g,"")}function vFS(e){return e?eh.green(q7.radioOn):q7.radioOff}var cmo=li(kSe(),1);function Nop(e,t){return e=String(e),t=typeof t=="string"?t:"*",e.length===0?"":Array.from({length:e.length+1}).join(t)}var Bca=class extends F2{_run(t){this.done=t;let r=bV(this.rl),i=r.line.pipe((0,cmo.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,cmo.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=`
|
|
1702
1702
|
`+eh.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?eh.cyan(Nop(t,this.opt.mask)):eh.italic.dim("[hidden]"):this.opt.mask?Nop(t,this.opt.mask):eh.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 ssp=li(xxs(),1),csp=li(kSe(),1);var Wca=class extends F2{_run(t){this.done=t,this.editorResult=new csp.Subject;let r=bV(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"?eh.dim("Received"):eh.dim("Press <enter> to launch your preferred editor."),t&&(r=eh.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),(0,ssp.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 $sp=li(Lsp(),1);var Wsp=li(require("readline"),1),Hsp=li(Vsp(),1),uzi=class{constructor(t){this.rl||=Wsp.default.createInterface(B3S(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 B3S(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 Hsp.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var Gca=class extends uzi{constructor(t={}){super(t),this.log=(0,$sp.default)(this.writeLog.bind(this)),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return Sca(this.rl,this.bottomBar.split(`
|
|
1703
1703
|
`).length),this}updateBottomBar(t){return Sca(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+`
|
|
1704
|
-
`}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&&amo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var tcp=li(Jsp(),1),rcp=li(VCs(),1),icp=li(ksp(),1),eq=li(kSe(),1),ncp=li(xsa(),1);var Bmo=li(kSe(),1),ecp=li(xsa(),1),xmo=function(e,t,r){return typeof e[t]!="function"?(0,Bmo.of)(e):(0,Bmo.from)((0,ecp.default)(e[t])(r).then(i=>(e[t]=i,e)))};var Qca={isPlainObject:tcp.default,set:icp.default,get:rcp.default},Kmn=class extends uzi{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=Qca.isPlainObject(r)?{...r}:{},Qca.isPlainObject(t)&&(t=Object.values(t).every(n=>Qca.isPlainObject(n)&&n.name===void 0)?Object.entries(t).map(([n,a])=>({name:n,...a})):[t]);let i=Array.isArray(t)?(0,eq.from)(t):t;return this.process=i.pipe((0,eq.concatMap)(this.processQuestion.bind(this)),(0,eq.publish)()),this.process.connect(),this.process.pipe((0,eq.reduce)((n,a)=>(Qca.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,eq.defer)(()=>(0,eq.of)(t).pipe((0,eq.concatMap)(this.setDefaultType.bind(this)),(0,eq.concatMap)(this.filterIfRunnable.bind(this)),(0,eq.concatMap)(()=>xmo(t,"message",this.answers)),(0,eq.concatMap)(()=>xmo(t,"default",this.answers)),(0,eq.concatMap)(()=>xmo(t,"choices",this.answers)),(0,eq.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,eq.defer)(()=>(0,eq.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,eq.defer)(()=>(0,eq.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&Qca.get(this.answers,t.name)!==void 0)return(0,eq.empty)();if(t.when===!1)return(0,eq.empty)();if(typeof t.when!="function")return(0,eq.of)(t);let{answers:r}=this;return(0,eq.defer)(()=>(0,eq.from)((0,ncp.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,eq.filter)(i=>i!=null)))}};function acp(e){let t=function(r,i){let n;try{n=new Kmn(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",Eca),this.registerPrompt("input",ZIi),this.registerPrompt("number",Mca),this.registerPrompt("confirm",Aca),this.registerPrompt("rawlist",qca),this.registerPrompt("expand",Tca),this.registerPrompt("checkbox",Cca),this.registerPrompt("password",Bca),this.registerPrompt("editor",Wca)},t.restoreDefaultPrompts(),t}var $xs=acp();function X3S(e,t){$xs.registerPrompt(e,t)}function Z3S(){$xs.restoreDefaultPrompts()}var k3S={prompt:$xs,ui:{BottomBar:Gca,Prompt:Kmn},createPromptModule:acp,registerPrompt:X3S,restoreDefaultPrompts:Z3S,Separator:zie},Imo=k3S;var hlp=li(ocp()),D2S="4.2.1",j5t;(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"})(j5t||(j5t={}));function E2S(e,t){if(!e)throw new Error(t)}function M2S(e){return e?.replace(/\/+$/,"")}async function A2S(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 q2S(){return new Date().getTime()}function ulp(){return new Date().toISOString()}function ylp(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var nla=String.fromCharCode,slp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Ymo={};function T2S(e,t){if(!Ymo[e]){Ymo[e]={};for(let r=0;r<e.length;r++)Ymo[e][e.charAt(r)]=r}return Ymo[e][t]}var ala={compressToBase64:function(e){if(e==null)return"";let t=ala._compress(e,6,function(r){return slp.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:ala._decompress(e.length,32,function(t){return T2S(slp,e.charAt(t))})},compress:function(e){return ala._compress(e,16,function(t){return nla(t)})},_compress:function(e,t,r){if(e==null)return"";let i={},n={},a=[],u,l,f="",s="",o="",c=2,b=3,g=2,O=0,m=0,P;for(P=0;P<e.length;P+=1)if(f=e.charAt(P),Object.prototype.hasOwnProperty.call(i,f)||(i[f]=b++,n[f]=!0),s=o+f,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(f)}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:ala._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,f=3,s="",o,c,b,g,O,m,P;for(o=0;o<3;o+=1)i[o]=o;for(b=0,O=Math.pow(2,2),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;P=nla(b);break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;P=nla(b);break;case 2:return""}for(i[3]=P,c=P,n.push(P);;){if(a.index>e)return"";for(b=0,O=Math.pow(2,f),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(P=b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=nla(b),P=l-1,u--;break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=nla(b),P=l-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,f),f++),i[P])s=i[P];else if(P===l)s=c+c.charAt(0);else return null;n.push(s),i[l++]=c+s.charAt(0),u--,c=s,u==0&&(u=Math.pow(2,f),f++)}}},AIs=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 Xmo="0123456789abcdef",Zmo=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+=Xmo.charAt(this.bytes[r]>>>4),t+=Xmo.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+=Xmo.charAt(this.bytes[r]>>>4),t+=Xmo.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}},qIs=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??C2S()}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 Zmo.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,Zmo.ofInner(t)}},C2S=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),clp,llp=()=>B2S().toString(),B2S=()=>(clp||(clp=new qIs)).generate(),kmo=class extends Error{constructor(t){super("HTTP error while fetching PostHog: "+t.status),this.response=t,this.name="PostHogFetchHttpError"}},ola=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};function flp(e){return typeof e=="object"&&(e instanceof kmo||e instanceof ola)}var TIs=class{constructor(t,r){this.flushPromise=null,this.disableGeoip=!0,this.historicalMigration=!1,this.disabled=!1,this.defaultOptIn=!0,this.pendingPromises={},this._events=new AIs,this._isInitialized=!1,E2S(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=M2S(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:flp},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(j5t.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(j5t.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(j5t.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=llp();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(f=>f.json()).catch(f=>{this._events.emit("error",f)})}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 f=l[t];return f===void 0&&(f=!1),f}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 f=l[t];return f===void 0?null:f}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),f=l?.featureFlags,s=l?.featureFlagPayloads,o=s;return s&&(o=Object.fromEntries(Object.entries(s).map(([c,b])=>[c,this._parsePayload(b)]))),{flags:f,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:ulp(),uuid:i?.uuid?i.uuid:llp()};(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(j5t.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(j5t.Queue,u),this._events.emit(t,n),u.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=ylp(()=>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(j5t.Queue)||[];if(!t.length)return[];let r=t.slice(0,this.maxBatchSize),i=r.map(s=>s.message),n=()=>{let s=this.getPersistedProperty(j5t.Queue)||[];this.setPersistedProperty(j5t.Queue,s.slice(r.length))},a={api_key:this.apiKey,batch:i,sent_at:ulp()};this.historicalMigration&&(a.historical_migration=!0);let u=JSON.stringify(a),l=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${q2S()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,f=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(ala.compressToBase64(u))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:u};try{await this.fetchWithRetry(l,f)}catch(s){throw s instanceof ola||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 f=new AbortController;return setTimeout(()=>f.abort(),l),f.signal}),await A2S(async()=>{let u=null;try{u=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(f){throw new ola(f)}if(!(r.mode==="no-cors")&&(u.status<200||u.status>=400))throw new kmo(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(j5t.Queue)||[]).length!==0;){await this.flush();let n=Date.now();if(r<n)break}}catch(r){if(!flp(r))throw r;this.logMsgIfDebug(()=>console.error("Error while shutting down PostHog",r))}}},CIs=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},BIs=typeof fetch<"u"?fetch:typeof global.fetch<"u"?global.fetch:void 0;if(!BIs){let e=olp();BIs=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 vlp=BIs,x2S=1152921504606847e3,I2S=["is_not"],ePo=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},L2=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},xIs=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||vlp,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 f of this.featureFlags)if(t===f.key){l=f;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(f){f instanceof L2?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${f}`)):f instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${f}`))}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 f=>{try{let s=this.computeFlagLocally(f,t,r,i,n);a[f.key]=s;let o=await this.computeFeatureFlagPayloadLocally(f.key,s);o&&(u[f.key]=o)}catch(s){s instanceof L2||s instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${f.key}: ${s}`)),l=!0}}),{response:a,payloads:u,fallbackToDecide:l}}computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new L2("Flag has experience continuity enabled");if(!t.active)return!1;let l=(t.filters||{}).aggregation_group_type_index;if(l!=null){let f=this.groupTypeMapping[String(l)];if(!f)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${l} for feature flag ${t.key}`)),new L2("Flag has unknown group type index");if(!(f 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[f];return this.matchFeatureFlagProperties(t,i[f],s)}else return this.matchFeatureFlagProperties(t,r,n)}matchFeatureFlagProperties(t,r,i){let n=t.filters||{},a=n.groups||[],u=!1,l,f=[...a].sort((s,o)=>{let c=!!s.variant,b=!!o.variant;return c&&b?0:c?-1:b?1:0});for(let s of f)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 L2)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new L2("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 f=l.type,s=!1;if(f==="cohort"?s=glp(l,n,this.cohorts,this.debugMode):s=blp(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&dlp(t.key,r)>a/100)}getMatchingVariant(t,r){let i=dlp(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 ePo("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 ePo&&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=ylp(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}};function dlp(e,t,r=""){let i=(0,hlp.createHash)();return i.update(`${e}.${t}${r}`),parseInt(i.digest("hex").slice(0,15),16)/x2S}function blp(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 L2("Operator is_not_set is not supported")}else throw new L2(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!I2S.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 f(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 plp(String(n))&&String(u).match(String(n))!==null;case"not_regex":return plp(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"?f(u,String(n),a):f(u,s,a):f(String(u),String(n),a)}case"is_date_after":case"is_date_before":{let s=z2S(String(n));if(s==null&&(s=_lp(n)),s==null)throw new L2(`Invalid date: ${n}`);let o=_lp(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new L2(`Unknown operator: ${a}`)}}function glp(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new L2("can't match cohort without a given cohort property value");let a=r[n];return Olp(a,t,r,i)}function Olp(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 f=Olp(l,t,r,i);if(n==="AND"){if(!f)return!1}else if(f)return!0}catch(f){if(f instanceof L2)i&&console.debug(`Failed to compute property ${l} locally: ${f}`),u=!0;else throw f}if(u)throw new L2("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let l of a)try{let f;l.type==="cohort"?f=glp(l,t,r,i):f=blp(l,t);let s=l.negation||!1;if(n==="AND"){if(!f&&!s||f&&s)return!1}else if(f&&!s||!f&&s)return!0}catch(f){if(f instanceof L2)i&&console.debug(`Failed to compute property ${l} locally: ${f}`),u=!0;else throw f}if(u)throw new L2("can't match cohort without a given cohort property value");return n==="AND"}}function plp(e){try{return new RegExp(e),!0}catch{return!1}}function _lp(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 L2(`${e} is in an invalid date format`)}else throw new L2(`The date provided ${e} must be a string, number, or date object`)}function z2S(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 R2S=30*1e3,N2S=50*1e3,rPn=class extends TIs{constructor(t,r={}){super(t,r),this._memoryStorage=new CIs,this.options=r,r.personalApiKey&&(this.featureFlagsPoller=new xIs({pollingInterval:typeof r.featureFlagsPollingInterval=="number"?r.featureFlagsPollingInterval:R2S,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||N2S}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):vlp(t,r)}getLibraryId(){return"posthog-node"}getLibraryVersion(){return D2S}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:f}){let s=b=>{super.captureStateless(t,r,b,{timestamp:u,disableGeoip:l,uuid:f})},o=(b,g,O)=>super.getFeatureFlagsStateless(b,g,void 0,void 0,O),c=Promise.resolve().then(async()=>{if(a)return await o(t,n,l);if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let b={};for(let[g,O]of Object.entries(n||{}))b[g]=String(O);return await this.getAllFlags(t,{groups:b,disableGeoip:l,onlyEvaluateLocally:!0})}return{}}).then(b=>{let g={};if(b)for(let[m,P]of Object.entries(b))g[`$feature/${m}`]=P;let O=Object.keys(b||{}).filter(m=>b?.[m]!==!1);return O.length>0&&(g.$active_feature_flags=O),g}).catch(()=>({})).then(b=>{s({...b,...i,$groups:n})});this.addPendingPromise(c)}identify({distinctId:t,properties:r,disableGeoip:i}){let n=r?.$set||r;super.identifyStateless(t,{$set:n},{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:u,sendFeatureFlagEvents:l,personProperties:f,groupProperties:s}=i||{},o=this.addLocalPersonAndGroupProperties(r,n,f,s);f=o.allPersonProperties,s=o.allGroupProperties,u==null&&(u=!1),l==null&&(l=!0);let c=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,f,s),b=c!==void 0;!b&&!u&&(c=await super.getFeatureFlagStateless(t,r,n,f,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:f,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),f==null&&(f=!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||{},f=this.addLocalPersonAndGroupProperties(t,i,u,l);u=f.allPersonProperties,l=f.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}}},IIs=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})}};IIs.POSTHOG_ID_TAG="posthog_distinct_id";var tPo=class{posthog;constructor({posthogApiKey:t}){this.posthog=new rPn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.60.19",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var ula=class{async sendEvent(){}async identify(){}async flush(){}};var iPn=require("fs/promises"),wlp=require("os"),Slp=require("path");var mlp=li(require("crypto")),iPo=new Uint8Array(256),rPo=iPo.length;function zIs(){return rPo>iPo.length-16&&(mlp.default.randomFillSync(iPo),rPo=0),iPo.slice(rPo,rPo+=16)}var mV=[];for(let e=0;e<256;++e)mV.push((e+256).toString(16).slice(1));function Plp(e,t=0){return mV[e[t+0]]+mV[e[t+1]]+mV[e[t+2]]+mV[e[t+3]]+"-"+mV[e[t+4]]+mV[e[t+5]]+"-"+mV[e[t+6]]+mV[e[t+7]]+"-"+mV[e[t+8]]+mV[e[t+9]]+"-"+mV[e[t+10]]+mV[e[t+11]]+mV[e[t+12]]+mV[e[t+13]]+mV[e[t+14]]+mV[e[t+15]]}var jlp=li(require("crypto")),RIs={randomUUID:jlp.default.randomUUID};function F2S(e,t,r){if(RIs.randomUUID&&!t&&!e)return RIs.randomUUID();e=e||{};let i=e.random||(e.rng||zIs)();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 Plp(i)}var Uie=F2S;var L2S="id",U2S=".fern",sla=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new rPn(r),this.userId=t==null?void 0:$Es(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.60.19",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Lu(Hl.of((0,wlp.homedir)()),Xa.of(U2S),Xa.of(L2S));await Cf(t)||(await(0,iPn.mkdir)((0,Slp.dirname)(t),{recursive:!0}),await(0,iPn.writeFile)(t,Uie())),this.persistedDistinctId=(await(0,iPn.readFile)(t)).toString()}return this.persistedDistinctId}};var NIs;async function nPn(){return NIs==null&&(NIs=await V2S()),NIs}async function V2S(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new ula;let r=await ayo();return r!=null?new sla({token:r,posthogApiKey:e}):await $gn()!=null?new tPo({posthogApiKey:e}):new sla({token:void 0,posthogApiKey:e})}catch{return new ula}}function cla(e,t){return function(){return e.apply(t,arguments)}}var{toString:W2S}=Object.prototype,{getPrototypeOf:LIs}=Object,aPo=(e=>t=>{let r=W2S.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),w5t=e=>(e=e.toLowerCase(),t=>aPo(t)===e),oPo=e=>t=>typeof t===e,{isArray:aPn}=Array,lla=oPo("undefined");function H2S(e){return e!==null&&!lla(e)&&e.constructor!==null&&!lla(e.constructor)&&tDe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var Elp=w5t("ArrayBuffer");function $2S(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Elp(e.buffer),t}var G2S=oPo("string"),tDe=oPo("function"),Mlp=oPo("number"),uPo=e=>e!==null&&typeof e=="object",Q2S=e=>e===!0||e===!1,nPo=e=>{if(aPo(e)!=="object")return!1;let t=LIs(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},J2S=w5t("Date"),K2S=w5t("File"),Y2S=w5t("Blob"),X2S=w5t("FileList"),Z2S=e=>uPo(e)&&tDe(e.pipe),k2S=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||tDe(e.append)&&((t=aPo(e))==="formdata"||t==="object"&&tDe(e.toString)&&e.toString()==="[object FormData]"))},e4S=w5t("URLSearchParams"),[t4S,r4S,i4S,n4S]=["ReadableStream","Request","Response","Headers"].map(w5t),a4S=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function fla(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),aPn(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 Alp(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 dzi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,qlp=e=>!lla(e)&&e!==dzi;function FIs(){let{caseless:e}=qlp(this)&&this||{},t={},r=(i,n)=>{let a=e&&Alp(t,n)||n;nPo(t[a])&&nPo(i)?t[a]=FIs(t[a],i):nPo(i)?t[a]=FIs({},i):aPn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&fla(arguments[i],r);return t}var o4S=(e,t,r,{allOwnKeys:i}={})=>(fla(t,(n,a)=>{r&&tDe(n)?e[a]=cla(n,r):e[a]=n},{allOwnKeys:i}),e),u4S=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),s4S=(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)},c4S=(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&&LIs(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},l4S=(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},f4S=e=>{if(!e)return null;if(aPn(e))return e;let t=e.length;if(!Mlp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},d4S=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&LIs(Uint8Array)),p4S=(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])}},_4S=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},h4S=w5t("HTMLFormElement"),y4S=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),Dlp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),v4S=w5t("RegExp"),Tlp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};fla(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},b4S=e=>{Tlp(e,(t,r)=>{if(tDe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(tDe(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+"'")})}})},g4S=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return aPn(e)?i(e):i(String(e).split(t)),r},O4S=()=>{},m4S=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function P4S(e){return!!(e&&tDe(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var j4S=e=>{let t=new Array(10),r=(i,n)=>{if(uPo(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=aPn(i)?[]:{};return fla(i,(u,l)=>{let f=r(u,n+1);!lla(f)&&(a[l]=f)}),t[n]=void 0,a}}return i};return r(e,0)},w4S=w5t("AsyncFunction"),S4S=e=>e&&(uPo(e)||tDe(e))&&tDe(e.then)&&tDe(e.catch),Clp=((e,t)=>e?setImmediate:t?((r,i)=>(dzi.addEventListener("message",({source:n,data:a})=>{n===dzi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),dzi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",tDe(dzi.postMessage)),D4S=typeof queueMicrotask<"u"?queueMicrotask.bind(dzi):typeof process<"u"&&process.nextTick||Clp,ds={isArray:aPn,isArrayBuffer:Elp,isBuffer:H2S,isFormData:k2S,isArrayBufferView:$2S,isString:G2S,isNumber:Mlp,isBoolean:Q2S,isObject:uPo,isPlainObject:nPo,isReadableStream:t4S,isRequest:r4S,isResponse:i4S,isHeaders:n4S,isUndefined:lla,isDate:J2S,isFile:K2S,isBlob:Y2S,isRegExp:v4S,isFunction:tDe,isStream:Z2S,isURLSearchParams:e4S,isTypedArray:d4S,isFileList:X2S,forEach:fla,merge:FIs,extend:o4S,trim:a4S,stripBOM:u4S,inherits:s4S,toFlatObject:c4S,kindOf:aPo,kindOfTest:w5t,endsWith:l4S,toArray:f4S,forEachEntry:p4S,matchAll:_4S,isHTMLForm:h4S,hasOwnProperty:Dlp,hasOwnProp:Dlp,reduceDescriptors:Tlp,freezeMethods:b4S,toObjectSet:g4S,toCamelCase:y4S,noop:O4S,toFiniteNumber:m4S,findKey:Alp,global:dzi,isContextDefined:qlp,isSpecCompliantForm:P4S,toJSONObject:j4S,isAsyncFn:w4S,isThenable:S4S,setImmediate:Clp,asap:D4S};function oPn(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)}ds.inherits(oPn,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:ds.toJSONObject(this.config),code:this.code,status:this.status}}});var Blp=oPn.prototype,xlp={};["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=>{xlp[e]={value:e}});Object.defineProperties(oPn,xlp);Object.defineProperty(Blp,"isAxiosError",{value:!0});oPn.from=(e,t,r,i,n,a)=>{let u=Object.create(Blp);return ds.toFlatObject(e,u,function(f){return f!==Error.prototype},l=>l!=="isAxiosError"),oPn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var Ep=oPn;var Ilp=li(Cia(),1),sPo=Ilp.default;function UIs(e){return ds.isPlainObject(e)||ds.isArray(e)}function Rlp(e){return ds.endsWith(e,"[]")?e.slice(0,-2):e}function zlp(e,t,r){return e?e.concat(t).map(function(n,a){return n=Rlp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function E4S(e){return ds.isArray(e)&&!e.some(UIs)}var M4S=ds.toFlatObject(ds,{},null,function(t){return/^is[A-Z]/.test(t)});function A4S(e,t,r){if(!ds.isObject(e))throw new TypeError("target must be an object");t=t||new(sPo||FormData),r=ds.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,P){return!ds.isUndefined(P[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,f=(r.Blob||typeof Blob<"u"&&Blob)&&ds.isSpecCompliantForm(t);if(!ds.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(ds.isDate(O))return O.toISOString();if(!f&&ds.isBlob(O))throw new Ep("Blob is not supported. Use a Buffer instead.");return ds.isArrayBuffer(O)||ds.isTypedArray(O)?f&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,P){let E=O;if(O&&!P&&typeof O=="object"){if(ds.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(ds.isArray(O)&&E4S(O)||(ds.isFileList(O)||ds.endsWith(m,"[]"))&&(E=ds.toArray(O)))return m=Rlp(m),E.forEach(function(A,D){!(ds.isUndefined(A)||A===null)&&t.append(u===!0?zlp([m],D,a):u===null?m:m+"[]",s(A))}),!1}return UIs(O)?!0:(t.append(zlp(P,m,a),s(O)),!1)}let c=[],b=Object.assign(M4S,{defaultVisitor:o,convertValue:s,isVisitable:UIs});function g(O,m){if(!ds.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),ds.forEach(O,function(E,q){(!(ds.isUndefined(E)||E===null)&&n.call(t,E,ds.isString(q)?q.trim():q,m,b))===!0&&g(E,m?m.concat(q):[q])}),c.pop()}}if(!ds.isObject(e))throw new TypeError("data must be an object");return g(e),t}var mfi=A4S;function Nlp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function Flp(e,t){this._pairs=[],e&&mfi(e,this,t)}var Llp=Flp.prototype;Llp.append=function(t,r){this._pairs.push([t,r])};Llp.toString=function(t){let r=t?function(i){return t.call(this,i,Nlp)}:Nlp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var Ulp=Flp;function q4S(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function pzi(e,t,r){if(!t)return e;let i=r&&r.encode||q4S;ds.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=ds.isURLSearchParams(t)?t.toString():new Ulp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var VIs=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){ds.forEach(this.handlers,function(i){i!==null&&t(i)})}},WIs=VIs;var uPn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var $lp=li(require("crypto"),1);var Vlp=li(require("url"),1),Wlp=Vlp.default.URLSearchParams;var HIs="abcdefghijklmnopqrstuvwxyz",Hlp="0123456789",Glp={DIGIT:Hlp,ALPHA:HIs,ALPHA_DIGIT:HIs+HIs.toUpperCase()+Hlp},T4S=(e=16,t=Glp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);$lp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},Qlp={isNode:!0,classes:{URLSearchParams:Wlp,FormData:sPo,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:Glp,generateString:T4S,protocols:["http","https","file","data"]};var QIs={};jo(QIs,{hasBrowserEnv:()=>GIs,hasStandardBrowserEnv:()=>C4S,hasStandardBrowserWebWorkerEnv:()=>B4S,navigator:()=>$Is,origin:()=>x4S});var GIs=typeof window<"u"&&typeof document<"u",$Is=typeof navigator=="object"&&navigator||void 0,C4S=GIs&&(!$Is||["ReactNative","NativeScript","NS"].indexOf($Is.product)<0),B4S=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",x4S=GIs&&window.location.href||"http://localhost";var AM={...QIs,...Qlp};function JIs(e,t){return mfi(e,new AM.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return AM.isNode&&ds.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function I4S(e){return ds.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function z4S(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 R4S(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let l=Number.isFinite(+u),f=a>=r.length;return u=!u&&ds.isArray(n)?n.length:u,f?(ds.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!ds.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&ds.isArray(n[u])&&(n[u]=z4S(n[u])),!l)}if(ds.isFormData(e)&&ds.isFunction(e.entries)){let r={};return ds.forEachEntry(e,(i,n)=>{t(I4S(i),n,r,0)}),r}return null}var cPo=R4S;function N4S(e,t,r){if(ds.isString(e))try{return(t||JSON.parse)(e),ds.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var KIs={transitional:uPn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=ds.isObject(t);if(a&&ds.isHTMLForm(t)&&(t=new FormData(t)),ds.isFormData(t))return n?JSON.stringify(cPo(t)):t;if(ds.isArrayBuffer(t)||ds.isBuffer(t)||ds.isStream(t)||ds.isFile(t)||ds.isBlob(t)||ds.isReadableStream(t))return t;if(ds.isArrayBufferView(t))return t.buffer;if(ds.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 JIs(t,this.formSerializer).toString();if((l=ds.isFileList(t))||i.indexOf("multipart/form-data")>-1){let f=this.env&&this.env.FormData;return mfi(l?{"files[]":t}:t,f&&new f,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),N4S(t)):t}],transformResponse:[function(t){let r=this.transitional||KIs.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(ds.isResponse(t)||ds.isReadableStream(t))return t;if(t&&ds.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"?Ep.from(l,Ep.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:AM.classes.FormData,Blob:AM.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ds.forEach(["delete","get","head","post","put","patch"],e=>{KIs.headers[e]={}});var sPn=KIs;var F4S=ds.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"]),Jlp=e=>{let t={},r,i,n;return e&&e.split(`
|
|
1704
|
+
`}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&&amo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var tcp=li(Jsp(),1),rcp=li(VCs(),1),icp=li(ksp(),1),eq=li(kSe(),1),ncp=li(xsa(),1);var Bmo=li(kSe(),1),ecp=li(xsa(),1),xmo=function(e,t,r){return typeof e[t]!="function"?(0,Bmo.of)(e):(0,Bmo.from)((0,ecp.default)(e[t])(r).then(i=>(e[t]=i,e)))};var Qca={isPlainObject:tcp.default,set:icp.default,get:rcp.default},Kmn=class extends uzi{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=Qca.isPlainObject(r)?{...r}:{},Qca.isPlainObject(t)&&(t=Object.values(t).every(n=>Qca.isPlainObject(n)&&n.name===void 0)?Object.entries(t).map(([n,a])=>({name:n,...a})):[t]);let i=Array.isArray(t)?(0,eq.from)(t):t;return this.process=i.pipe((0,eq.concatMap)(this.processQuestion.bind(this)),(0,eq.publish)()),this.process.connect(),this.process.pipe((0,eq.reduce)((n,a)=>(Qca.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,eq.defer)(()=>(0,eq.of)(t).pipe((0,eq.concatMap)(this.setDefaultType.bind(this)),(0,eq.concatMap)(this.filterIfRunnable.bind(this)),(0,eq.concatMap)(()=>xmo(t,"message",this.answers)),(0,eq.concatMap)(()=>xmo(t,"default",this.answers)),(0,eq.concatMap)(()=>xmo(t,"choices",this.answers)),(0,eq.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,eq.defer)(()=>(0,eq.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,eq.defer)(()=>(0,eq.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&Qca.get(this.answers,t.name)!==void 0)return(0,eq.empty)();if(t.when===!1)return(0,eq.empty)();if(typeof t.when!="function")return(0,eq.of)(t);let{answers:r}=this;return(0,eq.defer)(()=>(0,eq.from)((0,ncp.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,eq.filter)(i=>i!=null)))}};function acp(e){let t=function(r,i){let n;try{n=new Kmn(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",Eca),this.registerPrompt("input",ZIi),this.registerPrompt("number",Mca),this.registerPrompt("confirm",Aca),this.registerPrompt("rawlist",qca),this.registerPrompt("expand",Tca),this.registerPrompt("checkbox",Cca),this.registerPrompt("password",Bca),this.registerPrompt("editor",Wca)},t.restoreDefaultPrompts(),t}var $xs=acp();function X3S(e,t){$xs.registerPrompt(e,t)}function Z3S(){$xs.restoreDefaultPrompts()}var k3S={prompt:$xs,ui:{BottomBar:Gca,Prompt:Kmn},createPromptModule:acp,registerPrompt:X3S,restoreDefaultPrompts:Z3S,Separator:zie},Imo=k3S;var hlp=li(ocp()),D2S="4.2.1",j5t;(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"})(j5t||(j5t={}));function E2S(e,t){if(!e)throw new Error(t)}function M2S(e){return e?.replace(/\/+$/,"")}async function A2S(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 q2S(){return new Date().getTime()}function ulp(){return new Date().toISOString()}function ylp(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var nla=String.fromCharCode,slp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Ymo={};function T2S(e,t){if(!Ymo[e]){Ymo[e]={};for(let r=0;r<e.length;r++)Ymo[e][e.charAt(r)]=r}return Ymo[e][t]}var ala={compressToBase64:function(e){if(e==null)return"";let t=ala._compress(e,6,function(r){return slp.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:ala._decompress(e.length,32,function(t){return T2S(slp,e.charAt(t))})},compress:function(e){return ala._compress(e,16,function(t){return nla(t)})},_compress:function(e,t,r){if(e==null)return"";let i={},n={},a=[],u,l,f="",s="",o="",c=2,b=3,g=2,O=0,m=0,P;for(P=0;P<e.length;P+=1)if(f=e.charAt(P),Object.prototype.hasOwnProperty.call(i,f)||(i[f]=b++,n[f]=!0),s=o+f,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(f)}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:ala._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,f=3,s="",o,c,b,g,O,m,P;for(o=0;o<3;o+=1)i[o]=o;for(b=0,O=Math.pow(2,2),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;P=nla(b);break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;P=nla(b);break;case 2:return""}for(i[3]=P,c=P,n.push(P);;){if(a.index>e)return"";for(b=0,O=Math.pow(2,f),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(P=b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=nla(b),P=l-1,u--;break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=nla(b),P=l-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,f),f++),i[P])s=i[P];else if(P===l)s=c+c.charAt(0);else return null;n.push(s),i[l++]=c+s.charAt(0),u--,c=s,u==0&&(u=Math.pow(2,f),f++)}}},AIs=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 Xmo="0123456789abcdef",Zmo=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+=Xmo.charAt(this.bytes[r]>>>4),t+=Xmo.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+=Xmo.charAt(this.bytes[r]>>>4),t+=Xmo.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}},qIs=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??C2S()}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 Zmo.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,Zmo.ofInner(t)}},C2S=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),clp,llp=()=>B2S().toString(),B2S=()=>(clp||(clp=new qIs)).generate(),kmo=class extends Error{constructor(t){super("HTTP error while fetching PostHog: "+t.status),this.response=t,this.name="PostHogFetchHttpError"}},ola=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};function flp(e){return typeof e=="object"&&(e instanceof kmo||e instanceof ola)}var TIs=class{constructor(t,r){this.flushPromise=null,this.disableGeoip=!0,this.historicalMigration=!1,this.disabled=!1,this.defaultOptIn=!0,this.pendingPromises={},this._events=new AIs,this._isInitialized=!1,E2S(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=M2S(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:flp},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(j5t.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(j5t.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(j5t.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=llp();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(f=>f.json()).catch(f=>{this._events.emit("error",f)})}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 f=l[t];return f===void 0&&(f=!1),f}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 f=l[t];return f===void 0?null:f}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),f=l?.featureFlags,s=l?.featureFlagPayloads,o=s;return s&&(o=Object.fromEntries(Object.entries(s).map(([c,b])=>[c,this._parsePayload(b)]))),{flags:f,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:ulp(),uuid:i?.uuid?i.uuid:llp()};(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(j5t.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(j5t.Queue,u),this._events.emit(t,n),u.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=ylp(()=>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(j5t.Queue)||[];if(!t.length)return[];let r=t.slice(0,this.maxBatchSize),i=r.map(s=>s.message),n=()=>{let s=this.getPersistedProperty(j5t.Queue)||[];this.setPersistedProperty(j5t.Queue,s.slice(r.length))},a={api_key:this.apiKey,batch:i,sent_at:ulp()};this.historicalMigration&&(a.historical_migration=!0);let u=JSON.stringify(a),l=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${q2S()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,f=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(ala.compressToBase64(u))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:u};try{await this.fetchWithRetry(l,f)}catch(s){throw s instanceof ola||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 f=new AbortController;return setTimeout(()=>f.abort(),l),f.signal}),await A2S(async()=>{let u=null;try{u=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(f){throw new ola(f)}if(!(r.mode==="no-cors")&&(u.status<200||u.status>=400))throw new kmo(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(j5t.Queue)||[]).length!==0;){await this.flush();let n=Date.now();if(r<n)break}}catch(r){if(!flp(r))throw r;this.logMsgIfDebug(()=>console.error("Error while shutting down PostHog",r))}}},CIs=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},BIs=typeof fetch<"u"?fetch:typeof global.fetch<"u"?global.fetch:void 0;if(!BIs){let e=olp();BIs=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 vlp=BIs,x2S=1152921504606847e3,I2S=["is_not"],ePo=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},L2=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},xIs=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||vlp,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 f of this.featureFlags)if(t===f.key){l=f;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(f){f instanceof L2?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${f}`)):f instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${f}`))}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 f=>{try{let s=this.computeFlagLocally(f,t,r,i,n);a[f.key]=s;let o=await this.computeFeatureFlagPayloadLocally(f.key,s);o&&(u[f.key]=o)}catch(s){s instanceof L2||s instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${f.key}: ${s}`)),l=!0}}),{response:a,payloads:u,fallbackToDecide:l}}computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new L2("Flag has experience continuity enabled");if(!t.active)return!1;let l=(t.filters||{}).aggregation_group_type_index;if(l!=null){let f=this.groupTypeMapping[String(l)];if(!f)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${l} for feature flag ${t.key}`)),new L2("Flag has unknown group type index");if(!(f 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[f];return this.matchFeatureFlagProperties(t,i[f],s)}else return this.matchFeatureFlagProperties(t,r,n)}matchFeatureFlagProperties(t,r,i){let n=t.filters||{},a=n.groups||[],u=!1,l,f=[...a].sort((s,o)=>{let c=!!s.variant,b=!!o.variant;return c&&b?0:c?-1:b?1:0});for(let s of f)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 L2)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new L2("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 f=l.type,s=!1;if(f==="cohort"?s=glp(l,n,this.cohorts,this.debugMode):s=blp(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&dlp(t.key,r)>a/100)}getMatchingVariant(t,r){let i=dlp(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 ePo("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 ePo&&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=ylp(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}};function dlp(e,t,r=""){let i=(0,hlp.createHash)();return i.update(`${e}.${t}${r}`),parseInt(i.digest("hex").slice(0,15),16)/x2S}function blp(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 L2("Operator is_not_set is not supported")}else throw new L2(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!I2S.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 f(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 plp(String(n))&&String(u).match(String(n))!==null;case"not_regex":return plp(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"?f(u,String(n),a):f(u,s,a):f(String(u),String(n),a)}case"is_date_after":case"is_date_before":{let s=z2S(String(n));if(s==null&&(s=_lp(n)),s==null)throw new L2(`Invalid date: ${n}`);let o=_lp(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new L2(`Unknown operator: ${a}`)}}function glp(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new L2("can't match cohort without a given cohort property value");let a=r[n];return Olp(a,t,r,i)}function Olp(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 f=Olp(l,t,r,i);if(n==="AND"){if(!f)return!1}else if(f)return!0}catch(f){if(f instanceof L2)i&&console.debug(`Failed to compute property ${l} locally: ${f}`),u=!0;else throw f}if(u)throw new L2("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let l of a)try{let f;l.type==="cohort"?f=glp(l,t,r,i):f=blp(l,t);let s=l.negation||!1;if(n==="AND"){if(!f&&!s||f&&s)return!1}else if(f&&!s||!f&&s)return!0}catch(f){if(f instanceof L2)i&&console.debug(`Failed to compute property ${l} locally: ${f}`),u=!0;else throw f}if(u)throw new L2("can't match cohort without a given cohort property value");return n==="AND"}}function plp(e){try{return new RegExp(e),!0}catch{return!1}}function _lp(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 L2(`${e} is in an invalid date format`)}else throw new L2(`The date provided ${e} must be a string, number, or date object`)}function z2S(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 R2S=30*1e3,N2S=50*1e3,rPn=class extends TIs{constructor(t,r={}){super(t,r),this._memoryStorage=new CIs,this.options=r,r.personalApiKey&&(this.featureFlagsPoller=new xIs({pollingInterval:typeof r.featureFlagsPollingInterval=="number"?r.featureFlagsPollingInterval:R2S,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||N2S}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):vlp(t,r)}getLibraryId(){return"posthog-node"}getLibraryVersion(){return D2S}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:f}){let s=b=>{super.captureStateless(t,r,b,{timestamp:u,disableGeoip:l,uuid:f})},o=(b,g,O)=>super.getFeatureFlagsStateless(b,g,void 0,void 0,O),c=Promise.resolve().then(async()=>{if(a)return await o(t,n,l);if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let b={};for(let[g,O]of Object.entries(n||{}))b[g]=String(O);return await this.getAllFlags(t,{groups:b,disableGeoip:l,onlyEvaluateLocally:!0})}return{}}).then(b=>{let g={};if(b)for(let[m,P]of Object.entries(b))g[`$feature/${m}`]=P;let O=Object.keys(b||{}).filter(m=>b?.[m]!==!1);return O.length>0&&(g.$active_feature_flags=O),g}).catch(()=>({})).then(b=>{s({...b,...i,$groups:n})});this.addPendingPromise(c)}identify({distinctId:t,properties:r,disableGeoip:i}){let n=r?.$set||r;super.identifyStateless(t,{$set:n},{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:u,sendFeatureFlagEvents:l,personProperties:f,groupProperties:s}=i||{},o=this.addLocalPersonAndGroupProperties(r,n,f,s);f=o.allPersonProperties,s=o.allGroupProperties,u==null&&(u=!1),l==null&&(l=!0);let c=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,f,s),b=c!==void 0;!b&&!u&&(c=await super.getFeatureFlagStateless(t,r,n,f,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:f,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),f==null&&(f=!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||{},f=this.addLocalPersonAndGroupProperties(t,i,u,l);u=f.allPersonProperties,l=f.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}}},IIs=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})}};IIs.POSTHOG_ID_TAG="posthog_distinct_id";var tPo=class{posthog;constructor({posthogApiKey:t}){this.posthog=new rPn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.60.21",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var ula=class{async sendEvent(){}async identify(){}async flush(){}};var iPn=require("fs/promises"),wlp=require("os"),Slp=require("path");var mlp=li(require("crypto")),iPo=new Uint8Array(256),rPo=iPo.length;function zIs(){return rPo>iPo.length-16&&(mlp.default.randomFillSync(iPo),rPo=0),iPo.slice(rPo,rPo+=16)}var mV=[];for(let e=0;e<256;++e)mV.push((e+256).toString(16).slice(1));function Plp(e,t=0){return mV[e[t+0]]+mV[e[t+1]]+mV[e[t+2]]+mV[e[t+3]]+"-"+mV[e[t+4]]+mV[e[t+5]]+"-"+mV[e[t+6]]+mV[e[t+7]]+"-"+mV[e[t+8]]+mV[e[t+9]]+"-"+mV[e[t+10]]+mV[e[t+11]]+mV[e[t+12]]+mV[e[t+13]]+mV[e[t+14]]+mV[e[t+15]]}var jlp=li(require("crypto")),RIs={randomUUID:jlp.default.randomUUID};function F2S(e,t,r){if(RIs.randomUUID&&!t&&!e)return RIs.randomUUID();e=e||{};let i=e.random||(e.rng||zIs)();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 Plp(i)}var Uie=F2S;var L2S="id",U2S=".fern",sla=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new rPn(r),this.userId=t==null?void 0:$Es(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.60.21",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Lu(Hl.of((0,wlp.homedir)()),Xa.of(U2S),Xa.of(L2S));await Cf(t)||(await(0,iPn.mkdir)((0,Slp.dirname)(t),{recursive:!0}),await(0,iPn.writeFile)(t,Uie())),this.persistedDistinctId=(await(0,iPn.readFile)(t)).toString()}return this.persistedDistinctId}};var NIs;async function nPn(){return NIs==null&&(NIs=await V2S()),NIs}async function V2S(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new ula;let r=await ayo();return r!=null?new sla({token:r,posthogApiKey:e}):await $gn()!=null?new tPo({posthogApiKey:e}):new sla({token:void 0,posthogApiKey:e})}catch{return new ula}}function cla(e,t){return function(){return e.apply(t,arguments)}}var{toString:W2S}=Object.prototype,{getPrototypeOf:LIs}=Object,aPo=(e=>t=>{let r=W2S.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),w5t=e=>(e=e.toLowerCase(),t=>aPo(t)===e),oPo=e=>t=>typeof t===e,{isArray:aPn}=Array,lla=oPo("undefined");function H2S(e){return e!==null&&!lla(e)&&e.constructor!==null&&!lla(e.constructor)&&tDe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var Elp=w5t("ArrayBuffer");function $2S(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Elp(e.buffer),t}var G2S=oPo("string"),tDe=oPo("function"),Mlp=oPo("number"),uPo=e=>e!==null&&typeof e=="object",Q2S=e=>e===!0||e===!1,nPo=e=>{if(aPo(e)!=="object")return!1;let t=LIs(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},J2S=w5t("Date"),K2S=w5t("File"),Y2S=w5t("Blob"),X2S=w5t("FileList"),Z2S=e=>uPo(e)&&tDe(e.pipe),k2S=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||tDe(e.append)&&((t=aPo(e))==="formdata"||t==="object"&&tDe(e.toString)&&e.toString()==="[object FormData]"))},e4S=w5t("URLSearchParams"),[t4S,r4S,i4S,n4S]=["ReadableStream","Request","Response","Headers"].map(w5t),a4S=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function fla(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),aPn(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 Alp(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 dzi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,qlp=e=>!lla(e)&&e!==dzi;function FIs(){let{caseless:e}=qlp(this)&&this||{},t={},r=(i,n)=>{let a=e&&Alp(t,n)||n;nPo(t[a])&&nPo(i)?t[a]=FIs(t[a],i):nPo(i)?t[a]=FIs({},i):aPn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&fla(arguments[i],r);return t}var o4S=(e,t,r,{allOwnKeys:i}={})=>(fla(t,(n,a)=>{r&&tDe(n)?e[a]=cla(n,r):e[a]=n},{allOwnKeys:i}),e),u4S=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),s4S=(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)},c4S=(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&&LIs(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},l4S=(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},f4S=e=>{if(!e)return null;if(aPn(e))return e;let t=e.length;if(!Mlp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},d4S=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&LIs(Uint8Array)),p4S=(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])}},_4S=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},h4S=w5t("HTMLFormElement"),y4S=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),Dlp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),v4S=w5t("RegExp"),Tlp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};fla(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},b4S=e=>{Tlp(e,(t,r)=>{if(tDe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(tDe(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+"'")})}})},g4S=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return aPn(e)?i(e):i(String(e).split(t)),r},O4S=()=>{},m4S=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function P4S(e){return!!(e&&tDe(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var j4S=e=>{let t=new Array(10),r=(i,n)=>{if(uPo(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=aPn(i)?[]:{};return fla(i,(u,l)=>{let f=r(u,n+1);!lla(f)&&(a[l]=f)}),t[n]=void 0,a}}return i};return r(e,0)},w4S=w5t("AsyncFunction"),S4S=e=>e&&(uPo(e)||tDe(e))&&tDe(e.then)&&tDe(e.catch),Clp=((e,t)=>e?setImmediate:t?((r,i)=>(dzi.addEventListener("message",({source:n,data:a})=>{n===dzi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),dzi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",tDe(dzi.postMessage)),D4S=typeof queueMicrotask<"u"?queueMicrotask.bind(dzi):typeof process<"u"&&process.nextTick||Clp,ds={isArray:aPn,isArrayBuffer:Elp,isBuffer:H2S,isFormData:k2S,isArrayBufferView:$2S,isString:G2S,isNumber:Mlp,isBoolean:Q2S,isObject:uPo,isPlainObject:nPo,isReadableStream:t4S,isRequest:r4S,isResponse:i4S,isHeaders:n4S,isUndefined:lla,isDate:J2S,isFile:K2S,isBlob:Y2S,isRegExp:v4S,isFunction:tDe,isStream:Z2S,isURLSearchParams:e4S,isTypedArray:d4S,isFileList:X2S,forEach:fla,merge:FIs,extend:o4S,trim:a4S,stripBOM:u4S,inherits:s4S,toFlatObject:c4S,kindOf:aPo,kindOfTest:w5t,endsWith:l4S,toArray:f4S,forEachEntry:p4S,matchAll:_4S,isHTMLForm:h4S,hasOwnProperty:Dlp,hasOwnProp:Dlp,reduceDescriptors:Tlp,freezeMethods:b4S,toObjectSet:g4S,toCamelCase:y4S,noop:O4S,toFiniteNumber:m4S,findKey:Alp,global:dzi,isContextDefined:qlp,isSpecCompliantForm:P4S,toJSONObject:j4S,isAsyncFn:w4S,isThenable:S4S,setImmediate:Clp,asap:D4S};function oPn(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)}ds.inherits(oPn,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:ds.toJSONObject(this.config),code:this.code,status:this.status}}});var Blp=oPn.prototype,xlp={};["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=>{xlp[e]={value:e}});Object.defineProperties(oPn,xlp);Object.defineProperty(Blp,"isAxiosError",{value:!0});oPn.from=(e,t,r,i,n,a)=>{let u=Object.create(Blp);return ds.toFlatObject(e,u,function(f){return f!==Error.prototype},l=>l!=="isAxiosError"),oPn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var Ep=oPn;var Ilp=li(Cia(),1),sPo=Ilp.default;function UIs(e){return ds.isPlainObject(e)||ds.isArray(e)}function Rlp(e){return ds.endsWith(e,"[]")?e.slice(0,-2):e}function zlp(e,t,r){return e?e.concat(t).map(function(n,a){return n=Rlp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function E4S(e){return ds.isArray(e)&&!e.some(UIs)}var M4S=ds.toFlatObject(ds,{},null,function(t){return/^is[A-Z]/.test(t)});function A4S(e,t,r){if(!ds.isObject(e))throw new TypeError("target must be an object");t=t||new(sPo||FormData),r=ds.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,P){return!ds.isUndefined(P[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,f=(r.Blob||typeof Blob<"u"&&Blob)&&ds.isSpecCompliantForm(t);if(!ds.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(ds.isDate(O))return O.toISOString();if(!f&&ds.isBlob(O))throw new Ep("Blob is not supported. Use a Buffer instead.");return ds.isArrayBuffer(O)||ds.isTypedArray(O)?f&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,P){let E=O;if(O&&!P&&typeof O=="object"){if(ds.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(ds.isArray(O)&&E4S(O)||(ds.isFileList(O)||ds.endsWith(m,"[]"))&&(E=ds.toArray(O)))return m=Rlp(m),E.forEach(function(A,D){!(ds.isUndefined(A)||A===null)&&t.append(u===!0?zlp([m],D,a):u===null?m:m+"[]",s(A))}),!1}return UIs(O)?!0:(t.append(zlp(P,m,a),s(O)),!1)}let c=[],b=Object.assign(M4S,{defaultVisitor:o,convertValue:s,isVisitable:UIs});function g(O,m){if(!ds.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),ds.forEach(O,function(E,q){(!(ds.isUndefined(E)||E===null)&&n.call(t,E,ds.isString(q)?q.trim():q,m,b))===!0&&g(E,m?m.concat(q):[q])}),c.pop()}}if(!ds.isObject(e))throw new TypeError("data must be an object");return g(e),t}var mfi=A4S;function Nlp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function Flp(e,t){this._pairs=[],e&&mfi(e,this,t)}var Llp=Flp.prototype;Llp.append=function(t,r){this._pairs.push([t,r])};Llp.toString=function(t){let r=t?function(i){return t.call(this,i,Nlp)}:Nlp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var Ulp=Flp;function q4S(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function pzi(e,t,r){if(!t)return e;let i=r&&r.encode||q4S;ds.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=ds.isURLSearchParams(t)?t.toString():new Ulp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var VIs=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){ds.forEach(this.handlers,function(i){i!==null&&t(i)})}},WIs=VIs;var uPn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var $lp=li(require("crypto"),1);var Vlp=li(require("url"),1),Wlp=Vlp.default.URLSearchParams;var HIs="abcdefghijklmnopqrstuvwxyz",Hlp="0123456789",Glp={DIGIT:Hlp,ALPHA:HIs,ALPHA_DIGIT:HIs+HIs.toUpperCase()+Hlp},T4S=(e=16,t=Glp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);$lp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},Qlp={isNode:!0,classes:{URLSearchParams:Wlp,FormData:sPo,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:Glp,generateString:T4S,protocols:["http","https","file","data"]};var QIs={};jo(QIs,{hasBrowserEnv:()=>GIs,hasStandardBrowserEnv:()=>C4S,hasStandardBrowserWebWorkerEnv:()=>B4S,navigator:()=>$Is,origin:()=>x4S});var GIs=typeof window<"u"&&typeof document<"u",$Is=typeof navigator=="object"&&navigator||void 0,C4S=GIs&&(!$Is||["ReactNative","NativeScript","NS"].indexOf($Is.product)<0),B4S=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",x4S=GIs&&window.location.href||"http://localhost";var AM={...QIs,...Qlp};function JIs(e,t){return mfi(e,new AM.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return AM.isNode&&ds.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function I4S(e){return ds.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function z4S(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 R4S(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let l=Number.isFinite(+u),f=a>=r.length;return u=!u&&ds.isArray(n)?n.length:u,f?(ds.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!ds.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&ds.isArray(n[u])&&(n[u]=z4S(n[u])),!l)}if(ds.isFormData(e)&&ds.isFunction(e.entries)){let r={};return ds.forEachEntry(e,(i,n)=>{t(I4S(i),n,r,0)}),r}return null}var cPo=R4S;function N4S(e,t,r){if(ds.isString(e))try{return(t||JSON.parse)(e),ds.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var KIs={transitional:uPn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=ds.isObject(t);if(a&&ds.isHTMLForm(t)&&(t=new FormData(t)),ds.isFormData(t))return n?JSON.stringify(cPo(t)):t;if(ds.isArrayBuffer(t)||ds.isBuffer(t)||ds.isStream(t)||ds.isFile(t)||ds.isBlob(t)||ds.isReadableStream(t))return t;if(ds.isArrayBufferView(t))return t.buffer;if(ds.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 JIs(t,this.formSerializer).toString();if((l=ds.isFileList(t))||i.indexOf("multipart/form-data")>-1){let f=this.env&&this.env.FormData;return mfi(l?{"files[]":t}:t,f&&new f,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),N4S(t)):t}],transformResponse:[function(t){let r=this.transitional||KIs.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(ds.isResponse(t)||ds.isReadableStream(t))return t;if(t&&ds.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"?Ep.from(l,Ep.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:AM.classes.FormData,Blob:AM.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ds.forEach(["delete","get","head","post","put","patch"],e=>{KIs.headers[e]={}});var sPn=KIs;var F4S=ds.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"]),Jlp=e=>{let t={},r,i,n;return e&&e.split(`
|
|
1705
1705
|
`).forEach(function(u){n=u.indexOf(":"),r=u.substring(0,n).trim().toLowerCase(),i=u.substring(n+1).trim(),!(!r||t[r]&&F4S[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var Klp=Symbol("internals");function dla(e){return e&&String(e).trim().toLowerCase()}function lPo(e){return e===!1||e==null?e:ds.isArray(e)?e.map(lPo):String(e)}function L4S(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 U4S=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function YIs(e,t,r,i,n){if(ds.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!ds.isString(t)){if(ds.isString(i))return t.indexOf(i)!==-1;if(ds.isRegExp(i))return i.test(t)}}function V4S(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function W4S(e,t){let r=ds.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 cPn=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(l,f,s){let o=dla(f);if(!o)throw new Error("header name must be a non-empty string");let c=ds.findKey(n,o);(!c||n[c]===void 0||s===!0||s===void 0&&n[c]!==!1)&&(n[c||f]=lPo(l))}let u=(l,f)=>ds.forEach(l,(s,o)=>a(s,o,f));if(ds.isPlainObject(t)||t instanceof this.constructor)u(t,r);else if(ds.isString(t)&&(t=t.trim())&&!U4S(t))u(Jlp(t),r);else if(ds.isHeaders(t))for(let[l,f]of t.entries())a(f,l,i);else t!=null&&a(r,t,i);return this}get(t,r){if(t=dla(t),t){let i=ds.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return L4S(n);if(ds.isFunction(r))return r.call(this,n,i);if(ds.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=dla(t),t){let i=ds.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||YIs(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(u){if(u=dla(u),u){let l=ds.findKey(i,u);l&&(!r||YIs(i,i[l],l,r))&&(delete i[l],n=!0)}}return ds.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||YIs(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return ds.forEach(this,(n,a)=>{let u=ds.findKey(i,a);if(u){r[u]=lPo(n),delete r[a];return}let l=t?V4S(a):String(a).trim();l!==a&&delete r[a],r[l]=lPo(n),i[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return ds.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&ds.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(`
|
|
1706
1706
|
`)}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[Klp]=this[Klp]={accessors:{}}).accessors,n=this.prototype;function a(u){let l=dla(u);i[l]||(W4S(n,u),i[l]=!0)}return ds.isArray(t)?t.forEach(a):a(t),this}};cPn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);ds.reduceDescriptors(cPn.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});ds.freezeMethods(cPn);var bz=cPn;function pla(e,t){let r=this||sPn,i=t||r,n=bz.from(i.headers),a=i.data;return ds.forEach(e,function(l){a=l.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function _la(e){return!!(e&&e.__CANCEL__)}function Ylp(e,t,r){Ep.call(this,e??"canceled",Ep.ERR_CANCELED,t,r),this.name="CanceledError"}ds.inherits(Ylp,Ep,{__CANCEL__:!0});var rDe=Ylp;function eXt(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new Ep("Request failed with status code "+r.status,[Ep.ERR_BAD_REQUEST,Ep.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function XIs(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function ZIs(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function _zi(e,t,r){let i=!XIs(t);return e&&i||r==!1?ZIs(e,t):t}var dfp=li(Kca(),1),pfp=li(require("http"),1),_fp=li(require("https"),1),hfp=li(require("util"),1),yfp=li(aIs(),1),$Jr=li(require("zlib"),1);var hzi="1.8.2";function hla(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var H4S=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function kIs(e,t,r){let i=r&&r.Blob||AM.classes.Blob,n=hla(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=H4S.exec(e);if(!a)throw new Ep("Invalid URL",Ep.ERR_INVALID_URL);let u=a[1],l=a[2],f=a[3],s=Buffer.from(decodeURIComponent(f),l?"base64":"utf8");if(t){if(!i)throw new Ep("Blob is not supported",Ep.ERR_NOT_SUPPORT);return new i([s],{type:u})}return s}throw new Ep("Unsupported protocol "+n,Ep.ERR_NOT_SUPPORT)}var yzi=li(require("stream"),1);var Xlp=li(require("stream"),1);var ezs=Symbol("internals"),tzs=class extends Xlp.default.Transform{constructor(t){t=ds.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!ds.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[ezs]={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[ezs];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[ezs],a=n.maxRate,u=this.readableHighWaterMark,l=n.timeWindow,f=1e3/l,s=a/f,o=n.minChunkSize!==!1?Math.max(n.minChunkSize,s*.01):0,c=(g,O)=>{let m=Buffer.byteLength(g);n.bytesSeen+=m,n.bytes+=m,n.isCaptured&&this.emit("progress",n.bytesSeen),this.push(g)?process.nextTick(O):n.onReadCallback=()=>{n.onReadCallback=null,process.nextTick(O)}},b=(g,O)=>{let m=Buffer.byteLength(g),P=null,E=u,q,A=0;if(a){let D=Date.now();(!n.ts||(A=D-n.ts)>=l)&&(n.ts=D,q=s-n.bytes,n.bytes=q<0?-q:0,A=0),q=s-n.bytes}if(a){if(q<=0)return setTimeout(()=>{O(null,g)},l-A);q<E&&(E=q)}E&&m>E&&m-E>o&&(P=g.subarray(E),g=g.subarray(0,E)),c(g,P?()=>{process.nextTick(O,null,P)}:O)};b(t,function g(O,m){if(O)return i(O);m?b(m,g):i(null)})}},rzs=tzs;var vfp=require("events");var klp=li(require("util"),1),efp=require("stream");var{asyncIterator:Zlp}=Symbol,$4S=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[Zlp]?yield*e[Zlp]():yield e},fPo=$4S;var G4S=AM.ALPHABET.ALPHA_DIGIT+"-_",yla=typeof TextEncoder=="function"?new TextEncoder:new klp.default.TextEncoder,Pfi=`\r
|
|
1707
1707
|
`,Q4S=yla.encode(Pfi),J4S=2,izs=class{constructor(t,r){let{escapeName:i}=this.constructor,n=ds.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${Pfi}`;n?r=yla.encode(String(r).replace(/\r?\n|\r\n?/g,Pfi)):a+=`Content-Type: ${r.type||"application/octet-stream"}${Pfi}`,this.headers=yla.encode(a+Pfi),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+J4S,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;ds.isTypedArray(t)?yield t:yield*fPo(t),yield Q4S}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},K4S=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+AM.generateString(n,G4S)}=r||{};if(!ds.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=yla.encode("--"+a+Pfi),l=yla.encode("--"+a+"--"+Pfi+Pfi),f=l.byteLength,s=Array.from(e.entries()).map(([c,b])=>{let g=new izs(c,b);return f+=g.size,g});f+=u.byteLength*s.length,f=ds.toFiniteNumber(f);let o={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(f)&&(o["Content-Length"]=f),t&&t(o),efp.Readable.from(async function*(){for(let c of s)yield u,yield*c.encode();yield l}())},tfp=K4S;var rfp=li(require("stream"),1),nzs=class extends rfp.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)}},ifp=nzs;var Y4S=(e,t)=>ds.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,nfp=Y4S;function X4S(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(f){let s=Date.now(),o=i[a];u||(u=s),r[n]=f,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 afp=X4S;function Z4S(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 ofp=Z4S;var HJr=(e,t,r=3)=>{let i=0,n=afp(50,250);return ofp(a=>{let u=a.loaded,l=a.lengthComputable?a.total:void 0,f=u-i,s=n(f),o=u<=l;i=u;let c={loaded:u,total:l,progress:l?u/l:void 0,bytes:f,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)},lPn=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},fPn=e=>(...t)=>ds.asap(()=>e(...t));var ufp={flush:$Jr.default.constants.Z_SYNC_FLUSH,finishFlush:$Jr.default.constants.Z_SYNC_FLUSH},k4S={flush:$Jr.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:$Jr.default.constants.BROTLI_OPERATION_FLUSH},sfp=ds.isFunction($Jr.default.createBrotliDecompress),{http:e8S,https:t8S}=yfp.default,r8S=/https:?/,cfp=AM.protocols.map(e=>e+":"),lfp=(e,[t,r])=>(e.on("end",r).on("error",r),t);function i8S(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function bfp(e,t,r){let i=t;if(!i&&i!==!1){let n=dfp.default.getProxyForUrl(r);n&&(i=new URL(n))}if(i){if(i.username&&(i.auth=(i.username||"")+":"+(i.password||"")),i.auth){(i.auth.username||i.auth.password)&&(i.auth=(i.auth.username||"")+":"+(i.auth.password||""));let a=Buffer.from(i.auth,"utf8").toString("base64");e.headers["Proxy-Authorization"]="Basic "+a}e.headers.host=e.hostname+(e.port?":"+e.port:"");let n=i.hostname||i.host;e.hostname=n,e.host=n,e.port=i.port,e.path=r,i.protocol&&(e.protocol=i.protocol.includes(":")?i.protocol:`${i.protocol}:`)}e.beforeRedirects.proxy=function(a){bfp(a,t,a.href)}}var n8S=typeof process<"u"&&ds.kindOf(process)==="process",a8S=e=>new Promise((t,r)=>{let i,n,a=(f,s)=>{n||(n=!0,i&&i(f,s))},u=f=>{a(f),t(f)},l=f=>{a(f,!0),r(f)};e(u,l,f=>i=f).catch(l)}),o8S=({address:e,family:t})=>{if(!ds.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},ffp=(e,t)=>o8S(ds.isObject(e)?e:{address:e,family:t}),gfp=n8S&&function(t){return a8S(async function(i,n,a){let{data:u,lookup:l,family:f}=t,{responseType:s,responseEncoding:o}=t,c=t.method.toUpperCase(),b,g=!1,O;if(l){let Se=nfp(l,Qe=>ds.isArray(Qe)?Qe:[Qe]);l=(Qe,St,Ee)=>{Se(Qe,St,(Te,It,je)=>{if(Te)return Ee(Te);let Ot=ds.isArray(It)?It.map(at=>ffp(at)):[ffp(It,je)];St.all?Ee(Te,Ot):Ee(Te,Ot[0].address,Ot[0].family)})}}let m=new vfp.EventEmitter,P=()=>{t.cancelToken&&t.cancelToken.unsubscribe(E),t.signal&&t.signal.removeEventListener("abort",E),m.removeAllListeners()};a((Se,Qe)=>{b=!0,Qe&&(g=!0,P())});function E(Se){m.emit("abort",!Se||Se.type?new rDe(null,t,O):Se)}m.once("abort",n),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(E),t.signal&&(t.signal.aborted?E():t.signal.addEventListener("abort",E)));let q=_zi(t.baseURL,t.url,t.allowAbsoluteUrls),A=new URL(q,AM.hasBrowserEnv?AM.origin:void 0),D=A.protocol||cfp[0];if(D==="data:"){let Se;if(c!=="GET")return eXt(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{Se=kIs(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(Qe){throw Ep.from(Qe,Ep.ERR_BAD_REQUEST,t)}return s==="text"?(Se=Se.toString(o),(!o||o==="utf8")&&(Se=ds.stripBOM(Se))):s==="stream"&&(Se=yzi.default.Readable.from(Se)),eXt(i,n,{data:Se,status:200,statusText:"OK",headers:new bz,config:t})}if(cfp.indexOf(D)===-1)return n(new Ep("Unsupported protocol "+D,Ep.ERR_BAD_REQUEST,t));let C=bz.from(t.headers).normalize();C.set("User-Agent","axios/"+hzi,!1);let{onUploadProgress:z,onDownloadProgress:$}=t,x=t.maxRate,L,V;if(ds.isSpecCompliantForm(u)){let Se=C.getContentType(/boundary=([-_\w\d]{10,70})/i);u=tfp(u,Qe=>{C.set(Qe)},{tag:`axios-${hzi}-boundary`,boundary:Se&&Se[1]||void 0})}else if(ds.isFormData(u)&&ds.isFunction(u.getHeaders)){if(C.set(u.getHeaders()),!C.hasContentLength())try{let Se=await hfp.default.promisify(u.getLength).call(u);Number.isFinite(Se)&&Se>=0&&C.setContentLength(Se)}catch{}}else if(ds.isBlob(u)||ds.isFile(u))u.size&&C.setContentType(u.type||"application/octet-stream"),C.setContentLength(u.size||0),u=yzi.default.Readable.from(fPo(u));else if(u&&!ds.isStream(u)){if(!Buffer.isBuffer(u))if(ds.isArrayBuffer(u))u=Buffer.from(new Uint8Array(u));else if(ds.isString(u))u=Buffer.from(u,"utf-8");else return n(new Ep("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",Ep.ERR_BAD_REQUEST,t));if(C.setContentLength(u.length,!1),t.maxBodyLength>-1&&u.length>t.maxBodyLength)return n(new Ep("Request body larger than maxBodyLength limit",Ep.ERR_BAD_REQUEST,t))}let Y=ds.toFiniteNumber(C.getContentLength());ds.isArray(x)?(L=x[0],V=x[1]):L=V=x,u&&(z||L)&&(ds.isStream(u)||(u=yzi.default.Readable.from(u,{objectMode:!1})),u=yzi.default.pipeline([u,new rzs({maxRate:ds.toFiniteNumber(L)})],ds.noop),z&&u.on("progress",lfp(u,lPn(Y,HJr(fPn(z),!1,3)))));let K;if(t.auth){let Se=t.auth.username||"",Qe=t.auth.password||"";K=Se+":"+Qe}if(!K&&A.username){let Se=A.username,Qe=A.password;K=Se+":"+Qe}K&&C.delete("authorization");let Z;try{Z=pzi(A.pathname+A.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(Se){let Qe=new Error(Se.message);return Qe.config=t,Qe.url=t.url,Qe.exists=!0,n(Qe)}C.set("Accept-Encoding","gzip, compress, deflate"+(sfp?", br":""),!1);let fe={path:Z,method:c,headers:C.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:K,protocol:D,family:f,beforeRedirect:i8S,beforeRedirects:{}};!ds.isUndefined(l)&&(fe.lookup=l),t.socketPath?fe.socketPath=t.socketPath:(fe.hostname=A.hostname.startsWith("[")?A.hostname.slice(1,-1):A.hostname,fe.port=A.port,bfp(fe,t.proxy,D+"//"+A.hostname+(A.port?":"+A.port:"")+fe.path));let me,_e=r8S.test(fe.protocol);if(fe.agent=_e?t.httpsAgent:t.httpAgent,t.transport?me=t.transport:t.maxRedirects===0?me=_e?_fp.default:pfp.default:(t.maxRedirects&&(fe.maxRedirects=t.maxRedirects),t.beforeRedirect&&(fe.beforeRedirects.config=t.beforeRedirect),me=_e?t8S:e8S),t.maxBodyLength>-1?fe.maxBodyLength=t.maxBodyLength:fe.maxBodyLength=1/0,t.insecureHTTPParser&&(fe.insecureHTTPParser=t.insecureHTTPParser),O=me.request(fe,function(Qe){if(O.destroyed)return;let St=[Qe],Ee=+Qe.headers["content-length"];if($||V){let at=new rzs({maxRate:ds.toFiniteNumber(V)});$&&at.on("progress",lfp(at,lPn(Ee,HJr(fPn($),!0,3)))),St.push(at)}let Te=Qe,It=Qe.req||O;if(t.decompress!==!1&&Qe.headers["content-encoding"])switch((c==="HEAD"||Qe.statusCode===204)&&delete Qe.headers["content-encoding"],(Qe.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":St.push($Jr.default.createUnzip(ufp)),delete Qe.headers["content-encoding"];break;case"deflate":St.push(new ifp),St.push($Jr.default.createUnzip(ufp)),delete Qe.headers["content-encoding"];break;case"br":sfp&&(St.push($Jr.default.createBrotliDecompress(k4S)),delete Qe.headers["content-encoding"])}Te=St.length>1?yzi.default.pipeline(St,ds.noop):St[0];let je=yzi.default.finished(Te,()=>{je(),P()}),Ot={status:Qe.statusCode,statusText:Qe.statusMessage,headers:new bz(Qe.headers),config:t,request:It};if(s==="stream")Ot.data=Te,eXt(i,n,Ot);else{let at=[],he=0;Te.on("data",function(bt){at.push(bt),he+=bt.length,t.maxContentLength>-1&&he>t.maxContentLength&&(g=!0,Te.destroy(),n(new Ep("maxContentLength size of "+t.maxContentLength+" exceeded",Ep.ERR_BAD_RESPONSE,t,It)))}),Te.on("aborted",function(){if(g)return;let bt=new Ep("stream has been aborted",Ep.ERR_BAD_RESPONSE,t,It);Te.destroy(bt),n(bt)}),Te.on("error",function(bt){O.destroyed||n(Ep.from(bt,null,t,It))}),Te.on("end",function(){try{let bt=at.length===1?at[0]:Buffer.concat(at);s!=="arraybuffer"&&(bt=bt.toString(o),(!o||o==="utf8")&&(bt=ds.stripBOM(bt))),Ot.data=bt}catch(bt){return n(Ep.from(bt,null,t,Ot.request,Ot))}eXt(i,n,Ot)})}m.once("abort",at=>{Te.destroyed||(Te.emit("error",at),Te.destroy())})}),m.once("abort",Se=>{n(Se),O.destroy(Se)}),O.on("error",function(Qe){n(Ep.from(Qe,null,t,O))}),O.on("socket",function(Qe){Qe.setKeepAlive(!0,1e3*60)}),t.timeout){let Se=parseInt(t.timeout,10);if(Number.isNaN(Se)){n(new Ep("error trying to parse `config.timeout` to int",Ep.ERR_BAD_OPTION_VALUE,t,O));return}O.setTimeout(Se,function(){if(b)return;let St=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",Ee=t.transitional||uPn;t.timeoutErrorMessage&&(St=t.timeoutErrorMessage),n(new Ep(St,Ee.clarifyTimeoutError?Ep.ETIMEDOUT:Ep.ECONNABORTED,t,O)),E()})}if(ds.isStream(u)){let Se=!1,Qe=!1;u.on("end",()=>{Se=!0}),u.once("error",St=>{Qe=!0,O.destroy(St)}),u.on("close",()=>{!Se&&!Qe&&E(new rDe("Request stream has been aborted",t,O))}),u.pipe(O)}else O.end(u)})};var Ofp=AM.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,AM.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(AM.origin),AM.navigator&&/(msie|trident)/i.test(AM.navigator.userAgent)):()=>!0;var mfp=AM.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let u=[e+"="+encodeURIComponent(t)];ds.isNumber(r)&&u.push("expires="+new Date(r).toGMTString()),ds.isString(i)&&u.push("path="+i),ds.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 Pfp=e=>e instanceof bz?{...e}:e;function S5t(e,t){t=t||{};let r={};function i(s,o,c,b){return ds.isPlainObject(s)&&ds.isPlainObject(o)?ds.merge.call({caseless:b},s,o):ds.isPlainObject(o)?ds.merge({},o):ds.isArray(o)?o.slice():o}function n(s,o,c,b){if(ds.isUndefined(o)){if(!ds.isUndefined(s))return i(void 0,s,c,b)}else return i(s,o,c,b)}function a(s,o){if(!ds.isUndefined(o))return i(void 0,o)}function u(s,o){if(ds.isUndefined(o)){if(!ds.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 f={url:a,method:a,data:a,baseURL:u,transformRequest:u,transformResponse:u,paramsSerializer:u,timeout:u,timeoutMessage:u,withCredentials:u,withXSRFToken:u,adapter:u,responseType:u,xsrfCookieName:u,xsrfHeaderName:u,onUploadProgress:u,onDownloadProgress:u,decompress:u,maxContentLength:u,maxBodyLength:u,beforeRedirect:u,transport:u,httpAgent:u,httpsAgent:u,cancelToken:u,socketPath:u,responseEncoding:u,validateStatus:l,headers:(s,o,c)=>n(Pfp(s),Pfp(o),c,!0)};return ds.forEach(Object.keys(Object.assign({},e,t)),function(o){let c=f[o]||n,b=c(e[o],t[o],o);ds.isUndefined(b)&&c!==l||(r[o]=b)}),r}var dPo=e=>{let t=S5t({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:u,auth:l}=t;t.headers=u=bz.from(u),t.url=pzi(_zi(t.baseURL,t.url),e.params,e.paramsSerializer),l&&u.set("Authorization","Basic "+btoa((l.username||"")+":"+(l.password?unescape(encodeURIComponent(l.password)):"")));let f;if(ds.isFormData(r)){if(AM.hasStandardBrowserEnv||AM.hasStandardBrowserWebWorkerEnv)u.setContentType(void 0);else if((f=u.getContentType())!==!1){let[s,...o]=f?f.split(";").map(c=>c.trim()).filter(Boolean):[];u.setContentType([s||"multipart/form-data",...o].join("; "))}}if(AM.hasStandardBrowserEnv&&(i&&ds.isFunction(i)&&(i=i(t)),i||i!==!1&&Ofp(t.url))){let s=n&&a&&mfp.read(a);s&&u.set(n,s)}return t};var u8S=typeof XMLHttpRequest<"u",jfp=u8S&&function(e){return new Promise(function(r,i){let n=dPo(e),a=n.data,u=bz.from(n.headers).normalize(),{responseType:l,onUploadProgress:f,onDownloadProgress:s}=n,o,c,b,g,O;function m(){g&&g(),O&&O(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let P=new XMLHttpRequest;P.open(n.method.toUpperCase(),n.url,!0),P.timeout=n.timeout;function E(){if(!P)return;let A=bz.from("getAllResponseHeaders"in P&&P.getAllResponseHeaders()),C={data:!l||l==="text"||l==="json"?P.responseText:P.response,status:P.status,statusText:P.statusText,headers:A,config:e,request:P};eXt(function($){r($),m()},function($){i($),m()},C),P=null}"onloadend"in P?P.onloadend=E:P.onreadystatechange=function(){!P||P.readyState!==4||P.status===0&&!(P.responseURL&&P.responseURL.indexOf("file:")===0)||setTimeout(E)},P.onabort=function(){P&&(i(new Ep("Request aborted",Ep.ECONNABORTED,e,P)),P=null)},P.onerror=function(){i(new Ep("Network Error",Ep.ERR_NETWORK,e,P)),P=null},P.ontimeout=function(){let D=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",C=n.transitional||uPn;n.timeoutErrorMessage&&(D=n.timeoutErrorMessage),i(new Ep(D,C.clarifyTimeoutError?Ep.ETIMEDOUT:Ep.ECONNABORTED,e,P)),P=null},a===void 0&&u.setContentType(null),"setRequestHeader"in P&&ds.forEach(u.toJSON(),function(D,C){P.setRequestHeader(C,D)}),ds.isUndefined(n.withCredentials)||(P.withCredentials=!!n.withCredentials),l&&l!=="json"&&(P.responseType=n.responseType),s&&([b,O]=HJr(s,!0),P.addEventListener("progress",b)),f&&P.upload&&([c,g]=HJr(f),P.upload.addEventListener("progress",c),P.upload.addEventListener("loadend",g)),(n.cancelToken||n.signal)&&(o=A=>{P&&(i(!A||A.type?new rDe(null,e,P):A),P.abort(),P=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));let q=hla(n.url);if(q&&AM.protocols.indexOf(q)===-1){i(new Ep("Unsupported protocol "+q+":",Ep.ERR_BAD_REQUEST,e));return}P.send(a||null)})};var s8S=(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 Ep?o:new rDe(o instanceof Error?o.message:o))}},u=t&&setTimeout(()=>{u=null,a(new Ep(`timeout ${t} of ms exceeded`,Ep.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:f}=i;return f.unsubscribe=()=>ds.asap(l),f}},wfp=s8S;var c8S=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},l8S=async function*(e,t){for await(let r of f8S(e))yield*c8S(r,t)},f8S=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()}},azs=(e,t,r,i)=>{let n=l8S(e,t),a=0,u,l=f=>{u||(u=!0,i&&i(f))};return new ReadableStream({async pull(f){try{let{done:s,value:o}=await n.next();if(s){l(),f.close();return}let c=o.byteLength;if(r){let b=a+=c;r(b)}f.enqueue(new Uint8Array(o))}catch(s){throw l(s),s}},cancel(f){return l(f),n.return()}},{highWaterMark:2})};var _Po=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",Dfp=_Po&&typeof ReadableStream=="function",d8S=_Po&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),Efp=(e,...t)=>{try{return!!e(...t)}catch{return!1}},p8S=Dfp&&Efp(()=>{let e=!1,t=new Request(AM.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),Sfp=64*1024,ozs=Dfp&&Efp(()=>ds.isReadableStream(new Response("").body)),pPo={stream:ozs&&(e=>e.body)};_Po&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!pPo[t]&&(pPo[t]=ds.isFunction(e[t])?r=>r[t]():(r,i)=>{throw new Ep(`Response type '${t}' is not supported`,Ep.ERR_NOT_SUPPORT,i)})})})(new Response);var _8S=async e=>{if(e==null)return 0;if(ds.isBlob(e))return e.size;if(ds.isSpecCompliantForm(e))return(await new Request(AM.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(ds.isArrayBufferView(e)||ds.isArrayBuffer(e))return e.byteLength;if(ds.isURLSearchParams(e)&&(e=e+""),ds.isString(e))return(await d8S(e)).byteLength},h8S=async(e,t)=>{let r=ds.toFiniteNumber(e.getContentLength());return r??_8S(t)},Mfp=_Po&&(async e=>{let{url:t,method:r,data:i,signal:n,cancelToken:a,timeout:u,onDownloadProgress:l,onUploadProgress:f,responseType:s,headers:o,withCredentials:c="same-origin",fetchOptions:b}=dPo(e);s=s?(s+"").toLowerCase():"text";let g=wfp([n,a&&a.toAbortSignal()],u),O,m=g&&g.unsubscribe&&(()=>{g.unsubscribe()}),P;try{if(f&&p8S&&r!=="get"&&r!=="head"&&(P=await h8S(o,i))!==0){let C=new Request(t,{method:"POST",body:i,duplex:"half"}),z;if(ds.isFormData(i)&&(z=C.headers.get("content-type"))&&o.setContentType(z),C.body){let[$,x]=lPn(P,HJr(fPn(f)));i=azs(C.body,Sfp,$,x)}}ds.isString(c)||(c=c?"include":"omit");let E="credentials"in Request.prototype;O=new Request(t,{...b,signal:g,method:r.toUpperCase(),headers:o.normalize().toJSON(),body:i,duplex:"half",credentials:E?c:void 0});let q=await fetch(O),A=ozs&&(s==="stream"||s==="response");if(ozs&&(l||A&&m)){let C={};["status","statusText","headers"].forEach(L=>{C[L]=q[L]});let z=ds.toFiniteNumber(q.headers.get("content-length")),[$,x]=l&&lPn(z,HJr(fPn(l),!0))||[];q=new Response(azs(q.body,Sfp,$,()=>{x&&x(),m&&m()}),C)}s=s||"text";let D=await pPo[ds.findKey(pPo,s)||"text"](q,e);return!A&&m&&m(),await new Promise((C,z)=>{eXt(C,z,{data:D,headers:bz.from(q.headers),status:q.status,statusText:q.statusText,config:e,request:O})})}catch(E){throw m&&m(),E&&E.name==="TypeError"&&/fetch/i.test(E.message)?Object.assign(new Ep("Network Error",Ep.ERR_NETWORK,e,O),{cause:E.cause||E}):Ep.from(E,E&&E.code,e,O)}});var uzs={http:gfp,xhr:jfp,fetch:Mfp};ds.forEach(uzs,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var Afp=e=>`- ${e}`,y8S=e=>ds.isFunction(e)||e===null||e===!1,hPo={getAdapter:e=>{e=ds.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,!y8S(r)&&(i=uzs[(u=String(r)).toLowerCase()],i===void 0))throw new Ep(`Unknown adapter '${u}'`);if(i)break;n[u||"#"+a]=i}if(!i){let a=Object.entries(n).map(([l,f])=>`adapter ${l} `+(f===!1?"is not supported by the environment":"is not available in the build")),u=t?a.length>1?`since :
|
|
@@ -1940,7 +1940,7 @@ ${A}${q}${D}${wTp.default.cursorHide}`});var Q_a=li(ici(),1);function Y5s(e,t){i
|
|
|
1940
1940
|
Run ${Ws.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
|
|
1941
1941
|
Run ${Ws.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),pPn(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function u9s({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!JTp(e))return;let n=t??"",a=e.filter(l=>l.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let u=a.sort((l,f)=>l.generatorName.localeCompare(f.generatorName)||l.currentVersion.localeCompare(f.currentVersion));for(let l of u)n+=`
|
|
1942
1942
|
${await a_D(l.generatorName)} (${l.apiName!=null?"API: "+l.apiName+", ":""}Group: ${l.generatorGroup}) `+Ws.dim(l.currentVersion)+Ws.reset(" \u2192 ")+Ws.green(l.latestVersion);return n+=`
|
|
1943
|
-
`,i?pPn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function a_D(e){let r=await new QTp.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 o_D({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await YTp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(f,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=rci(o.name,c),g=await lJt({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 YTp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(l,f,s,o)=>{if(l==null)return;u.versions[l]==null&&(u.versions[l]={}),u.versions[l][f]==null&&(u.versions[l][f]={});let c=rci(s.name,o),b=await lJt({generatorName:c,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:o});b!=null&&(u.versions[l][f][s.name]={previousVersion:s.version,latestVersion:b})},generatorFilter:r,groupFilter:i}),u}async function YTp({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 Q8t({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(l==null||l.groups==null)){for(let f of l.groups)if(!(n!=null&&f.groupName!==n))for(let s of f.generators)i!=null&&s.name!==i||await r(a.workspaceName,f.groupName,s,u)}})}))}function XTp(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 f=Zie(l.latestVersion,l.previousVersion);r.debug(`Latest version: ${l.latestVersion}. `+(f?"Upgrade available.":"No upgrade available.")),i.push({generatorName:u,generatorGroup:n,apiName:t,isUpgradeAvailable:f,currentVersion:l.previousVersion,latestVersion:l.latestVersion})}return i}async function yAo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await o_D({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(l.type==="multiApi")for(let[f,s]of Object.entries(l.versions))u.push(...XTp(s,f,t.logger));else u.push(...XTp(l.versions,void 0,t.logger))}return u}var tha=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 G1n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var Q1n=e=>e!==null&&typeof e=="object";var rha=(...e)=>{for(let t of e)if((!Q1n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return l9s({},...e)},s9s=(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 vAo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:l9s(e[r]??[],t[r]??[])}var c9s=(e={},t={})=>({beforeRequest:vAo(e,t,"beforeRequest"),beforeRetry:vAo(e,t,"beforeRetry"),afterResponse:vAo(e,t,"afterResponse"),beforeError:vAo(e,t,"beforeError")}),l9s=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(Q1n(n)){for(let[a,u]of Object.entries(n))Q1n(u)&&a in t&&(u=l9s(t[a],u)),t={...t,[a]:u};Q1n(n.hooks)&&(i=c9s(i,n.hooks),t.hooks=i),Q1n(n.headers)&&(r=s9s(r,n.headers),t.headers=r)}return t};var ZTp=(()=>{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})(),kTp=typeof globalThis.AbortController=="function",eCp=typeof globalThis.ReadableStream=="function",tCp=typeof globalThis.FormData=="function",bAo=["get","post","put","patch","head","delete"],u_D=()=>{};u_D();var rCp={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},gAo=2147483647,OAo=Symbol("stop"),iCp={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},nCp={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 oCp=e=>bAo.includes(e)?e.toUpperCase():e,s_D=["get","put","head","delete","options","trace"],c_D=[408,413,429,500,502,503,504],l_D=[413,429,503],aCp={limit:2,methods:s_D,statusCodes:c_D,afterStatusCodes:l_D,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},uCp=(e={})=>{if(typeof e=="number")return{...aCp,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{...aCp,...e}};async function f9s(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new G1n(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function d9s(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 sCp=(e,t)=>{let r={};for(let i in t)!(i in nCp)&&!(i in iCp)&&!(i in e)&&(r[i]=t[i]);return r};var iha=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>gAo)throw new RangeError(`The \`timeout\` option cannot be greater than ${gAo}`);await Promise.resolve();let l=await i._fetch();for(let f of i._options.hooks.afterResponse){let s=await f(i.request,i._options,i._decorateResponse(l.clone()));s instanceof globalThis.Response&&(l=s)}if(i._decorateResponse(l),!l.ok&&i._options.throwHttpErrors){let f=new tha(l,i.request,i._options);for(let s of i._options.hooks.beforeError)f=await s(f);throw f}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!eCp)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,f]of Object.entries(rCp))u[l]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||f);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:s9s(this._input.headers,r.headers),hooks:c9s({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:oCp(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:uCp(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(kTp){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(ZTp&&(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);(tCp&&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 G1n)throw t;if(t instanceof tha){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),gAo);if(this._retryCount<1)throw r;await d9s(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})===OAo)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=sCp(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):f9s(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:f,value:s}=await u.read();if(f){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 p9s=e=>{let t=(r,i)=>iha.create(r,rha(e,i));for(let r of bAo)t[r]=(i,n)=>iha.create(i,rha(e,n,{method:r}));return t.create=r=>p9s(rha(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),p9s(rha(e,r))),t.stop=OAo,t},f_D=p9s(),cCp=f_D;var CCp=li(TCp(),1);function b9s(e){let t=(0,CCp.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var DBp=li(SBp(),1),EBp=li(ici(),1),C9s=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},B9s=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function x9s(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??b9s(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,DBp.default)(a.toString(),{recursive:!0}),f={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete f.accept,l&&(f.authorization=`${l.type} ${l.token}`);let s;try{s=await cCp(u,{headers:f,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new C9s(e):c}if(t.allVersions)return s;let o=new B9s(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=EBp.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 cha(e,t){let{version:r}=await x9s(e.toLowerCase(),t);return r}async function Gdi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:cha(e.packageName,{version:t?"prerelease":"latest"})}var MBp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],CAo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=G0.Info;isLocal;constructor(t,{isLocal:r}){this.ttyAwareLogger=new hAo(t),this.isLocal=r??!1;let i=this.getPackageName(),n=this.getPackageVersion(),a=this.getCliName();(i==null||n==null||a==null)&&this.exitProgram(),this.environment={packageName:i,packageVersion:n,cliName:a}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.60.19"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Ws.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new yre}failWithoutThrowing(t,r){this.didSucceed=!1,fAo({message:t,error:r,logger:this.logger})}async exit(){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await nPn()).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 KTp({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
1943
|
+
`,i?pPn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function a_D(e){let r=await new QTp.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 o_D({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await YTp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(f,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=rci(o.name,c),g=await lJt({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 YTp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(l,f,s,o)=>{if(l==null)return;u.versions[l]==null&&(u.versions[l]={}),u.versions[l][f]==null&&(u.versions[l][f]={});let c=rci(s.name,o),b=await lJt({generatorName:c,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:o});b!=null&&(u.versions[l][f][s.name]={previousVersion:s.version,latestVersion:b})},generatorFilter:r,groupFilter:i}),u}async function YTp({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 Q8t({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(l==null||l.groups==null)){for(let f of l.groups)if(!(n!=null&&f.groupName!==n))for(let s of f.generators)i!=null&&s.name!==i||await r(a.workspaceName,f.groupName,s,u)}})}))}function XTp(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 f=Zie(l.latestVersion,l.previousVersion);r.debug(`Latest version: ${l.latestVersion}. `+(f?"Upgrade available.":"No upgrade available.")),i.push({generatorName:u,generatorGroup:n,apiName:t,isUpgradeAvailable:f,currentVersion:l.previousVersion,latestVersion:l.latestVersion})}return i}async function yAo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await o_D({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(l.type==="multiApi")for(let[f,s]of Object.entries(l.versions))u.push(...XTp(s,f,t.logger));else u.push(...XTp(l.versions,void 0,t.logger))}return u}var tha=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 G1n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var Q1n=e=>e!==null&&typeof e=="object";var rha=(...e)=>{for(let t of e)if((!Q1n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return l9s({},...e)},s9s=(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 vAo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:l9s(e[r]??[],t[r]??[])}var c9s=(e={},t={})=>({beforeRequest:vAo(e,t,"beforeRequest"),beforeRetry:vAo(e,t,"beforeRetry"),afterResponse:vAo(e,t,"afterResponse"),beforeError:vAo(e,t,"beforeError")}),l9s=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(Q1n(n)){for(let[a,u]of Object.entries(n))Q1n(u)&&a in t&&(u=l9s(t[a],u)),t={...t,[a]:u};Q1n(n.hooks)&&(i=c9s(i,n.hooks),t.hooks=i),Q1n(n.headers)&&(r=s9s(r,n.headers),t.headers=r)}return t};var ZTp=(()=>{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})(),kTp=typeof globalThis.AbortController=="function",eCp=typeof globalThis.ReadableStream=="function",tCp=typeof globalThis.FormData=="function",bAo=["get","post","put","patch","head","delete"],u_D=()=>{};u_D();var rCp={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},gAo=2147483647,OAo=Symbol("stop"),iCp={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},nCp={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 oCp=e=>bAo.includes(e)?e.toUpperCase():e,s_D=["get","put","head","delete","options","trace"],c_D=[408,413,429,500,502,503,504],l_D=[413,429,503],aCp={limit:2,methods:s_D,statusCodes:c_D,afterStatusCodes:l_D,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},uCp=(e={})=>{if(typeof e=="number")return{...aCp,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{...aCp,...e}};async function f9s(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new G1n(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function d9s(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 sCp=(e,t)=>{let r={};for(let i in t)!(i in nCp)&&!(i in iCp)&&!(i in e)&&(r[i]=t[i]);return r};var iha=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>gAo)throw new RangeError(`The \`timeout\` option cannot be greater than ${gAo}`);await Promise.resolve();let l=await i._fetch();for(let f of i._options.hooks.afterResponse){let s=await f(i.request,i._options,i._decorateResponse(l.clone()));s instanceof globalThis.Response&&(l=s)}if(i._decorateResponse(l),!l.ok&&i._options.throwHttpErrors){let f=new tha(l,i.request,i._options);for(let s of i._options.hooks.beforeError)f=await s(f);throw f}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!eCp)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,f]of Object.entries(rCp))u[l]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||f);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:s9s(this._input.headers,r.headers),hooks:c9s({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:oCp(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:uCp(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(kTp){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(ZTp&&(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);(tCp&&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 G1n)throw t;if(t instanceof tha){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),gAo);if(this._retryCount<1)throw r;await d9s(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})===OAo)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=sCp(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):f9s(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:f,value:s}=await u.read();if(f){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 p9s=e=>{let t=(r,i)=>iha.create(r,rha(e,i));for(let r of bAo)t[r]=(i,n)=>iha.create(i,rha(e,n,{method:r}));return t.create=r=>p9s(rha(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),p9s(rha(e,r))),t.stop=OAo,t},f_D=p9s(),cCp=f_D;var CCp=li(TCp(),1);function b9s(e){let t=(0,CCp.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var DBp=li(SBp(),1),EBp=li(ici(),1),C9s=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},B9s=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function x9s(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??b9s(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,DBp.default)(a.toString(),{recursive:!0}),f={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete f.accept,l&&(f.authorization=`${l.type} ${l.token}`);let s;try{s=await cCp(u,{headers:f,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new C9s(e):c}if(t.allVersions)return s;let o=new B9s(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=EBp.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 cha(e,t){let{version:r}=await x9s(e.toLowerCase(),t);return r}async function Gdi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:cha(e.packageName,{version:t?"prerelease":"latest"})}var MBp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],CAo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=G0.Info;isLocal;constructor(t,{isLocal:r}){this.ttyAwareLogger=new hAo(t),this.isLocal=r??!1;let i=this.getPackageName(),n=this.getPackageVersion(),a=this.getCliName();(i==null||n==null||a==null)&&this.exitProgram(),this.environment={packageName:i,packageVersion:n,cliName:a}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.60.21"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Ws.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new yre}failWithoutThrowing(t,r){this.didSucceed=!1,fAo({message:t,error:r,logger:this.logger})}async exit(){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await nPn()).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 KTp({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
1944
1944
|
`)||(r+=`
|
|
1945
1945
|
`),this.logger.info(r))}catch{}}async exitIfFailed(){this.didSucceed||await this.exit()}exitProgram(){process.exit(this.didSucceed?0:1)}longestWorkspaceName;registerWorkspaces(t){let r=c_s(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 J_a(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 yre}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await nPn()).sendEvent(t)}logger=EQr(this.log.bind(this));constructTaskInitForWorkspace(t){let r=ABp(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?ABp(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=MBp[this.numTasks++%MBp.length],u=Ws.hex(a)(n);return{...this.constructTaskInit(),logPrefix:u}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===IC.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=>gsi.indexOf(i.level)>=gsi.indexOf(this.logLevel));this.ttyAwareLogger.log(r,{includeDebugInfo:this.logLevel===G0.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 Gdi({cliEnvironment:this.environment,includePreReleases:t}),i=Zie(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await yAo({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){return await H5s({message:t,default:r})}async getInput(t){return await $5s({message:t.message,default:t.default})}};function ABp(e){return`[${e}]:`}var lQp=require("fs/promises");function kie({breadcrumbs:e=[],title:t,subtitle:r}){let i=[];return e.length>0&&i.push(Ws.blue(e.join(" -> "))),i.push(t),r!=null&&i.push(Ws.dim(r)),i.join(`
|
|
1946
1946
|
`)}var aUp=require("fs/promises");var r9t=class{generatorsConfiguration;workspaceName;cliVersion;absoluteFilePath;changelog;constructor({generatorsConfiguration:t,workspaceName:r,cliVersion:i,absoluteFilePath:n,changelog:a}){this.generatorsConfiguration=t,this.workspaceName=r,this.cliVersion=i,this.absoluteFilePath=n,this.changelog=a}};var mDe=class extends r9t{definition;sources;type="fern";constructor({definition:t,sources:r,...i}){super(i),this.definition=t,this.sources=r??[]}async getDefinition(){return this.definition}async toFernWorkspace(){return this}getSources(){return this.sources}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};var lha=class{context;constructor(t){this.context=t}};var BAo=class e{files={};directories={};getAllFiles(){let t={},r=(i,n)=>{for(let[u,l]of Object.entries(i.files)){let f=n!=null?Xh.of(`${n}${l8t}${u}`):Xh.of(u);t[f]=l}let a=Object.keys(i.directories).sort();for(let u of a){let l=n!=null?`${n}${l8t}${u}`:u,f=i.directories[u];r(f,l)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split(l8t))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[Xh.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 gNi=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new BAo,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 XQr(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"]))qBp(i)&&t.push(i.header);let r=this.getVersionHeader();return r!=null&&t.push(r),new Set(t)}getAuthHeaderName(){if(this.rootApiFile["auth-schemes"]!=null){for(let t of Object.values(this.rootApiFile["auth-schemes"]))if(qBp(t))return t.header;return"Authorization"}}addGlobalHeader({name:t,schema:r}){let i=this.getVersionHeader();i!=null&&i===t||(this.rootApiFile.headers==null&&(this.rootApiFile.headers={}),this.rootApiFile.headers[t]=r)}addIdempotencyHeader({name:t,schema:r}){this.rootApiFile["idempotency-headers"]==null&&(this.rootApiFile["idempotency-headers"]={}),this.rootApiFile["idempotency-headers"][t]=r}addVariable({name:t,schema:r}){this.rootApiFile.variables==null&&(this.rootApiFile.variables={}),this.rootApiFile.variables[t]=r}addImport({file:t,fileToImport:r,alias:i}){if(t===r)return;let n=i??$y((cxe(r)+"/"+sBi(r,{stripExtension:!0})).replaceAll("__package__","root"));if(t===Xh.of(XN))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[n]=Dto(cxe(yvn.of(`/${t}`)),yvn.of(`/${r}`)),n;let a=this.getOrCreateFile(t);return a.imports==null&&(a.imports={}),a.imports[n]=Dto(cxe(yvn.of(`/${t}`)),yvn.of(`/${r}`)),n}addType(t,{name:r,schema:i}){if(t===Xh.of(XN))return;let n=this.getOrCreateFile(t);n.types==null&&(n.types={}),n.types[r]=i}addTypeExample(t,r,i){let n=this.getOrCreateFile(t);n.types==null&&(n.types={});let a=n.types[r];a!=null&&(typeof a=="string"?n.types[r]={type:a,examples:[i]}:(a.examples==null&&(a.examples=[]),a.examples.push(i)))}addError(t,{name:r,schema:i}){let n=this.getOrCreateFile(t);n.errors==null&&(n.errors={}),n.errors[r]==null?n.errors[r]=i:n.errors[r]?.type!==i.type&&(n.errors[r]={"status-code":i["status-code"],type:"unknown"})}addErrorExample(t,{name:r,example:i}){let n=this.getOrCreateFile(t);if(n.errors==null)return;let a=n.errors[r];if(a==null)return;a.examples==null&&(a.examples=[]),(a.examples.some(l=>hSe(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=NR(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:NR(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:NR(r,u.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===nS?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 qBp(e){return e?.header!=null}var ene={openapi:e=>({...e,type:"openapi",_visit:function(t){return ene._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return ene._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 eSn={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return eSn._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var W5={basic:e=>({...e,type:"basic",_visit:function(t){return W5._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return W5._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return W5._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return W5._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return W5._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 Yg={primitive:e=>({value:e,type:"primitive",_visit:function(t){return Yg._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Yg._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return Yg._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return Yg._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return Yg._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return Yg._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Yg._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return Yg._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 c_={int:e=>({value:e,type:"int",_visit:function(t){return c_._visit(this,t)}}),int64:e=>({value:e,type:"int64",_visit:function(t){return c_._visit(this,t)}}),uint:e=>({value:e,type:"uint",_visit:function(t){return c_._visit(this,t)}}),uint64:e=>({value:e,type:"uint64",_visit:function(t){return c_._visit(this,t)}}),float:e=>({value:e,type:"float",_visit:function(t){return c_._visit(this,t)}}),double:e=>({value:e,type:"double",_visit:function(t){return c_._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return c_._visit(this,t)}}),datetime:e=>({value:e,type:"datetime",_visit:function(t){return c_._visit(this,t)}}),date:e=>({value:e,type:"date",_visit:function(t){return c_._visit(this,t)}}),base64:e=>({value:e,type:"base64",_visit:function(t){return c_._visit(this,t)}}),boolean:e=>({value:e,type:"boolean",_visit:function(t){return c_._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 tSn={boolean:e=>({value:e,type:"boolean",_visit:function(t){return tSn._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return tSn._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"boolean":return t.boolean(e.value);case"string":return t.string(e.value);default:return t._other(e)}}};var Qdi={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return Qdi._visit(this,t)}}),undiscriminated:e=>({value:e,type:"undiscriminated",_visit:function(t){return Qdi._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 CV={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated",_visit:(e,t)=>{switch(e){case CV.GenerallyAvailable:return t.generallyAvailable();case CV.Beta:return t.beta();case CV.Deprecated:return t.deprecated();default:return t._other()}}};var $ze={cursor:e=>({...e,type:"cursor",_visit:function(t){return $ze._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return $ze._visit(this,t)}}),custom:e=>({...e,type:"custom",_visit:function(t){return $ze._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 xKr={language:e=>({...e,type:"language",_visit:function(t){return xKr._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return xKr._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 BV={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 BV.Curl:return t.curl();case BV.Python:return t.python();case BV.Javascript:return t.javascript();case BV.Typescript:return t.typescript();case BV.Go:return t.go();case BV.Ruby:return t.ruby();case BV.Csharp:return t.csharp();case BV.Java:return t.java();case BV.Js:return t.js();case BV.Node:return t.node();case BV.Ts:return t.ts();case BV.Nodets:return t.nodets();case BV.Golang:return t.golang();case BV.Dotnet:return t.dotnet();case BV.Jvm:return t.jvm();default:return t._other()}}};var i9t={unknown:e=>({value:e,type:"unknown",_visit:function(t){return i9t._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return i9t._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 n9t={withStreaming:e=>({...e,type:"withStreaming",_visit:function(t){return n9t._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit:function(t){return n9t._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 zG={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE",_visit:(e,t)=>{switch(e){case zG.Get:return t.get();case zG.Post:return t.post();case zG.Put:return t.put();case zG.Patch:return t.patch();case zG.Delete:return t.delete();case zG.Head:return t.head();case zG.Options:return t.options();case zG.Trace:return t.trace();default:return t._other()}}};var Jdi={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return Jdi._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return Jdi._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return Jdi._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 IKr={file:e=>({...e,type:"file",_visit:function(t){return IKr._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return IKr._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 RG={file:e=>({...e,type:"file",_visit:function(t){return RG._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return RG._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return RG._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return RG._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return RG._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return RG._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return RG._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var my={primitive:e=>({...e,type:"primitive",_visit:function(t){return my._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return my._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return my._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return my._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return my._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return my._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return my._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return my._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return my._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return my._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return my._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 wj={int:e=>({...e,type:"int",_visit:function(t){return wj._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return wj._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return wj._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return wj._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return wj._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return wj._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return wj._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return wj._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return wj._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return wj._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return wj._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 Dx={boolean:e=>({value:e,type:"boolean",_visit:function(t){return Dx._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return Dx._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 zKr={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return zKr._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return zKr._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 PDe={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return PDe._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return PDe._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return PDe._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 DT={file:e=>({...e,type:"file",_visit:function(t){return DT._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return DT._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return DT._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return DT._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return DT._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return DT._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return DT._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var Cl={primitive:e=>({...e,type:"primitive",_visit:function(t){return Cl._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Cl._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Cl._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Cl._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Cl._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Cl._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Cl._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Cl._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Cl._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Cl._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Cl._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 gX={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return gX._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return gX._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undiscriminated":return t.undiscriminated(e);default:return t._other(e)}}};var up={int:e=>({...e,type:"int",_visit:function(t){return up._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return up._visit(this,t)}}),uint:e=>({...e,type:"uint",_visit:function(t){return up._visit(this,t)}}),uint64:e=>({...e,type:"uint64",_visit:function(t){return up._visit(this,t)}}),float:e=>({...e,type:"float",_visit:function(t){return up._visit(this,t)}}),double:e=>({...e,type:"double",_visit:function(t){return up._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return up._visit(this,t)}}),datetime:e=>({...e,type:"datetime",_visit:function(t){return up._visit(this,t)}}),date:e=>({...e,type:"date",_visit:function(t){return up._visit(this,t)}}),base64:e=>({...e,type:"base64",_visit:function(t){return up._visit(this,t)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return up._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e);case"int64":return t.int64(e);case"uint":return t.uint(e);case"uint64":return t.uint64(e);case"float":return t.float(e);case"double":return t.double(e);case"string":return t.string(e);case"datetime":return t.datetime(e);case"date":return t.date(e);case"base64":return t.base64(e);case"boolean":return t.boolean(e);default:return t._other(e)}}};var lv={};jo(lv,{AllOfPropertyConflict:()=>wSn,ArraySchema:()=>Kqo,ArraySchemaWithExample:()=>jTo,Availability:()=>WAo,Base64WithExample:()=>bTo,BasicSecurityScheme:()=>GAo,BearerSecurityScheme:()=>QAo,BooleanSchema:()=>Wqo,BooleanWithExample:()=>gTo,BytesResponse:()=>hSn,CasingOverrides:()=>YAo,CommonProperty:()=>iTo,CommonPropertyWithExample:()=>CTo,CursorPagination:()=>Dqo,CustomCodeSample:()=>wqo,CustomCodeSampleLanguage:()=>mqo,CustomCodeSampleSdk:()=>jqo,CustomPagination:()=>Mqo,DateWithExample:()=>vTo,DatetimeWithExample:()=>yTo,DiscriminatedOneOfSchema:()=>tTo,DiscriminatedOneOfSchemaWithExample:()=>qTo,DoubleSchema:()=>Uqo,DoubleWithExample:()=>_To,Encoding:()=>VAo,Endpoint:()=>Aqo,EndpointExample:()=>gSn,EndpointResponseExample:()=>Oqo,EndpointSdkName:()=>UXt,EndpointWithExample:()=>oxp,EnumSchema:()=>aSn,EnumSchemaWithExample:()=>mTo,EnumValue:()=>Xdi,ErrorExample:()=>hqo,FernExample:()=>vqo,FileResponse:()=>pSn,FileSchema:()=>sqo,FloatWithExample:()=>pTo,FullEndpointExample:()=>Sqo,FullExample:()=>iq,FullObjectExample:()=>iqo,FullOneOfExample:()=>aqo,GlobalHeader:()=>$qo,Header:()=>kdi,HeaderExample:()=>bSn,HeaderSecurityScheme:()=>JAo,HeaderWithExample:()=>rpi,HttpEndpointServer:()=>ySn,HttpError:()=>yqo,HttpErrorWithExample:()=>sTo,HttpMethod:()=>sSn,IdempotencyHeader:()=>Gqo,Int64WithExample:()=>lTo,IntSchema:()=>Fqo,IntWithExample:()=>cTo,JsonRequest:()=>dqo,JsonRequestWithExample:()=>aTo,JsonResponse:()=>_Sn,JsonResponseWithExample:()=>ESn,KeyValuePair:()=>nqo,LiteralExample:()=>rqo,LiteralSchema:()=>jSn,LiteralSchemaValue:()=>Qqo,LongSchema:()=>Lqo,MapSchema:()=>Yqo,MapSchemaWithExample:()=>wTo,MultipartRequest:()=>dSn,MultipartRequestProperty:()=>fqo,MultipartRequestPropertyEncoding:()=>lqo,MultipartSchema:()=>cqo,NamedFullExample:()=>WXt,Namespace:()=>XAo,NamespaceId:()=>tqo,NullableSchema:()=>Zqo,NullableSchemaWithExample:()=>DTo,OauthSecurityScheme:()=>kAo,ObjectProperty:()=>eTo,ObjectPropertyConflictInfo:()=>SSn,ObjectPropertyWithExample:()=>ATo,ObjectSchema:()=>Jqo,ObjectSchemaWithExample:()=>ETo,OctetStreamRequest:()=>fSn,OffsetPagination:()=>Eqo,OneOfSchema:()=>kqo,OneOfSchemaWithExample:()=>MTo,OpenApiIntermediateRepresentation:()=>nxp,OpenApiSource:()=>NAo,OptionalSchema:()=>Xqo,OptionalSchemaWithExample:()=>STo,Pagination:()=>OSn,PathParameter:()=>cSn,PathParameterExample:()=>bqo,PathParameterWithExample:()=>nTo,PrimitiveExample:()=>uSn,PrimitiveSchema:()=>tpi,PrimitiveSchemaValue:()=>Hqo,PrimitiveSchemaValueWithExample:()=>OTo,PrimitiveSchemaWithExample:()=>MSn,PropertyKey:()=>oSn,ProtobufEncoding:()=>UAo,ProtobufSource:()=>FAo,QueryParameter:()=>lSn,QueryParameterExample:()=>vSn,QueryParameterWithExample:()=>DSn,QuerySecurityScheme:()=>KAo,ReferencedSchema:()=>VXt,Request:()=>pqo,RequestWithExample:()=>oTo,Response:()=>_qo,ResponseWithExample:()=>uTo,Schema:()=>ZO,SchemaId:()=>OX,SchemaWithExample:()=>xM,Schemas:()=>Nqo,SdkGroup:()=>ZAo,SdkGroupInfo:()=>oqo,SdkGroupName:()=>Zdi,SecurityScheme:()=>eqo,SecuritySchemeId:()=>$Ao,Server:()=>_ha,Source:()=>LAo,StatusCode:()=>LXt,StreamingResponseExample:()=>gqo,StringSchema:()=>Vqo,StringSchemaWithExample:()=>hTo,SupportedSdkLanguage:()=>Pqo,Tag:()=>HAo,TagId:()=>mX,Tags:()=>uqo,TextResponse:()=>epi,Uint64WithExample:()=>dTo,UintWithExample:()=>fTo,UnDiscriminatedOneOfSchema:()=>rTo,UnDiscriminatedOneOfSchemaWithExample:()=>TTo,UnknownSchemaWithExample:()=>PTo,Webhook:()=>qqo,WebhookExampleCall:()=>PSn,WebhookHttpMethod:()=>mSn,WebhookWithExample:()=>uxp,WebsocketChannel:()=>Rqo,WebsocketHandshake:()=>Tqo,WebsocketHandshakeWithExample:()=>axp,WebsocketMessageExample:()=>Iqo,WebsocketMessageOrigin:()=>Cqo,WebsocketMessageSchema:()=>Bqo,WebsocketServer:()=>xqo,WebsocketSessionExample:()=>zqo,WithAvailability:()=>ph,WithDescription:()=>_f,WithEncoding:()=>tne,WithInline:()=>hE,WithName:()=>c0,WithNamespace:()=>Cb,WithSdkGroupName:()=>RO,WithSource:()=>qh,WithStatusCode:()=>Gze,WithTitle:()=>zO,commons:()=>F9s,example:()=>L9s,finalIr:()=>U9s,parseIr:()=>V9s});var F9s={};jo(F9s,{BasicSecurityScheme:()=>GAo,BearerSecurityScheme:()=>QAo,Encoding:()=>VAo,HeaderSecurityScheme:()=>JAo,Namespace:()=>XAo,NamespaceId:()=>tqo,OauthSecurityScheme:()=>kAo,OpenApiSource:()=>NAo,ProtobufEncoding:()=>UAo,ProtobufSource:()=>FAo,QuerySecurityScheme:()=>KAo,SchemaId:()=>OX,SdkGroup:()=>ZAo,SdkGroupName:()=>Zdi,SecurityScheme:()=>eqo,SecuritySchemeId:()=>$Ao,Server:()=>_ha,Source:()=>LAo,StatusCode:()=>LXt,Tag:()=>HAo,TagId:()=>mX,WithAvailability:()=>ph,WithDescription:()=>_f,WithEncoding:()=>tne,WithInline:()=>hE,WithName:()=>c0,WithNamespace:()=>Cb,WithSdkGroupName:()=>RO,WithSource:()=>qh,WithStatusCode:()=>Gze,WithTitle:()=>zO});var At={};jo(At,{JsonError:()=>rSn,ParseError:()=>iSn,any:()=>$Bp,bigint:()=>CBp,boolean:()=>GBp,booleanLiteral:()=>HBp,date:()=>BBp,discriminant:()=>txp,enum_:()=>IAo,getObjectLikeUtils:()=>a9t,getObjectUtils:()=>ONi,getSchemaUtils:()=>rq,isProperty:()=>Ydi,lazy:()=>xBp,lazyObject:()=>UBp,list:()=>RAo,number:()=>QBp,object:()=>zAo,objectWithoutOptionalProperties:()=>LBp,optional:()=>I9s,property:()=>zBp,record:()=>XBp,set:()=>ZBp,string:()=>JBp,stringLiteral:()=>WBp,transform:()=>z9s,undiscriminatedUnion:()=>exp,union:()=>ixp,unknown:()=>KBp,withParsedProperties:()=>N9s});var tj={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 BM(e,t){return`Expected ${t}. Received ${yhD(e)}.`}function yhD(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 H5(e){return{...e,json:TBp(e.json),parse:TBp(e.parse)}}function TBp(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(`
|
|
@@ -1954,7 +1954,7 @@ plugins:
|
|
|
1954
1954
|
- enum_type=string
|
|
1955
1955
|
- default_response=false
|
|
1956
1956
|
- source_root=${e}
|
|
1957
|
-
`}async function aRe({context:e,specs:t,relativePathToDependency:r}){let i=new Ezo({context:e}),n=t.filter(l=>l.type==="openapi").map(l=>({...l,relativePathToDependency:r})),a=t.filter(l=>l.type==="protobuf"),u=await Promise.all(a.map(async l=>$8D({generator:i,protobufSpec:l,relativePathToDependency:r})));return[...n,...u]}async function $8D({generator:e,protobufSpec:t,relativePathToDependency:r}){return{type:"openapi",absoluteFilepath:await e.generate({absoluteFilepathToProtobufRoot:t.absoluteFilepathToProtobufRoot,absoluteFilepathToProtobufTarget:t.absoluteFilepathToProtobufTarget,relativeFilepathToProtobufRoot:t.relativeFilepathToProtobufRoot,local:t.generateLocally}),absoluteFilepathToOverrides:t.absoluteFilepathToOverrides,settings:t.settings,source:{type:"protobuf",relativePathToDependency:r,root:t.absoluteFilepathToProtobufRoot,file:t.absoluteFilepathToProtobufTarget}}}var x$p=require("fs"),TEn=require("fs/promises");var I$p=require("os"),z$p=li(require("path"),1),R$p=require("stream/promises"),N$p=li(IRo(),1),F$p=li(hre(),1);var jKs=li(rIi(),1);var pP;(function(e){e.FILE_READ="FILE_READ",e.FILE_PARSE="FILE_PARSE",e.FILE_MISSING="FILE_MISSING",e.STRUCTURE_VALIDATION="STRUCTURE_VALIDATION",e.JSONSCHEMA_VALIDATION="JSONSCHEMA_VALIDATION",e.DEPENDENCY_NOT_LISTED="DEPENDENCY_NOT_LISTED",e.FAILED_TO_LOAD_DEPENDENCY="FAILED_TO_LOAD_DEPENDENCY",e.EXPORTING_PACKAGE_MARKER_OTHER_KEYS="EXPORTING_PACKAGE_MARKER_OTHER_KEYS",e.EXPORT_PACKAGE_HAS_DEFINITIONS="EXPORT_PACKAGE_HAS_DEFINITIONS",e.MISCONFIGURED_DIRECTORY="MISCONFIGURED_DIRECTORY"})(pP||(pP={}));var mLD=vJr();async function L$p({dependencyName:e,dependenciesConfiguration:t,context:r,rootApiFile:i,cliVersion:n,settings:a,loadAPIWorkspace:u}){let l,f={type:pP.FAILED_TO_LOAD_DEPENDENCY,dependencyName:e},s=t.dependencies[e];return s==null?f={type:pP.DEPENDENCY_NOT_LISTED,dependencyName:e}:await r.runInteractiveTask({name:`Download ${MLD(s)}`},async o=>{switch(s.type){case"version":l=await DLD({context:o,dependency:s,cliVersion:n,settings:a,loadAPIWorkspace:u});return;case"local":l=await SLD({context:o,dependency:s,cliVersion:n,settings:a,loadAPIWorkspace:u});return;default:Mo(s)}}),l!=null?{didSucceed:!0,definition:l}:{didSucceed:!1,failure:f}}var U$p="dependencies";var PLD="metadata.json",jLD=".fern";function wLD(e){return Lu(Hl.of((0,I$p.homedir)()),Xa.of(jLD),Xa.of(U$p),Xa.of(e.organization),Xa.of(e.apiName),Xa.of(e.version))}async function SLD({dependency:e,context:t,cliVersion:r,settings:i,loadAPIWorkspace:n}){if(n==null){t.failWithoutThrowing("Failed to load api definition");return}t.logger.info("Parsing...");let a=await n({absolutePathToWorkspace:e.absoluteFilepath,context:t,cliVersion:r,workspaceName:void 0});if(!a.didSucceed){t.failWithoutThrowing("Failed to load api definition",a.failures);return}t.logger.info("Modifying source filepath ...");let u=await a.workspace.getDefinition({context:t,relativePathToDependency:Xa.of(e.path)},i);return t.logger.info("Loaded..."),u}async function DLD({dependency:e,context:t,cliVersion:r,settings:i,loadAPIWorkspace:n}){let a=wLD(e),u=Lu(a,Xa.of(U$p)),l=Lu(a,Xa.of(PLD)),f;if(!await Cf(u)||!await Cf(l)){t.logger.info("Downloading manifest...");let c=await mLD.definitionRegistry.get(jKs.FernFiddle.OrganizationId(e.organization),jKs.FernFiddle.ApiId(e.apiName),e.version);if(!c.ok){c.error._visit({orgDoesNotExistError:()=>{t.failWithoutThrowing("Organization does not exist")},apiDoesNotExistError:()=>{t.failWithoutThrowing("API does not exist")},versionDoesNotExistError:()=>{t.failWithoutThrowing("Version does not exist")},_other:m=>{t.failWithoutThrowing("Failed to download API manifest",m)}});return}let b=c.body.yamlSchemaVersion!=null?parseInt(c.body.yamlSchemaVersion):void 0,g=lNi(r),O=lNi(c.body.cliVersion);if(b!=null){if(b>1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a higher version of fern. Upgrade this workspace to ${c.body.cliVersion}`);return}else if(b<1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a lower version of fern. Upgrade it to ${r}`);return}}else if(g.major!==O.major||g.minor!==O.minor){t.failWithoutThrowing(`CLI version is ${c.body.cliVersion}. Expected ${g.major}.${g.minor}.x (to match current workspace).`);return}t.logger.info("Downloading..."),t.logger.debug("Remote URL: "+c.body.definitionS3DownloadUrl),await(0,TEn.mkdir)(u,{recursive:!0});try{await ELD({s3PreSignedReadUrl:c.body.definitionS3DownloadUrl,absolutePathToLocalOutput:u})}catch(m){t.failWithoutThrowing("Failed to download API",m);return}f=c.body,await(0,TEn.writeFile)(l,JSON.stringify(f))}else f=JSON.parse((await(0,TEn.readFile)(l)).toString());if(t.logger.info("Parsing..."),n==null){t.failWithoutThrowing("Failed to load API");return}let s=await n({absolutePathToWorkspace:u,context:t,cliVersion:f.cliVersion,workspaceName:void 0});if(!s.didSucceed){t.failWithoutThrowing("Failed to parse dependency after downloading",s.failures);return}if(s.workspace.type==="oss"){t.failWithoutThrowing("Dependency must be a fern workspace.");return}return await s.workspace.getDefinition({context:t},i)}async function ELD({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}){let r=await YR.get(e,{responseType:"stream"}),i=await F$p.default.dir(),n=z$p.default.join(i.path,"api.tgz");await(0,R$p.pipeline)(r.data,(0,x$p.createWriteStream)(n)),await(0,N$p.extract)({file:n,cwd:t})}function MLD(e){switch(e.type){case"version":return`@${e.organization}/${e.apiName}`;case"local":return`${e.path}`;default:Mo(e)}}var eGp=li(Q$p(),1);function zRo(e,t){for(let[r,i]of KN(e))qLD({relativeFilepath:r,failure:i,logger:t})}function qLD({relativeFilepath:e,failure:t,logger:r}){switch(t.type){case pP.MISCONFIGURED_DIRECTORY:r.error("Misconfigured fern directory: please see the docs at https://buildwithfern.com/learn/api-definition/introduction/what-is-the-fern-folder");break;case pP.FILE_READ:r.error("Failed to open file: "+e);break;case pP.FILE_MISSING:r.error("Missing file: "+e);break;case pP.FILE_PARSE:t.error instanceof Waa?r.error(kie({title:`Failed to parse ${e}: ${t.error.reason}`,subtitle:t.error.mark.snippet})):r.error("Failed to parse file: "+e);break;case pP.STRUCTURE_VALIDATION:for(let i of t.error.issues)for(let{title:n,subtitle:a}of TLD(i))r.error(kie({title:n,subtitle:a,breadcrumbs:[e,...i.path]}));break;case pP.FAILED_TO_LOAD_DEPENDENCY:r.error("Failed to load dependency: "+t.dependencyName);break;case pP.DEPENDENCY_NOT_LISTED:r.error(`Dependency is not listed in ${CZa}: `+t.dependencyName);break;case pP.EXPORT_PACKAGE_HAS_DEFINITIONS:r.error("Exported package contains API definitions: "+t.pathToPackage);break;case pP.EXPORTING_PACKAGE_MARKER_OTHER_KEYS:r.error(`${t.pathOfPackageMarker} has an export so it cannot define other keys.`);break;case pP.JSONSCHEMA_VALIDATION:t.error.error!=null&&r.error(kie({title:t.error.error.message??"Unknown error",breadcrumbs:[e,...t.error.error.instancePath.split("/").filter(i=>i!=="")]}));for(let i of t.error.allErrors)i!==t.error.error&&r.debug(kie({title:i.message??"Unknown error",breadcrumbs:[e,...i.instancePath.split("/").filter(n=>n!=="")]}));break;default:Mo(t)}}function TLD(e){switch(e.code){case Wl.invalid_type:return[{title:"Incorrect type",subtitle:`Expected ${Ws.underline(e.expected)} but received ${Ws.underline(e.received)}`}];case Wl.unrecognized_keys:return e.keys.map(t=>({title:"Unexpected key",subtitle:`Encountered unexpected key ${Ws.underline(t)}`}));case Wl.invalid_enum_value:return[{title:"Unrecognized value",subtitle:`Allowed values: ${e.options.map(t=>Ws.underline(t)).join(", ")}`}];case Wl.invalid_union:case Wl.invalid_arguments:case Wl.invalid_return_type:case Wl.invalid_date:case Wl.invalid_string:case Wl.too_small:case Wl.too_big:case Wl.invalid_intersection_types:case Wl.not_multiple_of:case Wl.custom:default:return[{title:e.message}]}}var J$p=require("fs/promises");async function K$p(e,t){let r=[];for(let i of await pxe(e,t))r.push(await CLD({relativeFilepath:KA(e,i),absoluteFilepath:i}));return r}async function CLD({relativeFilepath:e,absoluteFilepath:t}){return{relativeFilepath:e,absoluteFilepath:t,fileContents:(await(0,J$p.readFile)(t)).toString()}}async function Y$p(e){let t={},r={};function i(n){try{t[n.relativeFilepath]={defaultUrl:void 0,contents:Gd.load(n.fileContents,{schema:Gd.CORE_SCHEMA}),rawContents:n.fileContents}}catch(a){r[n.relativeFilepath]={type:pP.FILE_PARSE,error:a}}}return await Promise.all(e.map(i)),Object.keys(r).length>0?{didSucceed:!1,failures:r}:{didSucceed:!0,files:t}}async function X$p({dependenciesConfiguration:e,structuralValidationResult:t,context:r,cliVersion:i,settings:n,loadAPIWorkspace:a}){let u={},l={},f={};return await Promise.all(KN(t.packageMarkers).map(async([s,o])=>{if(o.contents.export==null)u[s]=o;else{let{export:c,...b}=o.contents;if(MY(b)>0)f[s]={type:pP.EXPORTING_PACKAGE_MARKER_OTHER_KEYS,pathOfPackageMarker:s};else{let g=Zd(s);if(k4t(t.namedDefinitionFiles).some(m=>m!==s&&m.startsWith(g)))f[s]={type:pP.EXPORT_PACKAGE_HAS_DEFINITIONS,pathToPackage:g};else{let m=await L$p({dependencyName:typeof o.contents.export=="string"?o.contents.export:o.contents.export.dependency,dependenciesConfiguration:e,context:r,rootApiFile:t.rootApiFile.contents,cliVersion:i,settings:n,loadAPIWorkspace:a});m.didSucceed?l[Zd(s)]={definition:m.definition,url:typeof o.contents.export=="object"?o.contents.export.url:void 0}:f[s]=m.failure}}}})),MY(f)>0?{didSucceed:!1,failures:f}:{didSucceed:!0,packageMarkers:u,importedDefinitions:l}}var Z$p=li(require("path"),1);var DKs={};jo(DKs,{additionalProperties:()=>zLD,default:()=>NLD,definitions:()=>RLD,properties:()=>xLD,required:()=>ILD,type:()=>BLD});var BLD="object",xLD={docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"default-url":{oneOf:[{type:"string"},{type:"null"}]},"default-environment":{oneOf:[{type:"string"},{type:"null"}]},environments:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/environments.EnvironmentSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/auth.ApiAuthSchema"},{type:"null"}]},"auth-schemes":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/auth.AuthSchemeDeclarationSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},name:{type:"string"},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},"error-discrimination":{oneOf:[{$ref:"#/definitions/file.ErrorDiscriminationSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},errors:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"idempotency-headers":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},variables:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/variables.VariableDeclarationSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"null"}]},version:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},ILD=["name"],zLD=!1,RLD={"environments.SingleBaseUrlEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},url:{type:"string"}},required:["url"],additionalProperties:!1},"environments.MultipleBaseUrlsEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},urls:{type:"object",additionalProperties:{type:"string"}}},required:["urls"],additionalProperties:!1},"environments.EnvironmentSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/environments.SingleBaseUrlEnvironmentSchema"},{$ref:"#/definitions/environments.MultipleBaseUrlsEnvironmentSchema"}]},"auth.AuthSchemeReferenceSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{type:"string"}},required:["scheme"],additionalProperties:!1},"auth.AnyAuthItem":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"}]},"auth.AnyAuthSchemesSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},any:{type:"array",items:{$ref:"#/definitions/auth.AnyAuthItem"}}},required:["any"],additionalProperties:!1},"auth.ApiAuthSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"},{$ref:"#/definitions/auth.AnyAuthSchemesSchema"}]},"auth.OAuthAccessTokenRequestPropertiesSchema":{type:"object",properties:{"client-id":{oneOf:[{type:"string"},{type:"null"}]},"client-secret":{oneOf:[{type:"string"},{type:"null"}]},scopes:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthAccessTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthGetTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthRefreshTokenRequestPropertiesSchema":{type:"object",properties:{"refresh-token":{type:"string"}},required:["refresh-token"],additionalProperties:!1},"auth.OAuthRefreshTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthRefreshTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"oauth"},type:{const:"client-credentials"},scopes:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"client-id-env":{oneOf:[{type:"string"},{type:"null"}]},"client-secret-env":{oneOf:[{type:"string"},{type:"null"}]},"token-prefix":{oneOf:[{type:"string"},{type:"null"}]},"token-header":{oneOf:[{type:"string"},{type:"null"}]},"get-token":{$ref:"#/definitions/auth.OAuthGetTokenEndpointSchema"},"refresh-token":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenEndpointSchema"},{type:"null"}]}},required:["scheme","type","get-token"],additionalProperties:!1},"auth.HeaderAuthSchemeSchema":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},header:{type:"string"},type:{oneOf:[{type:"string"},{type:"null"}]},prefix:{oneOf:[{type:"string"},{type:"null"}]}},required:["header"],additionalProperties:!1},"auth.AuthVariable":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.BasicAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"basic"},username:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]},password:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.BearerAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"bearer"},token:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.AuthSchemeDeclarationSchema":{anyOf:[{$ref:"#/definitions/auth.OAuthSchemeSchema"},{$ref:"#/definitions/auth.HeaderAuthSchemeSchema"},{$ref:"#/definitions/auth.BasicAuthSchemeSchema"},{$ref:"#/definitions/auth.BearerAuthSchemeSchema"}]},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"file.PropertyBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"property"},"property-name":{type:"string"}},required:["strategy","property-name"],additionalProperties:!1},"file.StatusCodeBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"status-code"}},required:["strategy"],additionalProperties:!1},"file.ErrorDiscriminationSchema":{anyOf:[{$ref:"#/definitions/file.PropertyBasedErrorDiscrimination"},{$ref:"#/definitions/file.StatusCodeBasedErrorDiscrimination"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"variables.VariableDeclarationDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"variables.VariableDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/variables.VariableDeclarationDetailed"}]},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"versioning.VersionValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionValue":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionValueDetailed"}]},"versioning.VersionDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionDeclarationHeaderObjectSchema"}]},"versioning.VersionDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/versioning.VersionValue"}},header:{$ref:"#/definitions/versioning.VersionDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1}},NLD={type:BLD,properties:xLD,required:ILD,additionalProperties:zLD,definitions:RLD};var EKs={};jo(EKs,{additionalProperties:()=>ULD,default:()=>WLD,definitions:()=>VLD,properties:()=>LLD,type:()=>FLD});var FLD="object",LLD={docs:{oneOf:[{type:"string"},{type:"null"}]},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]}},ULD=!1,VLD={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{type:"boolean"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1}},WLD={type:FLD,properties:LLD,additionalProperties:ULD,definitions:VLD};var MKs={};jo(MKs,{additionalProperties:()=>GLD,default:()=>JLD,definitions:()=>QLD,properties:()=>$LD,type:()=>HLD});var HLD="object",$LD={imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},navigation:{oneOf:[{$ref:"#/definitions/file.Navigation"},{type:"null"}]},export:{oneOf:[{$ref:"#/definitions/file.Export"},{type:"null"}]}},GLD=!1,QLD={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{type:"boolean"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1},"file.Navigation":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"file.ExportDetailed":{type:"object",properties:{dependency:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]}},required:["dependency"],additionalProperties:!1},"file.Export":{anyOf:[{type:"string"},{$ref:"#/definitions/file.ExportDetailed"}]}},JLD={type:HLD,properties:$LD,additionalProperties:GLD,definitions:QLD};function k$p({files:e,absolutePathToDefinition:t}){let r,i={},n={},a={};for(let[u,l]of KN(e)){let f=l.contents,s=o=>{a[u]={type:pP.JSONSCHEMA_VALIDATION,error:o}};if(u===XN){let o=yQr(f,DKs);if(o.success){let c=cF.serialization.RootApiFileSchema.parseOrThrow(f);r={defaultUrl:c["default-url"],contents:c,rawContents:l.rawContents}}else s(o)}else if(Z$p.default.basename(u)===nS){let o=yQr(f,MKs);if(o.success){let c=cF.serialization.PackageMarkerFileSchema.parseOrThrow(f);n[u]={defaultUrl:typeof c.export=="object"?c.export.url:void 0,contents:c,rawContents:l.rawContents}}else s(o)}else{let o=yQr(f,EKs);if(o.success){let c=cF.serialization.DefinitionFileSchema.parseOrThrow(f);i[u]={defaultUrl:void 0,contents:c,rawContents:l.rawContents,absoluteFilePath:Lu(t,u)}}else s(o)}}return r==null?{didSucceed:!1,failures:{[Xa.of(XN)]:{type:pP.FILE_MISSING},...a}}:Object.keys(a).length>0?{didSucceed:!1,failures:a}:{didSucceed:!0,namedDefinitionFiles:i,rootApiFile:r,packageMarkers:n}}var yZt=class extends r9t{type="fern";context;fernWorkspaces={};loadAPIWorkspace;constructor({context:t,loadAPIWorkspace:r,...i}){super(i),this.context=t,this.loadAPIWorkspace=r}async getDefinition({context:t},r){return(await this.toFernWorkspace({context:t},r)).definition}async toFernWorkspace({context:t},r){let i=(0,eGp.default)(r??{}),n=this.fernWorkspaces[i];if(n==null){let a=t||this.context,u=Lu(this.absoluteFilePath,Xa.of(i5)),l=await Dbs({absolutePathToWorkspace:this.absoluteFilePath,context:a}),f=await K$p(u,"{yml,yaml}"),s=await Y$p(f);if(!s.didSucceed)return zRo(s.failures,a.logger),a.failAndThrow();let o=k$p({files:s.files,absolutePathToDefinition:u});if(!o.didSucceed)return zRo(o.failures,a.logger),a.failAndThrow();let c=await X$p({dependenciesConfiguration:l,structuralValidationResult:o,context:a,cliVersion:this.cliVersion,settings:r,loadAPIWorkspace:this.loadAPIWorkspace});if(!c.didSucceed)return zRo(c.failures,a.logger),a.failAndThrow();n=new mDe({absoluteFilePath:this.absoluteFilePath,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:l,workspaceName:this.workspaceName,definition:{absoluteFilePath:u,rootApiFile:o.rootApiFile,namedDefinitionFiles:o.namedDefinitionFiles,packageMarkers:c.packageMarkers,importedDefinitions:c.importedDefinitions},cliVersion:this.cliVersion,sources:[]}),this.fernWorkspaces[i]=n}return n}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};function k7(e){let t=YLD(e),{value:r,done:i}=AKs(t,"{");return i?{head:r,parts:[]}:{head:r,parts:[...KLD(t)]}}function*KLD(e){let t;do{let{value:r}=AKs(e,"}"),i=AKs(e,"{");t=i.done,yield{pathParameter:r,tail:i.value}}while(!t)}function*YLD(e){for(let t of e)yield t}function AKs(e,t){let r="",i=e.next();for(;i.done!==!0&&i.value!==t;)r+=i.value,i=e.next();return{value:r,done:i.done??!1}}function Yva(e){let t=2166136261;function r(n,a){if(typeof n=="object"&&n!=null){if(a>64){i("[MaxDepthExceeded]");return}if(Array.isArray(n)){i("[");for(let u=0;u<n.length;u++)u>0&&i(","),r(n[u],a+1);i("]")}else i("{"),Object.keys(n).sort().forEach((l,f)=>{f>0&&i(","),i(l),i(":"),r(n[l],a+1)}),i("}")}else i(String(n))}function i(n){for(let a=0;a<n.length;a++){let u=n.charCodeAt(a);t^=u,t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24),t>>>=0}}return r(e,0),t.toString(16)}function vZt({typeReference:e,typeDeclarations:t}){if(e.type==="container"&&e.container.type==="optional")return!0;if(e.type==="named"){let r=t?.[e.typeId];if(r?.shape.type==="alias"&&r?.shape.resolvedType.type==="container"&&r?.shape.resolvedType.container.type==="optional")return!0}return!1}function tGp({fieldName:e,containerType:t,maxDepth:r,currentDepth:i,typeDeclarations:n,skipOptionalProperties:a}){if(i>=r)return bZt({containerType:t});switch(t.type){case"list":{let u=aq({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?bZt({containerType:t}):{type:"success",example:YO.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:YO.literal({literal:t.literal._visit({boolean:u=>Td.boolean(u),string:u=>Td.string({original:u}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:t.literal._visit({boolean:u=>u,string:u=>u,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":{if(a)return bZt({containerType:t});let u=aq({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?bZt({containerType:t}):{type:"success",example:YO.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"nullable":{if(a)return bZt({containerType:t});let u=aq({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?bZt({containerType:t}):{type:"success",example:YO.nullable({nullable:u.example,valueType:t.nullable}),jsonExample:u.jsonExample}}case"set":{let u=aq({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?bZt({containerType:t}):{type:"success",example:YO.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=aq({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a}),l=aq({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"||l.type==="failure"?bZt({containerType:t}):{type:"success",example:YO.map({map:[{key:u.example,value:l.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:l.jsonExample}}}default:Mo(t)}}function bZt({containerType:e}){switch(e.type){case"list":return{type:"success",example:YO.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:YO.literal({literal:e.literal._visit({boolean:t=>Td.boolean(t),string:t=>Td.string({original:t}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:e.literal._visit({boolean:t=>t,string:t=>t,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":return{type:"success",example:YO.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:YO.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:YO.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:YO.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:Mo(e)}}function iGp({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return tUD({fieldName:e,default_:XLD(t.v2),validation:ZLD(t.v2)});case"BASE_64":return{type:"success",example:Td.base64(My.BASE64),jsonExample:My.BASE64};case"BOOLEAN":return{type:"success",example:Td.boolean(My.BOOLEAN),jsonExample:My.BOOLEAN};case"DATE":return{type:"success",example:Td.date(My.DATE),jsonExample:My.DATE};case"DATE_TIME":return{type:"success",example:Td.datetime({datetime:new Date(My.DATE_TIME),raw:My.DATE_TIME}),jsonExample:My.DATE_TIME};case"DOUBLE":return rUD({fieldName:e,validation:kLD(t.v2)});case"FLOAT":return{type:"success",example:Td.float(My.FLOAT),jsonExample:My.FLOAT};case"INTEGER":return iUD({fieldName:e,validation:eUD(t.v2)});case"UINT_64":return{type:"success",example:Td.uint64(My.INT64),jsonExample:My.INT64};case"UINT":return{type:"success",example:Td.uint(My.UINT),jsonExample:My.UINT};case"BIG_INTEGER":return{type:"success",example:Td.bigInteger(My.INT64.toString()),jsonExample:`${My.INT64}`};case"LONG":return{type:"success",example:Td.long(My.INT64),jsonExample:My.INT64};case"UUID":return{type:"success",example:Td.uuid(My.UUID),jsonExample:My.UUID};default:Mo(t.v1)}}function XLD(e){if(e?.type==="string")return e.default}function ZLD(e){if(e?.type==="string")return e.validation}function kLD(e){if(e?.type==="double")return e.validation}function eUD(e){if(e?.type==="integer")return e.validation}function rGp(e){if(e<=My.SAMPLE_STRINGS.length){let t=My.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return My.SAMPLE_STRINGS[My.SAMPLE_STRINGS.length-1]+".".repeat(e-My.SAMPLE_STRINGS.length)}function tUD({fieldName:e,default_:t,validation:r}){if(t!=null)return{type:"success",example:Td.string({original:t}),jsonExample:t};if(r){let n=r.minLength,a=r.maxLength;if(n){let u=rGp(n);return{type:"success",example:Td.string({original:u}),jsonExample:u}}else if(a){let u=rGp(a);return{type:"success",example:Td.string({original:u}),jsonExample:u}}}let i=e??My.STRING;return{type:"success",example:Td.string({original:i}),jsonExample:i}}function rUD({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Td.double(r),jsonExample:r};if(i)return{type:"success",example:Td.double(i),jsonExample:i}}return{type:"success",example:Td.double(My.DOUBLE),jsonExample:My.DOUBLE}}function iUD({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Td.integer(r),jsonExample:r};if(i)return{type:"success",example:Td.integer(i),jsonExample:i}}return{type:"success",example:Td.integer(My.INT),jsonExample:My.INT}}function xEn({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=aq({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:l,jsonExample:f}=u;return{type:"success",example:uw.alias({value:l}),jsonExample:f}}case"enum":{let u=r.shape.values[0];return u==null?{type:"failure",message:"No enum values present"}:{type:"success",example:uw.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u={},l=[];if(r.shape.extends!=null)for(let c of r.shape.extends){let b=t[c.typeId];if(b==null)continue;let g=xEn({fieldName:e,typeDeclaration:b,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});g!=null&&g.type==="success"&&g.example.type==="object"&&(Object.assign(u,g.jsonExample),l.push(...g.example.properties))}let f=nUD({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:n,maxDepth:i,skipOptionalProperties:a});if(f.type==="failure")return f;let{example:s,jsonExample:o}=f;return{type:"success",example:uw.object({...s,properties:[...l,...s.properties]}),jsonExample:Object.assign({},u,o)}}case"undiscriminatedUnion":{let u=0;for(let l of r.shape.members){let f=aq({fieldName:e,typeReference:l.type,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});if(f.type==="failure"){++u;continue}let{example:s,jsonExample:o}=f;return{type:"success",example:uw.undiscriminatedUnion({index:u,singleUnionType:s}),jsonExample:o}}break}case"union":{let u=r.shape.discriminant,l={};if(r.shape.baseProperties!=null)for(let f of r.shape.baseProperties){let s=aq({fieldName:f.name.wireValue,typeReference:f.valueType,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});s.type==="success"&&(l[f.name.wireValue]=s.jsonExample)}for(let f of r.shape.types){let s=f.shape._visit({noProperties:()=>({type:"success",example:uw.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:lF.noProperties()}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,...l}}),samePropertiesAsObject:o=>{let c=t[o.typeId];if(c==null)return{type:"failure",message:`Failed to find type declaration with id ${o.typeId}`};let b=xEn({currentDepth:n,maxDepth:i,fieldName:e,typeDeclaration:c,typeDeclarations:t,skipOptionalProperties:a});if(b==null)return{type:"failure",message:"Failed to generate example for type reference"};if(b.type==="failure")return b;let{example:g,jsonExample:O}=b;return{type:"success",example:uw.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:lF.samePropertiesAsObject({typeId:c.name.typeId,object:g.type==="object"?g:{properties:[]}})}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,...typeof O=="object"?O:{},...l}}},singleProperty:o=>{let c=aq({currentDepth:n+1,maxDepth:i,fieldName:e,typeReference:o.type,typeDeclarations:t,skipOptionalProperties:a});if(c.type==="failure")return c;let{example:b,jsonExample:g}=c;return{type:"success",example:uw.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:lF.singleProperty(b)}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,[o.name.wireValue]:g,...l}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(s.type!=="failure")return s}}}return{type:"failure",message:"Failed to generate example for type reference"}}function nUD({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:i,maxDepth:n,currentDepth:a,skipOptionalProperties:u}){let l={},f=[];for(let s of[...r.properties??[],...r.extendedProperties??[]]){let o=aq({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:i,currentDepth:a+1,maxDepth:n,skipOptionalProperties:u});if(o.type==="failure"&&!vZt({typeDeclarations:i,typeReference:s.valueType}))return{type:"failure",message:`Failed to generate required property ${s.name.wireValue} b/c ${o.message}`};if(o.type==="failure")continue;let{example:c,jsonExample:b}=o;f.push({name:s.name,originalTypeDeclaration:t.name,value:c}),l[s.name.wireValue]=b}return{type:"success",example:uw.object({properties:f}),jsonExample:l}}function aq({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){if(n>i)return{type:"failure",message:"Exceeded max depth"};switch(t.type){case"named":{let u=r[t.typeId];if(u==null)return{type:"failure",message:`Failed to find type declaration with id ${t.typeId}`};let l=xEn({fieldName:e,typeDeclaration:u,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(l==null)return{type:"failure",message:"Failed to generate example for type declaration"};if(l.type==="failure")return l;let{example:f,jsonExample:s}=l;return{type:"success",example:{jsonExample:s,shape:Ph.named({shape:f,typeName:u.name})},jsonExample:s}}case"container":{let u=tGp({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure"){let{example:s,jsonExample:o}=bZt({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:Ph.container(s)},jsonExample:o}}let{example:l,jsonExample:f}=u;return{type:"success",example:{jsonExample:f,shape:Ph.container(l)},jsonExample:f}}case"primitive":{let{jsonExample:u,example:l}=iGp({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:Ph.primitive(l)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:Ph.unknown(u)},jsonExample:u}}}}function wFi(e,t){let r=[];for(let i of e){let n=aq({fieldName:i.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,value:n.example})}return{type:"success",example:r,jsonExample:void 0}}function IEn(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&vZt({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=aq({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,value:n.example})}return{type:"success",example:r,jsonExample:void 0}}function RRo(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&vZt({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=aq({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??10,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,shape:i.allowMultiple?B2.exploded():B2.single(),value:n.example})}return{type:"success",example:r,jsonExample:void 0}}var qKs=Bf.primitive({v1:Zb.String,v2:wp.string({default:void 0,validation:void 0})});function Xva({ir:e,endpoint:t,service:r,typeDeclarations:i,skipOptionalRequestProperties:n,generationResponse:a}){let u={name:void 0,endpointHeaders:[],endpointPathParameters:[],queryParameters:[],servicePathParameters:[],serviceHeaders:[],rootPathParameters:[],request:void 0,response:Qq.ok(uC.body(void 0)),docs:void 0},l=wFi(t.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(l.type==="failure")return l;u.endpointPathParameters=l.example;let f=wFi(r.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(f.type==="failure")return f;u.servicePathParameters=f.example;let s=wFi(e.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(s.type==="failure")return s;u.rootPathParameters=s.example;let o=RRo(t.queryParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:10});if(o.type==="failure")return o;u.queryParameters=o.example;let c=IEn(t.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(c.type==="failure")return c;u.endpointHeaders=c.example;let b=IEn(r.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(b.type==="failure")return b;if(u.serviceHeaders=b.example,t.requestBody!=null)switch(t.requestBody.type){case"bytes":return{type:"failure",message:"Bytes request unsupported"};case"fileUpload":return{type:"failure",message:"File upload unsupported"};case"inlinedRequestBody":{let g={},O=[];if(t.requestBody.extends!=null)for(let m of t.requestBody.extends){let P=i[m.typeId];if(P==null)throw new Error(`Failed to find extended type declaration with id ${m.typeId}`);let E=xEn({typeDeclaration:P,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});E!=null&&E.type==="success"&&Object.assign(g,E.jsonExample)}for(let m of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let P=aq({fieldName:m.name.wireValue,typeReference:m.valueType,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});if(P.type==="failure"&&!vZt({typeDeclarations:i,typeReference:m.valueType}))return{type:"failure",message:`Failed to generate required property ${m.name.wireValue} b/c ${P.message}`};if(P.type==="failure")continue;let{example:E,jsonExample:q}=P;O.push({name:m.name,originalTypeDeclaration:void 0,value:E}),g[m.name.wireValue]=q}u.request=uG.inlinedRequestBody({jsonExample:g,properties:O});break}case"reference":{let g=aq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.request=uG.reference(O);break}default:Mo(t.requestBody)}if(a.type==="success"&&t.response?.body!=null)switch(t.response.body.type){case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":{let g=aq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=Qq.ok(uC.body({...O,jsonExample:m}));break}case"streamParameter":{let g;switch(t.response.body.nonStreamResponse.type){case"bytes":return{type:"failure",message:"Bytes unsupported"};case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":g=aq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":g=aq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:qKs,skipOptionalProperties:!1});break;default:Mo(t.response.body.nonStreamResponse)}if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=Qq.ok(uC.body({...O,jsonExample:m}));break}case"streaming":{let g;switch(t.response.body.value.type){case"sse":{if(g=aq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=Qq.ok(uC.sse([{data:{...O,jsonExample:m},event:""}]));break}case"json":{if(g=aq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=Qq.ok(uC.stream([{...O,jsonExample:m}]));break}case"text":{if(g=aq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:qKs,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=Qq.ok(uC.stream([{...O,jsonExample:m}]));break}default:Mo(t.response.body.value)}break}case"text":{let g=aq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:qKs,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=Qq.ok(uC.body({...O,jsonExample:m}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:Mo(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=Qq.error({body:void 0,error:a.declaration.name});else{let g=aq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:a.declaration.type,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.response=Qq.error({body:O,error:a.declaration.name})}try{return{type:"success",example:{id:Yva(u),url:aUD(t,u),...u},jsonExample:void 0}}catch(g){return{type:"failure",message:`Parse failure with exceptions ${g}`}}}function aUD(e,t){let r={};[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.fullPath.head+e.fullPath.parts.map(n=>r[n.pathParameter]+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function aGp({ir:e,channel:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let n={name:void 0,pathParameters:[],headers:[],queryParameters:[],messages:[],docs:void 0},a=wFi(t.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(a.type==="failure")return a;n.pathParameters.push(...a.example);let u=wFi(e.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(u.type==="failure")return u;n.pathParameters.push(...u.example);let l=RRo(t.queryParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:10});if(l.type==="failure")return l;n.queryParameters=l.example;let f=IEn(t.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(f.type==="failure")return f;n.headers.push(...f.example);let s=IEn(e.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(s.type==="failure")return s;n.headers.push(...s.example);let c=t.messages.filter(O=>O.origin==="client")[0];if(c!=null){let O=nGp({message:c,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:c.type,body:O})}let g=t.messages.filter(O=>O.origin==="server")[0];if(g!=null){let O=nGp({message:g,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:g.type,body:O})}return{type:"success",example:{...n,url:oUD(t,n)},jsonExample:void 0}}function nGp({message:e,typeDeclarations:t,skipOptionalRequestProperties:r}){if(e.body.type==="inlinedBody")return;let i=aq({currentDepth:0,maxDepth:10,typeDeclarations:t,typeReference:e.body.bodyType,skipOptionalProperties:r});if(i.type==="success")return WSe.reference(i.example)}function oUD(e,t){let r={};[...t.pathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.path.head+e.path.parts.map(n=>r[n.pathParameter]+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function gZt(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{},i=Object.values(t)[0],n=Object.values(r)[0];return{userExample:i,autoExample:n}}function oGp({service:e,endpoint:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let n={pathParameters:{},queryParameters:{},headers:{}};for(let a of t.pathParameters){let{userExample:u,autoExample:l}=gZt(a.v2Examples);u!==void 0?n.pathParameters[a.name.originalName]=u:l!==void 0&&(n.pathParameters[a.name.originalName]=l)}for(let a of t.queryParameters){let{userExample:u,autoExample:l}=gZt(a.v2Examples);if(u!==void 0)n.queryParameters[a.name.name.originalName]=u;else if(l!==void 0){if(i&&vZt({typeReference:a.valueType,typeDeclarations:r}))continue;n.queryParameters[a.name.name.originalName]=l}}for(let a of t.headers){let{userExample:u,autoExample:l}=gZt(a.v2Examples);if(u!==void 0)n.headers[a.name.name.originalName]=u;else if(l!==void 0){if(i&&vZt({typeReference:a.valueType,typeDeclarations:r}))continue;n.headers[a.name.name.originalName]=l}}return n}function uGp({endpoint:e,service:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let{pathParameters:n,queryParameters:a,headers:u}=oGp({service:t,endpoint:e,typeDeclarations:r,skipOptionalRequestProperties:i}),l={endpoint:{method:e.method,path:e.path.head},baseUrl:void 0,environment:e.baseUrl,auth:void 0,pathParameters:n,queryParameters:a,headers:u,requestBody:void 0,docs:void 0};if(e.requestBody!=null)switch(e.requestBody.type){case"bytes":break;case"fileUpload":{let{userExample:f,autoExample:s}=gZt(e.requestBody.v2Examples),o=f??s;l.requestBody=o;break}case"inlinedRequestBody":{let{userExample:f,autoExample:s}=gZt(e.requestBody.v2Examples),o=f??s;l.requestBody=o;break}case"reference":{let{userExample:f,autoExample:s}=gZt(e.requestBody.v2Examples),o=f??s;l.requestBody=o;break}default:Mo(e.requestBody)}return l}function cGp({endpoint:e,typeDeclarations:t,skipOptionalRequestProperties:r}){let i={statusCode:e.response?.statusCode,body:void 0,docs:void 0};if(e.response==null)return i;if(e.response.body==null)return e.source?.type==="openrpc"&&(i.body=N8t.json(sGp(null))),i;switch(e.response.body.type){case"bytes":break;case"fileDownload":break;case"text":break;case"json":{let n=e.response.body.value;if(n.type==="response"){let{userExample:a,autoExample:u}=gZt(n.v2Examples),l=a??u;if(l!==void 0){let f=e.source?.type==="openrpc"?sGp(l):l;i.body=N8t.json(f)}}break}case"streaming":break;case"streamParameter":break;default:Mo(e.response.body)}return i}function sGp(e,t=1){return{id:t,jsonrpc:"2.0",result:e}}function lGp({ir:e,endpoint:t,service:r,typeDeclarations:i,skipOptionalRequestProperties:n}){let a={request:void 0,response:void 0,codeSamples:void 0};return a.request=uGp({endpoint:t,service:r,typeDeclarations:i,skipOptionalRequestProperties:n}),a.response=cGp({endpoint:t,typeDeclarations:i,skipOptionalRequestProperties:n}),{name:`${t.name.originalName}_example`,example:a}}function bYr({ir:e,exampleGeneration:t}){for(let[r,i]of Object.entries(e.services))for(let n of i.endpoints){if(n.userSpecifiedExamples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let a=Xva({ir:e,service:i,endpoint:n,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples,generationResponse:{type:"success"}});if(a.type==="failure")continue;let{example:u}=a;n.autogeneratedExamples=[{example:u}]}for(let[r,i]of Object.entries(e.websocketChannels??{})){if(i.examples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let n=aGp({ir:e,channel:i,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});if(n.type==="failure")continue;let{example:a}=n;i.examples=[...i.examples,a]}return e}function SFi({ir:e,exampleGeneration:t}){for(let[r,i]of Object.entries(e.services))for(let n of i.endpoints){if(Object.keys(n.v2Examples?.userSpecifiedExamples??{}).length>0)continue;let a=lGp({ir:e,service:i,endpoint:n,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});n.v2Examples==null&&(n.v2Examples={userSpecifiedExamples:{},autogeneratedExamples:{}}),n.v2Examples.autogeneratedExamples={[a.name]:a.example}}return e}function NRo(e,t,r){let{environments:i,changedBaseUrlIds1:n,changedBaseUrlIds2:a}=uUD(e.environments,t.environments,r),{services:u,websocketChannels:l}=sUD(e,t,n,a);return{apiName:e.apiName,basePath:e.basePath,selfHosted:e.selfHosted&&t.selfHosted,apiDisplayName:e.apiDisplayName??t.apiDisplayName,apiDocs:e.apiDocs??t.apiDocs,auth:e.auth??t.auth,headers:[...e.headers??[],...t.headers??[]],environments:i,types:{...e.types??{},...t.types??{}},constants:{...e.constants??{},...t.constants??{}},errors:{...e.errors??{},...t.errors??{}},services:u,webhookGroups:{...e.webhookGroups??{},...t.webhookGroups??{}},subpackages:{...e.subpackages??{},...t.subpackages??{}},websocketChannels:l,rootPackage:{service:e.rootPackage.service??t.rootPackage.service,types:[...e.rootPackage.types??[],...t.rootPackage.types??[]],errors:[...e.rootPackage.errors??[],...t.rootPackage.errors??[]],subpackages:[...e.rootPackage.subpackages??[],...t.rootPackage.subpackages??[]],fernFilepath:e.rootPackage.fernFilepath??t.rootPackage.fernFilepath,webhooks:e.rootPackage.webhooks??t.rootPackage.webhooks,websocket:e.rootPackage.websocket??t.rootPackage.websocket,hasEndpointsInTree:e.rootPackage.hasEndpointsInTree||t.rootPackage.hasEndpointsInTree,navigationConfig:e.rootPackage.navigationConfig??t.rootPackage.navigationConfig,docs:e.rootPackage.docs??t.rootPackage.docs},fdrApiDefinitionId:e.fdrApiDefinitionId??t.fdrApiDefinitionId,apiVersion:e.apiVersion??t.apiVersion,idempotencyHeaders:[...e.idempotencyHeaders??[],...t.idempotencyHeaders??[]],pathParameters:[...e.pathParameters??[],...t.pathParameters??[]],errorDiscriminationStrategy:e.errorDiscriminationStrategy??t.errorDiscriminationStrategy,variables:[...e.variables??[],...t.variables??[]],serviceTypeReferenceInfo:e.serviceTypeReferenceInfo??t.serviceTypeReferenceInfo,readmeConfig:e.readmeConfig??t.readmeConfig,sourceConfig:e.sourceConfig??t.sourceConfig,publishConfig:e.publishConfig??t.publishConfig,dynamic:e.dynamic??t.dynamic,sdkConfig:e.sdkConfig??t.sdkConfig}}function uUD(e,t,r){if(e==null&&t==null)return{environments:void 0,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(t==null)return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(e==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(JSON.stringify(e)===JSON.stringify(t))return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let i=fGp(e),n=fGp(t);if(i&&n&&e.environments.type==="singleBaseUrl"&&t.environments.type==="singleBaseUrl")return{environments:{defaultEnvironment:e.defaultEnvironment??t.defaultEnvironment,environments:yI.singleBaseUrl({environments:[...e.environments.environments,...t.environments.environments]})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let a=i?t.defaultEnvironment:e.defaultEnvironment,u=e.environments,l=t.environments;if(u.type==="singleBaseUrl"&&l.type==="singleBaseUrl"){let f=i?l:u,s=i?u:l,o={},{deconflictedEnvironments2:c,changedBaseUrlIds2:b}=cUD(f,s,r);if(f.environments[0]==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let g="Base",O=r.generateName("Base");return f.environments.forEach(m=>{o[m.id]=g}),{environments:{defaultEnvironment:a,environments:yI.multipleBaseUrls({baseUrls:[{id:g,name:O},...c.environments.map(m=>({id:m.id,name:m.name}))],environments:f.environments.map(m=>({id:m.id,name:m.name,urls:{[g]:m.url,...Object.fromEntries(c.environments.map(P=>[P.id,P.url]))},docs:void 0}))})},changedBaseUrlIds1:i?b:o,changedBaseUrlIds2:i?o:b}}if(u.type==="multipleBaseUrls"&&l.type==="singleBaseUrl"||u.type==="singleBaseUrl"&&l.type==="multipleBaseUrls"){let f=u.type==="singleBaseUrl"?u:l,s=u.type==="multipleBaseUrls"?u:l,{deconflictedEnvironments1:o,changedBaseUrlIds1:c}=lUD(f,s,r);return{environments:{defaultEnvironment:a,environments:yI.multipleBaseUrls({baseUrls:[...s.baseUrls,...o.environments.map(b=>({id:b.id,name:b.name}))],environments:s.environments.map(b=>({...b,urls:{...b.urls,...Object.fromEntries(o.environments.map(g=>[g.id,g.url]))}}))})},changedBaseUrlIds1:u.type==="singleBaseUrl"?c:void 0,changedBaseUrlIds2:u.type==="singleBaseUrl"?void 0:c}}if(u.type==="multipleBaseUrls"&&l.type==="multipleBaseUrls"){let{deconflictedEnvironments:f,changedBaseUrlIds:s}=fUD(u,l,r);return{environments:{defaultEnvironment:a,environments:yI.multipleBaseUrls({baseUrls:[...u.baseUrls,...f.baseUrls],environments:u.environments.flatMap(o=>f.environments.map(c=>({...o,urls:{...o.urls,...c.urls}})))})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:s}}return{environments:e??t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0}}function sUD(e,t,r,i){if(r!=null)for(let[u,l]of Object.entries(r)){for(let f of Object.values(e.services))for(let s of Object.values(f.endpoints))s.baseUrl==u&&(s.baseUrl=l);for(let f of Object.values(e.websocketChannels??{}))f.baseUrl==u&&(f.baseUrl=l)}if(i!=null)for(let[u,l]of Object.entries(i)){for(let f of Object.values(t.services))for(let s of Object.values(f.endpoints))s.baseUrl==u&&(s.baseUrl=l);for(let f of Object.values(t.websocketChannels??{}))f.baseUrl==u&&(f.baseUrl=l)}let n={...e.services??{},...t.services??{}},a={...e.websocketChannels??{},...t.websocketChannels??{}};return{services:n,websocketChannels:a}}function cUD(e,t,r){let i={},n=new Set(e.environments.map(s=>s.id)),a=new Set(e.environments.map(s=>s.name)),u=new Map(e.environments.map(s=>[s.url,s.id])),l=t.environments.filter(s=>{let o=u.get(s.url);return o!=null?(i[s.id]=o,!1):!0}).map(s=>{if(n.has(s.id)||a.has(s.name)){let o=TKs(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s});return{deconflictedEnvironments2:yI.singleBaseUrl({environments:l}),changedBaseUrlIds2:i}}function lUD(e,t,r){let i={},n=new Set(t.baseUrls.map(f=>f.id)),a=new Set(t.baseUrls.map(f=>f.name)),u=e.environments.map(f=>{if(n.has(f.id)||a.has(f.name)){let s=TKs(f.id,n);return i[f.id]=s,{...f,id:s,name:r.generateName(s)}}return f});return{deconflictedEnvironments1:yI.singleBaseUrl({environments:u}),changedBaseUrlIds1:i}}function fUD(e,t,r){let i={},n=new Set(e.baseUrls.map(s=>s.id)),a=new Set(e.baseUrls.map(s=>s.name)),u=t.baseUrls.map(s=>{if(n.has(s.id)||a.has(s.name)){let o=TKs(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s}),l=t.environments.map(s=>({...s,urls:Object.fromEntries(Object.entries(s.urls).map(([o,c])=>[i[o]??o,c]))}));return{deconflictedEnvironments:yI.multipleBaseUrls({baseUrls:u,environments:l}),changedBaseUrlIds:i}}function fGp(e){return e.environments.type==="singleBaseUrl"?e.environments.environments.some(t=>t.url&&(t.url.startsWith("ws://")||t.url.startsWith("wss://"))):e.environments.type==="multipleBaseUrls"?e.environments.environments.some(t=>Object.values(t.urls).some(r=>r&&(r.startsWith("ws://")||r.startsWith("wss://")))):!1}function TKs(e,t){let r=e,i=1;for(;t.has(r);)r=`${e}-${i}`,i++;return r}function BKs({rawApiFileSchema:e,casingsGenerator:t}){if(e.auth==null)return{docs:void 0,requirement:Uxe.All,schemes:[]};let r=typeof e.auth!="string"?e.auth.docs:void 0;return Ixi(e.auth,{single:i=>{let n=dGp({reference:i,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t});return{docs:r,requirement:Uxe.All,schemes:[n]}},any:({any:i})=>({docs:r,requirement:Uxe.Any,schemes:i.map(n=>dGp({reference:n,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t}))})})}function dGp({reference:e,authSchemeDeclarations:t,casingsGenerator:r}){let i=(a,u)=>{let l=t?.[a];if(l==null)throw new Error("Unknown auth scheme: "+a);return nua(l,{header:f=>NC.header({docs:u,name:r.generateNameAndWireValue({name:f.name??a,wireValue:f.header}),valueType:Bf.primitive({v1:Zb.String,v2:wp.string({default:void 0,validation:void 0})}),prefix:f.prefix,headerEnvVar:f.env}),basic:f=>pGp({casingsGenerator:r,docs:u,rawScheme:f}),bearer:f=>CKs({casingsGenerator:r,docs:u,rawScheme:f}),oauth:f=>CKs({casingsGenerator:r,docs:u,rawScheme:void 0})})},n=typeof e=="string"?e:e.scheme;switch(n){case"bearer":case"oauth":return CKs({casingsGenerator:r,docs:void 0,rawScheme:void 0});case"basic":return pGp({casingsGenerator:r,docs:void 0,rawScheme:void 0});default:return i(n,typeof e!="string"?e.docs:void 0)}}function CKs({casingsGenerator:e,docs:t,rawScheme:r}){return NC.bearer({docs:t,token:e.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function pGp({casingsGenerator:e,docs:t,rawScheme:r}){return NC.basic({docs:t,username:e.generateName(r?.username?.name??"username"),usernameEnvVar:r?.username?.env,password:e.generateName(r?.password?.name??"password"),passwordEnvVar:r?.password?.env})}function zEn({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:XQr(i,{singleBaseUrl:()=>yI.singleBaseUrl(dUD({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>yI.multipleBaseUrls(pUD({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})}}function dUD({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>XQr(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:_Gp(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function pUD({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>XQr(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:nd(a.urls,u=>_Gp(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function _Gp(e){return e.endsWith("/")?e.slice(0,-1):e}function CDe(e){return e.allParts.map(t=>t.originalName).join("/")}var em={generateTypeId:e=>`type_${CDe(e.fernFilepath)}:${e.name.originalName}`,generateErrorId:e=>`error_${CDe(e.fernFilepath)}:${e.name.originalName}`,generateServiceId:e=>`service_${CDe(e.fernFilepath)}`,generateServiceIdFromFernFilepath:e=>`service_${CDe(e)}`,generateSubpackageId:e=>`subpackage_${CDe(e)}`,generateEndpointId:(e,t)=>{let r=CDe(e.fernFilepath),i=t.name.originalName;return`endpoint_${r}.${i}`},generateWebhookGroupId:e=>`webhooks_${CDe(e)}`,generateWebhookId:(e,t)=>`webhooks_${CDe(e)}.${t}`,generateWebSocketChannelId:e=>`channel_${CDe(e)}`};function REn(e){return e.type!=null}var FRo=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:f,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=f,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=em.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=em.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=em.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)}};function DFi(e){let t={};for(let[r,i]of Object.entries(e))if(typeof i!="string")for(let n of i.audiences??[])t[n]==null&&(t[n]=new Set),t[n]?.add(r);return t}var EFi=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=_UD(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let u=em.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=em.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=em.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&Dz(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=em.generateServiceId(t.name),a=r.id,u=new Set,l=new Set,f=new Set;for(let s of[...t.headers,...r.headers])Dz(s.valueType,u,f);for(let s of[...t.pathParameters,...r.pathParameters])Dz(s.valueType,u,f);for(let s of r.queryParameters)Dz(s.valueType,u,f);if(i!=null&&i.request!=null&&typeof i.request!="string"){let s=DFi(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:s}}r.requestBody!=null&&FC._visit(r.requestBody,{inlinedRequestBody:s=>{for(let o of s.extends)LRo(o,u,f);for(let o of s.properties)Dz(o.valueType,u,f);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&oC(i.request.body)){let o=DFi(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:s})=>{Dz(s,u,f)},fileUpload:({properties:s})=>{for(let o of s)O5._visit(o,{file:Go,bodyProperty:({valueType:c})=>{Dz(c,u,f)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+o.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&SM._visit(r.response.body,{fileDownload:Go,json:s=>{Dz(s.responseBodyType,u,f)},streaming:s=>{s._visit({sse:o=>Dz(o.payload,u,f),json:o=>Dz(o.payload,u,f),text:Go,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.type)}})},streamParameter:s=>{s.streamResponse._visit({sse:o=>Dz(o.payload,u,f),json:o=>Dz(o.payload,u,f),text:Go,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.streamResponse.type)}}),s.nonStreamResponse.type==="json"&&Dz(s.nonStreamResponse.value.responseBodyType,u,f)},text:Go,bytes:Go,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(s=>{l.add(em.generateErrorId(s.error)),f.add(s.error.fernFilepath)}),this.endpoints[a]={endpointId:a,serviceId:n,referencedTypes:u,referencedErrors:l,referencedSubpackages:f}}markEndpointForAudience(t,r,i){if(this.hasAudience(i)){let n=em.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&&aV._visit(r.payload,{inlinedPayload:l=>{for(let f of l.extends)LRo(f,a,u);for(let f of l.properties)Dz(f.valueType,a,u);if(i?.payload!=null&&typeof i.payload=="object"&&!REn(i.payload)){let f=DFi(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:f}}},reference:({payloadType:l})=>{Dz(l,a,u)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),u.add(t),this.webhooks[n]={webhookId:n,referencedTypes:a,referencedSubpackages:u}}markWebhookForAudiences(t,r,i){let n=r.id;n!=null&&this.hasAudience(i)&&(this.webhooksNeededForAudience.add(n),this.addSubpackages(t))}addChannel(t,r,i,n){if(r==null)return;let a=new Set,u=new Set;for(let l of i.messages)P5._visit(l.body,{reference:({bodyType:f})=>{Dz(f,a,u)},inlinedBody:f=>{for(let s of f.extends)LRo(s,a,u);for(let s of f.properties)Dz(s.valueType,a,u)},_other:()=>{}});u.add(t),this.channels[r]={channelId:r,referencedTypes:a,referencedSubpackages:u}}markChannelForAudiences(t,r,i){r!=null&&this.hasAudience(i)&&(this.channelsNeededForAudience.add(r),this.addSubpackages(t))}build(){let t=new Set,r=new Set;for(let l of this.endpointsNeededForAudience.keys()){let f=this.getEndpointNode(l);for(let s of f.referencedErrors){if(r.has(s))continue;r.add(s);let o=this.getErrorNode(s);this.addReferencedTypes(t,o.referencedTypes)}this.addReferencedTypes(t,f.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let l of this.webhooksNeededForAudience.keys()){let f=this.getWebhookNode(l);this.addReferencedTypes(t,f.referencedTypes)}for(let l of this.channelsNeededForAudience.keys()){let f=this.getChannelNode(l);this.addReferencedTypes(t,f.referencedTypes)}let i={},n={},a={},u={};if(this.audiences.type==="filtered"){for(let[l,f]of Object.entries(this.properties)){if(!t.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=f.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,f]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=f.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}n[l]=s.size>0?s:void 0}for(let[l,f]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=f.parametersByAudience[o];c?.forEach(b=>{s.add(b)})}a[l]=s.size>0?s:void 0}for(let[l,f]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=f.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}u[l]=s.size>0?s:void 0}}return new FRo({types:t,properties:i,errors:r,requestProperties:n,queryParameters:a,environments:this.environmentsNeededForAudience,services:this.servicesNeededForAudience,endpoints:this.endpointsNeededForAudience,webhooks:this.webhooksNeededForAudience,webhookPayloadProperties:u,subpackages:this.subpackagesNeededForAudience,channels:this.channelsNeededForAudience})}markTypeForService(t,r){let i=this.typesReferencedByService[t]??=new Set;if(i.has(r))return;i.add(r);let n=this.getTypeNode(t);for(let a of n.allDescendants)this.markTypeForService(a,r)}addReferencedTypes(t,r){for(let i of r){if(t.has(i))continue;t.add(i);let n=this.getTypeNode(i);if(this.audiences.type==="filtered")for(let a of this.audiences.audiences){let u=n.descendantsByAudience[a];if(u!=null)u.forEach(l=>{t.add(l)});else{n.allDescendants.forEach(l=>{t.add(l)});break}}else n.allDescendants.forEach(a=>{t.add(a)})}}getTypeNode(t){let r=this.types[t];if(r==null)throw new Error(`Failed to find type node with id ${t}`);return r}getErrorNode(t){let r=this.errors[t];if(r==null)throw new Error(`Failed to find error node with id ${t}`);return r}getEndpointNode(t){let r=this.endpoints[t];if(r==null)throw new Error(`Failed to find endpoint node with id ${t}`);return r}getWebhookNode(t){let r=this.webhooks[t];if(r==null)throw new Error(`Failed to find webhook node with id ${t}`);return r}getChannelNode(t){let r=this.channels[t];if(r==null)throw new Error(`Failed to find channel node with id ${t}`);return r}hasNoAudiences(){return this.audiences.type==="none"}hasAudience(t){let r=this.audiences;switch(r.type){case"none":return!0;case"filtered":return t.some(i=>r.audiences.has(i));default:Mo(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(em.generateSubpackageId(i))}}};function _UD(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:Mo(e)}}function Dz(e,t,r){Bf._visit(e,{container:i=>{hUD(i,t,r)},named:i=>{LRo(i,t,r)},primitive:Go,unknown:Go,_other:Go})}function LRo(e,t,r){t.add(em.generateTypeId(e)),r.add(e.fernFilepath)}function hUD(e,t,r){Tv._visit(e,{list:i=>{Dz(i,t,r)},map:i=>{Dz(i.keyType,t,r),Dz(i.valueType,t,r)},optional:i=>{Dz(i,t,r)},nullable:i=>{Dz(i,t,r)},set:i=>{Dz(i,t,r)},literal:Go,_other:Go})}var hne={};jo(hne,{FernAvailabilityExtension:()=>URo,FernEnumExtension:()=>VRo,FernIgnoreExtension:()=>MFi,FernOptionalExtension:()=>WRo,FernTypeExtension:()=>GRo,SdkGroupNameExtension:()=>HRo,SdkMethodNameExtension:()=>$Ro});var dS=class{breadcrumbs;context;constructor(t){this.breadcrumbs=t.breadcrumbs,this.context=t.context}getExtensionValue(t){if(!(typeof t!="object"||t==null))return t[this.key]}};var URo=class extends dS{node;key="x-fern-availability";constructor({breadcrumbs:t,node:r,context:i}){super({breadcrumbs:t,context:i}),this.node=r}async convert(){let t=this.getExtensionValue(this.node);if(t==null||typeof t!="string")return;switch(t.toUpperCase().replace(/[-_\s]/g,"_")){case"IN_DEVELOPMENT":return g5.InDevelopment;case"PRE_RELEASE":return g5.PreRelease;case"GENERAL_AVAILABILITY":return g5.GeneralAvailability;case"DEPRECATED":return g5.Deprecated;default:return}}};var yUD=pu.object({snake:pu.string().optional(),camel:pu.string().optional(),screamingSnake:pu.string().optional(),pascal:pu.string().optional()}),vUD=pu.object({description:pu.string().optional(),name:pu.string().optional(),casing:yUD.optional()}),hGp=pu.record(vUD);var VRo=class extends dS{schema;key="x-fern-enum";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t==null)return;let r=hGp.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-enum extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data}};var MFi=class extends dS{operation;key="x-fern-ignore";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-ignore",path:this.breadcrumbs});return}return t}}};var WRo=class extends dS{parameter;key="x-fern-optional";constructor({breadcrumbs:t,parameter:r,context:i}){super({breadcrumbs:t,context:i}),this.parameter=r}convert(){let t=this.getExtensionValue(this.parameter);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-optional",path:this.breadcrumbs});return}return t}}};var HRo=class extends dS{operation;key="x-fern-sdk-group-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(i=>typeof i=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{groups:r}}};var $Ro=class extends dS{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null&&typeof t=="string")return{methodName:t}}};var GRo=class extends dS{schema;key="x-fern-type";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t!=null&&typeof t=="string")return t}};var w0=class{ir;breadcrumbs=[];context;static STRING=Ks.TypeReference.primitive({v1:"STRING",v2:Ks.PrimitiveTypeV2.string({default:void 0,validation:void 0})});constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r,this.ir={auth:{docs:void 0,requirement:Ks.AuthSchemesRequirement.All,schemes:[]},selfHosted:!1,types:{},services:{},errors:{},webhookGroups:{},websocketChannels:void 0,headers:[],idempotencyHeaders:[],apiVersion:void 0,apiDisplayName:void 0,apiDocs:void 0,basePath:void 0,pathParameters:[],errorDiscriminationStrategy:Ks.ErrorDiscriminationStrategy.statusCode(),variables:[],serviceTypeReferenceInfo:{sharedTypes:[],typesReferencedOnlyByService:{}},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,environments:void 0,fdrApiDefinitionId:void 0,rootPackage:r.createPackage(),subpackages:{},sdkConfig:{hasFileDownloadEndpoints:!1,hasPaginatedEndpoints:!1,hasStreamingEndpoints:!1,isAuthMandatory:!0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}}}}async resolveExternalRefs({spec:t,context:r}){let i=[t];for(;i.length>0;){let n=i.shift();n!=null&&(Array.isArray(n)?await this.resolveExternalRefsInArray(n,r,i):typeof n=="object"&&await this.resolveExternalRefsInObject(n,r,i))}return t}async resolveExternalRefsInArray(t,r,i){for(let n=0;n<t.length;n++)t[n]=await this.resolveReferenceChain(t[n],r,i)}async resolveExternalRefsInObject(t,r,i){for(let[n,a]of Object.entries(t))t[n]=await this.resolveReferenceChain(a,r,i)}async resolveReferenceChain(t,r,i){let n=t;if(!this.context.isReferenceObject(n))return i.push(n),t;for(;this.context.isReferenceObject(n);){let a=this.context.isExternalReference(n.$ref),u=await r.resolveReference({$ref:n.$ref});if(u.resolved){if(n=u.value,a)return n}else return t}return t}removeXFernIgnores({document:t,context:r,breadcrumbs:i=[]}){return Array.isArray(t)?t.filter((n,a)=>!new MFi({breadcrumbs:[...i,String(a)],operation:n,context:r}).convert()).map((n,a)=>this.removeXFernIgnores({document:n,context:r,breadcrumbs:[...i,String(a)]})):t!=null&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([n,a])=>!new MFi({breadcrumbs:[...i,n],operation:a,context:r}).convert()).map(([n,a])=>[n,this.removeXFernIgnores({document:a,context:r,breadcrumbs:[...i,n]})])):t}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...t??[]),r.length==0)return this.ir.rootPackage;let i=this.ir.rootPackage;for(let n=0;n<r.length;n++){let a=$y(r[n]),l=`subpackage_${r.slice(0,n+1).map(s=>$y(s)).join(".")}`;this.ir.subpackages[l]==null&&(this.ir.subpackages[l]={name:this.context.casingsGenerator.generateName(a),...this.context.createPackage({name:a})});let f=this.ir.subpackages[l];i.subpackages.includes(l)||i.subpackages.push(l),i=f}return i}};var yGp={[Yh.GenerationLanguage.PHP]:new Set(["abstract","and","as","break","callable","case","catch","class","clone","const","continue","declare","default","do","echo","else","elseif","enddeclare","endfor","endforeach","endif","endswitch","endwhile","extends","final","finally","fn","for","foreach","function","global","goto","list","if","implements","include","include_once","instanceof","insteadof","interface","match","namespace","new","or","parent","Parent","print","private","protected","public","readonly","require","require_once","return","static","switch","throw","trait","try","use","var","while","xor","yield"].flatMap(e=>[e,dx(e)])),[Yh.GenerationLanguage.TYPESCRIPT]:new Set(["any","as","boolean","break","case","catch","class","const","constructor","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","let","module","new","null","number","of","package","private","protected","public","require","return","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","Date","Error","File","Object","Record"]),[Yh.GenerationLanguage.JAVA]:new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","false","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","true","try","void","volatile","while"]),[Yh.GenerationLanguage.PYTHON]:new Set(["False","None","True","and","as","assert","async","","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","float","int","complex","bool","uuid","list","set","map","long","self","all"]),[Yh.GenerationLanguage.GO]:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[Yh.GenerationLanguage.RUBY]:new Set(["__ENCODING__","__LINE__","__FILE__","alias","and","begin","break","case","class","def","defined","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield","Object","JSON","Date","DateTime"]),[Yh.GenerationLanguage.CSHARP]:new Set(["abstract","as","base","bool","break","byte","case","catch","char","checked","class","const","continue","decimal","default","delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","goto","if","implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","operator","out","override","params","private","protected","public","readonly","ref","return","sbyte","sealed","short","sizeof","stackalloc","static","string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","ushort","using","virtual","void","volatile","while","add","and","alias","ascending","args","async","","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","managed","nameof","nint","not","notnull","nuint","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value","var","when","where","with","yield"]),[Yh.GenerationLanguage.SWIFT]:new Set([])};var bUD=["go","ruby"];function BDe({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let u=c=>({unsafeName:c,safeName:gUD({name:c,keywords:OUD({generationLanguage:e,keywords:t})})}),l=$y(n),f=dx(l),s=qCi(n),o=DCi(l);return r&&(!jUD(o)&&(e==null||bUD.includes(e))&&(l=o.map((c,b)=>{if(b>0){let g=QRo(c);if(g!=null)return g;if(JRo(c))return c.toUpperCase()}return c}).join(""),f=o.map((c,b)=>{let g=QRo(c);return g??(JRo(c)?c.toUpperCase():b===0?dx(c):c)}).join("")),s=n.split(" ").map(c=>c.split(/(\d+)/).map(qCi).join("")).join("_")),{originalName:n,camelCase:u(a?.casingOverrides?.camel??l),snakeCase:u(a?.casingOverrides?.snake??s),screamingSnakeCase:u(a?.casingOverrides?.["screaming-snake"]??s.toUpperCase()),pascalCase:u(a?.casingOverrides?.pascal??f)}},generateNameAndWireValue:({name:n,wireValue:a,opts:u})=>({name:i.generateName(n,u),wireValue:a})};return i}function gUD({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":PUD(e)?"_"+e:e}function OUD({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return yGp[e]}var mUD=/^[0-9]/;function PUD(e){return mUD.test(e)}function jUD(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=QRo(i)!=null||JRo(i),a=QRo(t)!=null||JRo(t);return n&&a})}function QRo(e){return SUD.get(e.toUpperCase())}function JRo(e){return wUD.has(e.toUpperCase())}var wUD=new Set(["ACL","API","ASCII","CPU","CSS","DNS","EOF","GUID","HTML","HTTP","HTTPS","ID","IP","JSON","LHS","QPS","RAM","RHS","RPC","SAML","SCIM","SLA","SMTP","SQL","SSH","SSO","TCP","TLS","TTL","UDP","UI","UID","UUID","URI","URL","UTF8","VM","XML","XMPP","XSRF","XSS"]),SUD=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);var k2=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;authOverrides;environmentOverrides;globalHeaderOverrides;constructor(t){this.args=t,this.spec=t.spec,this.settings=t.settings,this.errorCollector=t.errorCollector,this.logger=t.logger,this.generationLanguage=t.generationLanguage,this.smartCasing=t.smartCasing,this.namespace=t.namespace,this.casingsGenerator=BDe({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs,this.authOverrides=t.authOverrides,this.environmentOverrides=t.environmentOverrides,this.globalHeaderOverrides=t.globalHeaderOverrides}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=t.filter((n,a)=>!(/^\d+$/.test(n)||e.BREADCRUMBS_TO_IGNORE.includes(n)||a===0&&n==="components"||a===1&&n==="schemas"||t[0]==="paths"&&(a===0||a===1&&["get","post","put","delete","patch"].includes(n)||a===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&n==="parameters"))),i=$y(r.join("_"));return i.charAt(0).toUpperCase()+i.slice(1)}createPackage(t={}){return{fernFilepath:this.createFernFilepath(t),service:void 0,types:[],errors:[],subpackages:[],docs:void 0,webhooks:void 0,websocket:void 0,hasEndpointsInTree:!1,navigationConfig:void 0}}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],i=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:i?[...r,i]:r,packagePath:r,file:i}}async resolveReference(t){let r=this.spec,i,n=!1,a=null,u;if(this.isExternalReference(t.$ref)){n=!0;let f=t.$ref.split("#"),s=f[0];if(i=f[1],!s)return{resolved:!1};u=s;let o=await fetch(s);if(!o.ok)return{resolved:!1};try{let c=await o.text();try{a=JSON.parse(c),r=a}catch{a=Gd.load(c),r=a}if(r==null)return{resolved:!1}}catch{return{resolved:!1}}if(!i)return{resolved:!0,value:r}}let l=(i??t.$ref).replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(f=>f.replace(/~1/g,"/"));for(let f of l){if(typeof r!="object"||r==null)return{resolved:!1};r=r[f]}if(r==null)return{resolved:!1};if(n&&typeof r=="object"&&r!==null){let f=new Set;f.add(t.$ref),r=await this.resolveNestedExternalReferences(r,a,f,u)}return{resolved:!0,value:r}}async resolveNestedExternalReferences(t,r,i,n){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let u=[];for(let l of t)u.push(await this.resolveNestedExternalReferences(l,r,i,n));return u}if(this.isReferenceObject(t)){let u=t.$ref;if(this.isExternalReference(u)){if(i.has(u))return t;i.add(u);let l=await this.resolveReference({$ref:u});if(i.delete(u),l.resolved)return l.value}else{let l=`${n}${u}`;if(i.has(l))return t;i.add(l);let f=r,s=u.substring(2).split("/").map(o=>o.replace(/~1/g,"/").replace(/~0/g,"~"));for(let o of s){if(typeof f!="object"||f===null)return t;f=f[o]}if(f!=null){let o=await this.resolveNestedExternalReferences(f,r,i,n);return i.delete(u),o}i.delete(u)}return t}let a={};for(let[u,l]of Object.entries(t))typeof l=="object"&&l!==null?a[u]=await this.resolveNestedExternalReferences(l,r,i,n):a[u]=l;return a}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let i=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?i.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),i}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:i}){if(t==null)return[];let n=[];if(t.example!=null){let a=this.generateUniqueName({prefix:i??`${r.join("_")}_example`,existingNames:[]});n.push([a,t.example])}return t.examples!=null&&n.push(...Object.entries(t.examples)),n}async resolveMaybeReference({schemaOrReference:t,breadcrumbs:r}){if(this.isReferenceObject(t)){let i=await this.resolveReference(t);if(!i.resolved){this.errorCollector.collect({message:`Failed to resolve reference: ${t.$ref}`,path:r});return}return i.value}return t}async resolveExample(t){if(!this.isReferenceObject(t))return t;let r=await this.resolveReference(t);return r.resolved?this.returnExampleValue(r.value):void 0}async resolveExampleWithValue(t){if(!this.isReferenceObject(t))return this.returnExampleValue(t);let r=await this.resolveReference(t);return r.resolved?this.returnExampleValue(r.value):void 0}returnExampleValue(t){return this.isExampleWithValue(t)?t.value:t}async getPropertyAccess(t){let r=t;for(;this.isReferenceObject(r);){let i=await this.resolveReference(r);if(!i.resolved)return;r=i.value}if(!(r.readOnly&&r.writeOnly)){if(r.readOnly)return vJt.ReadOnly;if(r.writeOnly)return vJt.WriteOnly}}async getAvailability({node:t,breadcrumbs:r}){for(;this.isReferenceObject(t);){let a=await this.resolveReference(t);if(!a.resolved)return;t=a.value}let n=await new hne.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(n!=null)return{status:n,message:void 0};if(t.deprecated===!0)return{status:g5.Deprecated,message:void 0}}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t){return Bf.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t??"defaultName"),typeId:t,default:void 0,inline:!1})}typeReferenceToDeclaredTypeName(t){if(t.type!=="named")return;let r=t.typeId;return{typeId:r,fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(r)}}removeSchemaFromInlinedTypes({id:t,inlinedTypes:r}){return Object.fromEntries(Object.entries(r).filter(([i])=>i!==t))}static maybeTrimPrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}generateUniqueName({prefix:t,existingNames:r}){if(!r.includes(t))return t;let i=0;for(;r.includes(`${t}_${i}`);)i++;return`${t}_${i}`}isReferenceObject(t){return typeof t=="object"&&t!==null&&"$ref"in t}isExternalReference(t){return t.startsWith("http://")||t.startsWith("https://")}isExampleWithValue(t){return typeof t=="object"&&t!=null&&"value"in t}isOptional(t){return t.type==="container"&&t.container.type==="optional"}isNullable(t){return t.type==="container"&&t.container.type==="nullable"}isList(t){return t.type==="container"&&t.container.type==="list"}isFile(t){return t.type==="primitive"&&t.primitive.v2?.type==="string"&&t.primitive.v2.validation?.format==="binary"}getAsString(t){if(typeof t=="string")return t}getAsInteger(t){if(typeof t=="number"&&Number.isInteger(t))return t}getAsNumber(t){if(typeof t=="number")return t}getAsBoolean(t){if(typeof t=="boolean")return t}getAsArray(t){if(Array.isArray(t))return t}getAsObject(t){if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}getGroup({groupParts:t,namespace:r}){let i=[];return r!=null&&i.push(r),i.push(...t??[]),i}};var hA={};jo(hA,{AbstractConverters:()=>IKs,ExampleConverter:()=>OZt,SchemaConverters:()=>xKs,ServersConverter:()=>mZt});var IKs={};jo(IKs,{AbstractMediaTypeObjectConverter:()=>YRo,AbstractParameterConverter:()=>XRo});var OZt=class e extends w0{MAX_DEPTH=12;EXAMPLE_STRING="foo";EXAMPLE_NUMBER=42;EXAMPLE_BOOLEAN=!0;EXAMPLE_INTEGER=42;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;constructor({breadcrumbs:t,context:r,schema:i,example:n,depth:a=0,exampleGenerationStrategy:u,generateOptionalProperties:l=!1}){super({breadcrumbs:t,context:r}),this.example=n,this.schema=i,this.depth=a,this.exampleGenerationStrategy=u,this.generateOptionalProperties=l}async convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};let t=await this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs});return t==null?{isValid:!1,coerced:!1,validExample:null,errors:[{message:"Schema is not resolvable",path:this.breadcrumbs}]}:typeof t!="object"?{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Schema should be an object: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]}:"nullable"in t&&t.nullable===!0&&this.example===null?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:Array.isArray(t.type)?this.convertSchemaTypeArray({resolvedSchema:t}):t.type=="null"?this.convertNull():t.type=="boolean"?await this.convertBoolean():t.enum!=null?this.convertEnum(t):t.type=="number"?await this.convertNumber():t.type=="string"?await this.convertString():t.type=="integer"?await this.convertInteger():t.type=="array"?this.convertArray({resolvedSchema:t}):"oneOf"in t&&t.oneOf!=null?this.convertOneOf({resolvedSchema:t}):"anyOf"in t&&t.anyOf!=null?this.convertAnyOf({resolvedSchema:t}):t.type=="object"||t.properties!=null||t.allOf!=null?this.convertObject({resolvedSchema:t}):typeof t=="object"&&Object.keys(t).length===0?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Unsupported schema type: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]}}convertNull(){let t=this.example===null;return t?{isValid:t,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Example is not null: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}async convertBoolean(){let t=typeof this.example=="boolean";if(t)return{isValid:t,coerced:!1,validExample:this.example,errors:[]};let r=this.context.isReferenceObject(this.schema)?(await this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs}))?.default:this.schema.default;return typeof r=="boolean"?{isValid:!0,coerced:!1,validExample:r,errors:[]}:{isValid:!1,coerced:!1,validExample:await this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_BOOLEAN,errors:[{message:`Example is not a boolean: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}async convertEnum(t){let r=t.enum?.includes(this.example)??!1;if(r)return{isValid:r,coerced:!1,validExample:this.example,errors:[]};let i=this.context.isReferenceObject(this.schema)?(await this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs}))?.default:this.schema.default;return i!==void 0&&t.enum?.includes(i)?{isValid:!0,coerced:!1,validExample:i,errors:[]}:{isValid:r,coerced:!1,validExample:t.enum?.[0],errors:[{message:`Example is not one of the allowed enum values: ${JSON.stringify(t.enum,null,2)}`,path:this.breadcrumbs}]}}async convertNumber(){if(typeof this.example=="number")return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};let t=Number(this.example);if(!isNaN(t))return{isValid:!0,coerced:!0,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?(await this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs}))?.default:this.schema.default;return typeof r=="number"?{isValid:!0,coerced:!1,validExample:r,errors:[]}:{isValid:!1,coerced:!1,validExample:await this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}async convertString(){if(typeof this.example=="string")return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};if(typeof this.example!="object"&&!Array.isArray(this.example)&&this.example!=null)return{isValid:!0,coerced:!0,validExample:String(this.example),errors:[]};let t=this.context.isReferenceObject(this.schema)?(await this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs}))?.default:this.schema.default;return typeof t=="string"?{isValid:!0,coerced:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,validExample:await this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_STRING,errors:[{message:`Example cannot be converted to string: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}async convertInteger(){if(typeof this.example=="number"&&Number.isInteger(this.example))return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};if(typeof this.example=="string"){let r=Number(this.example);if(!isNaN(r)&&Number.isInteger(r))return{isValid:!0,coerced:!0,validExample:r,errors:[]}}let t=this.context.isReferenceObject(this.schema)?(await this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs}))?.default:this.schema.default;return typeof t=="number"&&Number.isInteger(t)?{isValid:!0,coerced:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,validExample:await this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_INTEGER,errors:[{message:`Example is not an integer: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}async convertArray({resolvedSchema:t}){if(t.type!="array")return{isValid:!1,coerced:!1,validExample:null,errors:[]};t.items==null&&(t.items={type:"string"});let r=Array.isArray(this.example)?this.example:[this.example],i=await Promise.all(r.map(async(a,u)=>await new e({breadcrumbs:[...this.breadcrumbs,`Item[${u}]`],context:this.context,schema:t.items,example:a,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy}).convert())),n=i.every(a=>a?.isValid??!1);return{isValid:n,coerced:!1,validExample:i.map(a=>a.validExample),errors:n?[]:i.flatMap(a=>a.errors)}}async convertObject({resolvedSchema:t}){if(t.type=="object"&&t.properties==null&&t.allOf==null)return{isValid:!0,coerced:!1,validExample:this.example??{},errors:[]};let r=typeof this.example!="object"||this.example==null?{}:this.example,i=await Promise.all(Object.entries(t.properties??{}).map(async([l,f])=>{if(typeof f!="object")return{key:l,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("readOnly"in f&&f.readOnly===!0&&"writeOnly"in f&&f.writeOnly===!0)return{key:l,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("readOnly"in f&&f.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:l,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("writeOnly"in f&&f.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:l,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};let s=!(l in r)||!("nullable"in f)&&r[l]==null||"nullable"in f&&f.nullable===!0&&r[l]===void 0,o=!t.required?.includes(l);if(s&&o){if(this.example===void 0&&this.generateOptionalProperties){let c=new e({breadcrumbs:[...this.breadcrumbs,l],context:this.context,schema:f,example:void 0,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy});return{key:l,result:await c.convert()}}return{key:l,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}}}else{let b=await new e({breadcrumbs:[...this.breadcrumbs,l],context:this.context,schema:f,example:r[l],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy}).convert();return{key:l,result:b}}})),n=await Promise.all((t.allOf??[]).map(async(l,f)=>await new e({breadcrumbs:[...this.breadcrumbs,`allOf[${f}]`],context:this.context,schema:{...t,...l,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy}).convert())),a=i.every(l=>l.result.isValid)&&n.every(l=>l.isValid),u=Object.fromEntries(i.map(({key:l,result:f})=>[l,f.validExample]).filter(([l,f])=>f!==void 0));for(let l of n)if(typeof l.validExample=="object"&&l.validExample!==null){let f=l.validExample;u={...u,...Object.fromEntries(Object.entries(f).filter(([s,o])=>o!==void 0))}}if(Object.keys(u).length===0){let l=n.find(f=>f.validExample!==void 0&&(typeof f.validExample!="object"||f.validExample===null));l&&(u=l.validExample)}return{isValid:a,coerced:!1,validExample:u,errors:[...i.flatMap(({result:l})=>l.errors),...n.flatMap(l=>l.errors)]}}async convertSchemaTypeArray({resolvedSchema:t}){if(!Array.isArray(t.type))return{isValid:!1,coerced:!1,validExample:null,errors:[]};if(t.type.length===1)return await new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:{...t,type:t.type[0]},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy}).convert();let r=await Promise.all(t.type.map(async(u,l)=>await new e({breadcrumbs:[...this.breadcrumbs,`type[${l}]`],context:this.context,schema:{...t,type:u},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy}).convert())),i=r.some(u=>u?.isValid??!1),a=r.find(u=>u.isValid)?.validExample??r[0]?.validExample??null;return{isValid:i,coerced:!1,validExample:a,errors:i?[]:r.flatMap(u=>u?.errors??[])}}async convertOneOf({resolvedSchema:t}){if(!("oneOf"in t)||t.oneOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=await Promise.all(t.oneOf.map(async(u,l)=>await new e({breadcrumbs:[...this.breadcrumbs,`oneOf[${l}]`],context:this.context,schema:{...t,...u,oneOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy}).convert())),i=r.filter(u=>u.isValid),n=i.length>0,a;return n?a=i.find(l=>!l.coerced)?.validExample??i[0]?.validExample:a=r[0]?.validExample,{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(u=>u.errors)}}async convertAnyOf({resolvedSchema:t}){if(!("anyOf"in t)||t.anyOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=await Promise.all(t.anyOf.map(async(u,l)=>await new e({breadcrumbs:[...this.breadcrumbs,`anyOf[${l}]`],context:this.context,schema:u,example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy}).convert())),i=r.filter(u=>u.isValid),n=i.length>0,a;return n?a=i.find(l=>!l.coerced)?.validExample??i[0]?.validExample:a=r[0]?.validExample,{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(u=>u.errors)}}async maybeResolveSchemaExample(t){let r=await this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs});if(r!=null){if("example"in r)return r.example;if("examples"in r)return Object.values(r.examples??{})[0]}}};var xKs={};jo(xKs,{ArraySchemaConverter:()=>VEn,EnumSchemaConverter:()=>NEn,ObjectSchemaConverter:()=>FEn,OneOfSchemaConverter:()=>LEn,PrimitiveSchemaConverter:()=>UEn,SchemaConverter:()=>p_i,SchemaOrReferenceConverter:()=>zX});function vGp(e){return x2({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return Bf.primitive({v1:"BASE_64",v2:wp.base64({})});case"BOOLEAN":return Bf.primitive({v1:"BOOLEAN",v2:wp.boolean({default:void 0})});case"DATE":return Bf.primitive({v1:"DATE",v2:wp.date({})});case"DATE_TIME":return Bf.primitive({v1:"DATE_TIME",v2:wp.dateTime({})});case"FLOAT":return Bf.primitive({v1:"FLOAT",v2:wp.float({})});case"DOUBLE":return Bf.primitive({v1:"DOUBLE",v2:wp.double({default:void 0,validation:void 0})});case"UINT":return Bf.primitive({v1:"UINT",v2:wp.uint({})});case"UINT_64":return Bf.primitive({v1:"UINT_64",v2:wp.uint64({})});case"INTEGER":return Bf.primitive({v1:"INTEGER",v2:wp.integer({default:void 0,validation:void 0})});case"LONG":return Bf.primitive({v1:"LONG",v2:wp.long({default:void 0})});case"STRING":return Bf.primitive({v1:"STRING",v2:wp.string({default:void 0,validation:void 0})});case"UUID":return Bf.primitive({v1:"UUID",v2:wp.uuid({})});case"BIG_INTEGER":return Bf.primitive({v1:"BIG_INTEGER",v2:wp.bigInteger({default:void 0})});default:return}},unknown:()=>Bf.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return Bf.container(Tv.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return Bf.container(Tv.list(t))},optional:t=>{if(t!=null)return Bf.container(Tv.optional(t))},nullable:t=>{if(t!=null)return Bf.container(Tv.nullable(t))},set:t=>{if(t!=null)return Bf.container(Tv.set(t))},literal:t=>Bf.container(Tv.literal(t._visit({string:r=>m5.string(r),boolean:r=>m5.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var NEn=class extends w0{schema;maybeFernEnum;constructor({context:t,breadcrumbs:r,schema:i,maybeFernEnum:n}){super({context:t,breadcrumbs:r}),this.schema=i,this.maybeFernEnum=n}convert(){if(!this.schema.enum)return;let r=this.schema.enum.filter(n=>typeof n=="string"||typeof n=="number").map(n=>{let a=n.toString(),u=this.maybeFernEnum?.[a],l=u?.name??a;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:l,wireValue:a}),docs:u?.description,availability:void 0,casing:u?.casing}});if(r.length===0){this.context.errorCollector.collect({message:`Received enum schema with no valid values: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}let i=this.context.getAsString(this.schema.default);return{type:KO.enum({default:i!=null?r.find(n=>n.name.wireValue===i):void 0,values:r})}}};var DUD=Bf.primitive({v1:"STRING",v2:wp.string({default:void 0,validation:void 0})}),KRo=class extends w0{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}async convert(){let r=await new zX({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schema}).convert();if(r!=null){let i=Bf.container(Tv.map({keyType:DUD,valueType:r.type}));return{type:KO.alias({aliasOf:i,resolvedType:i}),inlinedTypes:r.inlinedTypes}}}};async function Zva({properties:e,required:t,breadcrumbs:r,context:i,errorCollector:n}){let a=[],u={};for(let[l,f]of Object.entries(e??{})){let s=[...r,"properties",l];if(typeof f!="object"){n.collect({message:`Schema property ${l} should be an object`,path:s});continue}let o=i.convertBreadcrumbsToName(s),c="nullable"in f?f.nullable:!1,g=await new zX({context:i,breadcrumbs:s,schemaOrReference:f,schemaIdOverride:o,wrapAsOptional:!t.includes(l),wrapAsNullable:c}).convert();g!=null&&(a.push({name:i.casingsGenerator.generateNameAndWireValue({name:l,wireValue:l}),valueType:g.type,docs:f.description,availability:g.availability,propertyAccess:await i.getPropertyAccess(f),v2Examples:g.schema?.v2Examples??{userSpecifiedExamples:{},autogeneratedExamples:{}}}),u={...u,...g.inlinedTypes})}return{convertedProperties:a,inlinedTypesFromProperties:u}}var FEn=class extends w0{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}async convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:KO.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),inlinedTypes:{}};let{convertedProperties:r,inlinedTypesFromProperties:i}=await Zva({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector}),n=[],a=i;for(let[u,l]of(this.schema.allOf??[]).entries()){if(this.context.isReferenceObject(l)){let o=await this.context.convertReferenceToTypeReference(l);o.ok&&n.push(o.reference);continue}let{convertedProperties:f,inlinedTypesFromProperties:s}=await Zva({properties:l.properties??{},required:[...this.schema.required??[],...l.required??[]],breadcrumbs:[...this.breadcrumbs,"allOf",u.toString()],context:this.context,errorCollector:this.context.errorCollector});r.push(...f),a={...a,...s}}return{type:KO.object({properties:r,extends:n.map(u=>this.context.typeReferenceToDeclaredTypeName(u)).filter(g0),extendedProperties:[],extraProperties:t}),inlinedTypes:a}}};var LEn=class extends w0{schema;id;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlinedTypes:a}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n}async convert(){return this.shouldConvertAsNullableSchemaOrReference()?await this.convertAsNullableSchemaOrReference():this.schema.discriminator!=null&&!await this.unionVariantsContainLiteral({discriminantProperty:this.schema.discriminator.propertyName})?await this.convertAsDiscriminatedUnion():this.convertAsUndiscriminatedUnion()}async unionVariantsContainLiteral({discriminantProperty:t}){for(let[r,i]of Object.entries(this.schema.discriminator?.mapping??{})){let n=await this.context.resolveReference({$ref:i});if(n.resolved&&!Object.keys(n.value.properties??{}).includes(t))return!1}return!0}async convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=[],r={};for(let[a,u]of Object.entries(this.schema.discriminator.mapping??{})){let l=new zX({context:this.context,schemaOrReference:{$ref:u},breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",a]}),f=this.context.getTypeIdFromSchemaReference({$ref:u}),s=await l.convert();if(s?.type!=null&&f!=null){let o=this.context.casingsGenerator.generateNameAndWireValue({name:a,wireValue:a});t.push({docs:void 0,discriminantValue:o,availability:s.availability,displayName:void 0,shape:sG.samePropertiesAsObject({typeId:f,name:this.context.casingsGenerator.generateName(f),fernFilepath:{allParts:[],packagePath:[],file:void 0}})}),r={...r,...s.inlinedTypes}}}let{convertedProperties:i,inlinedTypesFromProperties:n}=await Zva({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});return{type:KO.union({baseProperties:i,discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:[],types:t}),inlinedTypes:{...r,...n}}}async convertAsUndiscriminatedUnion(){if(!this.schema.oneOf&&!this.schema.anyOf||this.schema.anyOf?.length===0&&this.schema.oneOf?.length===0)return;let t=[],r={};for(let[i,n]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(n)){let f=await this.context.convertReferenceToTypeReference(n);f.ok&&t.push({type:f.reference,docs:n.description});continue}let a=this.context.convertBreadcrumbsToName([`${this.id}_${i}`]),l=await new p_i({context:this.context,id:a,breadcrumbs:[...this.breadcrumbs,`oneOf[${i}]`],schema:n}).convert();l!=null&&(t.push({type:this.context.createNamedTypeReference(a),docs:n.description}),r={...r,...l.inlinedTypes,[a]:l.typeDeclaration})}return{type:KO.undiscriminatedUnion({members:t}),inlinedTypes:r}}shouldConvertAsNullableSchemaOrReference(){return this.schema.oneOf!=null?this.schema.oneOf.some(t=>"type"in t&&t.type==="null"):this.schema.anyOf!=null?this.schema.anyOf.some(t=>"type"in t&&t.type==="null"):!1}removeNullFromOneOfOrAnyOf(){let t=this.schema.oneOf??this.schema.anyOf,r=this.schema.oneOf!=null?"oneOf":"anyOf";if(t==null)return;let i=t.filter(n=>!("type"in n&&n.type==="null"));if(i.length===0){this.context.errorCollector.collect({message:`Received ${r} schema with no valid non-null types: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}return i.length===1?{...this.schema,[r]:void 0,...i[0]}:{...this.schema,[r]:i}}async convertAsNullableSchemaOrReference(){let t=this.removeNullFromOneOfOrAnyOf();if(t==null)return;let i=await new zX({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(i==null)return;let n=this.wrapInNullable(i.type);return{type:KO.alias({aliasOf:n,resolvedType:n}),inlinedTypes:i.inlinedTypes}}wrapInNullable(t){return Bf.container(Tv.nullable(t))}};var UEn=class extends w0{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){switch(this.schema.type){case"string":{let t=this.context.getAsString(this.schema.const);return t!=null?Bf.container(Tv.literal(m5.string(t))):Bf.primitive({v1:"STRING",v2:wp.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":case"integer":switch(this.schema.format){case"double":return Bf.primitive({v1:"DOUBLE",v2:wp.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Bf.primitive({v1:"FLOAT",v2:wp.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Bf.primitive({v1:"INTEGER",v2:wp.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Bf.primitive({v1:"LONG",v2:wp.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return Bf.primitive({v1:"UINT",v2:wp.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Bf.primitive({v1:"UINT_64",v2:wp.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Bf.primitive({v1:"INTEGER",v2:wp.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"boolean":{let t=this.context.getAsBoolean(this.schema.const);return t!=null?Bf.container(Tv.literal(m5.boolean(t))):Bf.primitive({v1:"BOOLEAN",v2:wp.boolean({default:this.schema.default})})}default:return}}getNumberValidation(t){return{max:t.maximum,min:t.minimum,exclusiveMax:typeof t.exclusiveMaximum=="boolean"?t.exclusiveMaximum:void 0,exclusiveMin:typeof t.exclusiveMinimum=="boolean"?t.exclusiveMinimum:void 0,multipleOf:t.multipleOf}}getStringValidation(t){return{minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,format:t.format}}};var p_i=class extends w0{schema;id;inlined;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlined:a=!1}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n,this.inlined=a}async convert(){let t=await this.tryConvertFernTypeDeclaration();return t!=null?{typeDeclaration:t,inlinedTypes:{}}:this.convertSchema()}async convertSchema(){if(this.schema.enum?.length){let n=new hne.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),u=new NEn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,maybeFernEnum:n}).convert();if(u!=null)return{typeDeclaration:await this.createTypeDeclaration({shape:u.type}),inlinedTypes:{}}}let r=new UEn({context:this.context,schema:this.schema}).convert();if(r!=null)return{typeDeclaration:await this.createTypeDeclaration({shape:KO.alias({aliasOf:r,resolvedType:r})}),inlinedTypes:{}};if(this.schema.type==="array"){let n=await new VEn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(n!=null)return{typeDeclaration:await this.createTypeDeclaration({shape:KO.alias({aliasOf:n.typeReference,resolvedType:n.typeReference})}),inlinedTypes:n.inlinedTypes}}if(Array.isArray(this.schema.type)&&this.schema.type.length>0){if(this.schema.type.length===1)this.schema.type=this.schema.type[0];else{let i=this.schema.type;this.schema.type=void 0,this.schema.oneOf=i.map(n=>({type:n}))}return this.convertSchema()}if(this.schema.oneOf!=null||this.schema.anyOf!=null){let n=await new LEn({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,inlinedTypes:{}}).convert();if(n!=null)return{typeDeclaration:await this.createTypeDeclaration({shape:n.type}),inlinedTypes:n.inlinedTypes}}if(typeof this.schema.additionalProperties=="object"&&this.schema.additionalProperties!=null&&!this.schema.properties&&!this.schema.allOf){let n=await new KRo({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema.additionalProperties}).convert();if(n!=null)return{typeDeclaration:await this.createTypeDeclaration({shape:n.type}),inlinedTypes:n.inlinedTypes}}if(this.schema.type==="object"||this.schema.properties!=null||this.schema.allOf!=null){let n=await new FEn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(n!=null)return{typeDeclaration:await this.createTypeDeclaration({shape:n.type}),inlinedTypes:n.inlinedTypes}}this.context.errorCollector.collect({message:`Failed to convert schema object: ${JSON.stringify(this.schema,null,2)}`,path:this.breadcrumbs})}async tryConvertFernTypeDeclaration(){let r=new hne.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r!=null){let i=await this.createTypeDeclarationFromFernType({fernType:r});if(i!=null)return i}}async createTypeDeclaration({shape:t}){let r=await this.convertSchemaExamples();return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:await this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:new Set,source:void 0,inline:this.inlined,v2Examples:r}}convertDeclaredTypeName(){return{typeId:this.id,fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(this.id)}}async createTypeDeclarationFromFernType({fernType:t}){let r=vGp(t);if(r!=null)return{name:this.convertDeclaredTypeName(),shape:KO.alias({aliasOf:r,resolvedType:r}),autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:await this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:new Set,source:void 0,inline:this.inlined,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}async convertSchemaExamples(){let t={userSpecifiedExamples:{},autogeneratedExamples:{}},r=this.context.getExamplesFromSchema({schema:this.schema,breadcrumbs:this.breadcrumbs});if(r.length===0){let i=await this.generateOrValidateExample({example:void 0,ignoreErrors:!0});return t.autogeneratedExamples={[`${this.id}_example_autogenerated`]:i},t}return t.userSpecifiedExamples=await this.convertUserSpecifiedExamples(r),t}async convertUserSpecifiedExamples(t){let r={};for(let[i,n]of t.entries()){let a=await this.context.resolveExample(n),u=await this.generateOrValidateExample({example:a});r[`${this.id}_example_${i}`]=u}return r}async generateOrValidateExample({example:t,ignoreErrors:r}){let i=new OZt({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n,errors:a}=await i.convert();return r||a.forEach(u=>{this.context.errorCollector.collect({message:u.message,path:u.path})}),n}};var zX=class extends w0{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:i,schemaIdOverride:n,wrapAsOptional:a=!1,wrapAsNullable:u=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=i,this.schemaIdOverride=n,this.wrapAsOptional=a,this.wrapAsNullable=u}async convert(){return this.context.isReferenceObject(this.schemaOrReference)?this.convertReferenceObject({reference:this.schemaOrReference}):this.convertSchemaObject({schema:this.schemaOrReference})}async convertReferenceObject({reference:t}){let r=await this.context.convertReferenceToTypeReference(t);if(!r.ok){this.context.errorCollector.collect({message:`Failed to convert reference to type reference: ${t.$ref}`,path:this.breadcrumbs});return}return{type:this.wrapTypeReference(r.reference),inlinedTypes:{}}}async convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),i=new p_i({context:this.context,breadcrumbs:this.breadcrumbs,schema:t,id:r}),n=await this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs}),a=await i.convert();if(a!=null){let u=a.typeDeclaration.shape;return u.type==="alias"?{type:this.wrapTypeReference(u.aliasOf),schema:a.typeDeclaration,inlinedTypes:a.inlinedTypes,availability:n}:{type:this.wrapTypeReference(this.context.createNamedTypeReference(r)),schema:a.typeDeclaration,inlinedTypes:{...a.inlinedTypes,[r]:a.typeDeclaration},availability:n}}}wrapTypeReference(t){return this.wrapAsOptional&&this.wrapAsNullable?this.wrapInOptional(this.wrapInNullable(t)):this.wrapAsOptional?this.wrapInOptional(t):this.wrapAsNullable?this.wrapInNullable(t):t}wrapInOptional(t){return Bf.container(Tv.optional(t))}wrapInNullable(t){return Bf.container(Tv.nullable(t))}};var VEn=class e extends w0{static LIST_UNKNOWN=Bf.container(Tv.list(Bf.unknown()));schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}async convert(){if(this.schema.items==null)return{typeReference:e.LIST_UNKNOWN,inlinedTypes:{}};let r=await new zX({context:this.context,breadcrumbs:[...this.breadcrumbs,"items"],schemaOrReference:this.schema.items}).convert();return r!=null?{typeReference:Bf.container(Tv.list(r.type)),inlinedTypes:r.inlinedTypes}:{typeReference:e.LIST_UNKNOWN,inlinedTypes:{}}}};var YRo=class extends w0{group;method;constructor({context:t,breadcrumbs:r,group:i,method:n}){super({context:t,breadcrumbs:r}),this.group=i,this.method=n}async parseMediaTypeObject({mediaTypeObject:t,schemaId:r}){if(t==null||t.schema==null)return;let n=await new zX({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaOrReference:t.schema,schemaIdOverride:r}).convert();if(n==null)return;let a=t.examples!=null?Object.fromEntries(await Promise.all(Object.entries(t.examples).map(async([u,l])=>[u,this.context.isReferenceObject(l)?await this.context.resolveReference(l):l]))):void 0;return{...n,examples:a}}async convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:r,exampleGenerationStrategy:i}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},a=t?.schema,u=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`});for(let[l,f]of u){let s=await this.context.resolveExampleWithValue(f);s!=null&&(a!=null?n.userSpecifiedExamples[l]=await this.generateOrValidateExample({schema:a,example:s,exampleGenerationStrategy:i}):n.userSpecifiedExamples[l]=s)}if(Object.keys(n.userSpecifiedExamples).length===0&&a!=null){let l=`${[...this.group,this.method].join("_")}_example`;n.autogeneratedExamples[l]=await this.generateOrValidateExample({schema:a,example:void 0,ignoreErrors:!0,generateOptionalProperties:r,exampleGenerationStrategy:i})}return n}async generateOrValidateExample({schema:t,example:r,ignoreErrors:i,generateOptionalProperties:n,exampleGenerationStrategy:a}){let u=await this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs});if(u==null)return;let l=this.context.getExamplesFromSchema({schema:u,breadcrumbs:this.breadcrumbs}),f=new OZt({breadcrumbs:this.breadcrumbs,context:this.context,schema:u,example:r??l[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:a}),{validExample:s,errors:o}=await f.convert();return i||o.forEach(c=>{this.context.errorCollector.collect({message:c.message,path:c.path})}),s}};var XRo=class e extends w0{static STRING=Bf.primitive({v1:"STRING",v2:wp.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Bf.container(Tv.optional(e.STRING));parameter;constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r}),this.parameter=i}async convertToOutput({schema:t,typeReference:r,inlinedTypes:i}){let n=await this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??e.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,v2Examples:await this.convertParameterExamples({schema:t}),availability:n},inlinedTypes:i};case"header":return{type:"header",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??e.OPTIONAL_STRING,env:void 0,v2Examples:await this.convertParameterExamples({schema:t}),availability:n},inlinedTypes:i};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:this.parameter.description,valueType:r??e.STRING,location:"ENDPOINT",variable:void 0,v2Examples:await this.convertParameterExamples({schema:t})},inlinedTypes:i};default:return}}async convertParameterExamples({schema:t}){let r={userSpecifiedExamples:{},autogeneratedExamples:{}},i=this.parameter.example,n=this.parameter.examples;for(let[a,u]of Object.entries(n??{})){let l=await this.context.resolveExampleWithValue(u);l!=null&&(r.userSpecifiedExamples[a]=await this.generateOrValidateExample({schema:t,example:l}))}if(i!=null){let a=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(r.userSpecifiedExamples)});r.userSpecifiedExamples[a]=await this.generateOrValidateExample({schema:t,example:i})}if(Object.keys(r.userSpecifiedExamples).length===0){let a=`${this.parameter.name}_example`;r.autogeneratedExamples[a]=await this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0})}return r}async generateOrValidateExample({schema:t,ignoreErrors:r,example:i}){let n=new OZt({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:i}),{validExample:a,errors:u}=await n.convert();return r||u.forEach(l=>{this.context.errorCollector.collect({message:l.message,path:l.path})}),a}};var ZRo=class extends dS{server;key="x-fern-server-name";constructor({breadcrumbs:t,server:r,context:i}){super({breadcrumbs:t,context:i}),this.server=r}convert(){let t=this.getExtensionValue(this.server);if(!(t==null||typeof t!="string"))return t}};var zKs="Base",mZt=class e extends w0{servers;endpointLevelServers;constructor({breadcrumbs:t,context:r,servers:i,endpointLevelServers:n}){super({breadcrumbs:t,context:r}),this.servers=i,this.endpointLevelServers=n}convert(){if(this.servers==null||this.servers.length===0||this.servers[0]==null)return;if(this.endpointLevelServers!=null&&this.endpointLevelServers.length>0){let r={id:zKs,name:this.context.casingsGenerator.generateName(zKs)},i=this.endpointLevelServers.map(u=>{let l=e.getServerName({server:u,context:this.context});return{id:l,name:this.context.casingsGenerator.generateName(l)}}).filter((u,l,f)=>f.findIndex(s=>s.id===u.id)===l),n=[r,...i],a=this.servers.map(u=>{let l=e.getServerName({server:u,context:this.context}),f=this.endpointLevelServers?.map(s=>[e.getServerName({server:s,context:this.context}),this.getServerUrl(s)]);return{id:l,name:this.context.casingsGenerator.generateName(l),urls:{[zKs]:this.getServerUrl(u),...Object.fromEntries(f??[])},docs:u.description}});return{value:{defaultEnvironment:a[0]?.id,environments:yI.multipleBaseUrls({baseUrls:n,environments:a})},defaultUrl:e.getServerName({server:this.servers[0],context:this.context})}}let t=this.withExplodedServers(this.servers).map(r=>{let i=e.getServerName({server:r,context:this.context});return{id:i,name:this.context.casingsGenerator.generateName(i),url:this.getServerUrl(r),docs:r.description}}).filter(g0);return{value:{defaultEnvironment:t[0]?.id,environments:yI.singleBaseUrl({environments:t})}}}static getServerName({server:t,context:r}){return new ZRo({breadcrumbs:[],server:t,context:r}).convert()??t.description??t.url}getServerUrl(t){if(t.variables==null)return t.url;let r=t.url;for(let[i,n]of Object.entries(t.variables))n.default!=null&&(r=r.replace(`{${i}}`,n.default));return r}withExplodedServers(t){return t.flatMap(r=>{if(r.variables==null)return[r];let i=Object.entries(r.variables).filter(([l,f])=>f.enum!=null&&f.enum.length>0);if(i.length===0)return[r];let n=i[0];if(n==null)return[r];let[a,u]=n;return u.enum==null?[r]:u.enum.map(l=>{let f=r.url.replace(`{${a}}`,l),s={};for(let[c,b]of Object.entries(r.variables??{}))c!==a&&(s[c]=b);let o={...r,url:f,variables:Object.keys(s).length>0?s:void 0,"x-fern-server-name":r.description?`${r.description}_${l}`:`${l}`,description:r.description};return this.withExplodedServers([o])[0]})}).filter(g0)}};var WEn=class{errors=[];logger;constructor({logger:t}){this.logger=t}collect(t){this.errors.push(t)}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}logErrors(){for(let t of this.errors)this.logger.log(G0.Info,kie({title:t.message,breadcrumbs:t.path,subtitle:t.path!=null?eh.dim(t.path.join(" -> ")):void 0}))}};var EUD=pu.object({type:pu.string(),channelId:pu.string().optional(),messageId:pu.string(),value:pu.any()}),MUD=pu.object({summary:pu.string().optional(),description:pu.string().optional(),queryParameters:pu.record(pu.string()).optional(),headers:pu.record(pu.string()).optional(),messages:pu.array(EUD)}),bGp=pu.array(MUD);var kRo=class extends dS{channel;key="x-fern-examples";constructor({breadcrumbs:t,channel:r,context:i}){super({breadcrumbs:t??[],context:i}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(t==null)return;let r=bGp.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-examples extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data.map(i=>({summary:i.summary,description:i.description,queryParameters:i.queryParameters,headers:i.headers,messages:i.messages.map(n=>({type:n.type,channelId:n.channelId,messageId:n.messageId,value:n.value}))}))}};var HEn=class extends w0{channel;channelPath;group;inlinedTypes={};constructor({context:t,breadcrumbs:r,channel:i,channelPath:n,group:a}){super({context:t,breadcrumbs:r}),this.channel=i,this.channelPath=n,this.group=a}convertExamples({pathHead:t,baseUrl:r}){let n=new kRo({context:this.context,breadcrumbs:this.breadcrumbs,channel:this.channel}).convert();return n==null?{}:Object.fromEntries(n.map((a,u)=>[u.toString(),{channel:{method:"GET",path:t},baseUrl:void 0,environment:r,auth:void 0,pathParameters:{userSpecifiedExamples:{},autogeneratedExamples:{}},queryParameters:{userSpecifiedExamples:a.queryParameters??{},autogeneratedExamples:{}},headers:{userSpecifiedExamples:a.headers??{},autogeneratedExamples:{}},messages:a.messages.map(l=>({type:l.messageId,body:l.value}))}]))}transformToValidPath(t){return t.startsWith("/")?t:"/"+t}};var __i=class extends hA.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r,parameter:i})}async convert(){let t,r={},n=new hne.FernOptionalExtension({breadcrumbs:this.breadcrumbs,parameter:this.parameter,context:this.context}).convert()??this.parameter.required??!1,a=this.parameter.schema??{...this.parameter,type:"string",enum:this.parameter.enum,default:this.parameter.default,example:this.parameter.example,examples:Object.values(this.parameter.examples??{}),required:void 0},l=await new hA.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaIdOverride:this.parameter.name,schemaOrReference:a,wrapAsOptional:n}).convert();return l!=null&&(t=l.type,r=l.inlinedTypes??{}),this.convertToOutput({schema:a,typeReference:t,inlinedTypes:r})}};var eNo=class extends dS{channel;key="x-fern-address";constructor({breadcrumbs:t,channel:r,context:i}){super({breadcrumbs:t,context:i}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(!(t==null||typeof t!="string"))return t}};var $En=class extends dS{channel;key="x-fern-display-name";constructor({breadcrumbs:t,channel:r,context:i}){super({breadcrumbs:t,context:i}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(!(t==null||typeof t!="string"))return t}};var tNo=class extends HEn{inlinedTypes={};constructor({context:t,breadcrumbs:r,channel:i,channelPath:n,group:a}){super({context:t,breadcrumbs:r,channel:i,channelPath:n,group:a})}async convert(){let t=[],r=[],i=[],a=new $En({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert()??this.channelPath;this.channel.parameters&&await this.convertQueryParameters({context:this.context,queryParameters:r}),this.channel.bindings?.ws!=null&&(await this.convertHeaders({context:this.context,headers:i}),await this.convertBindingQueryParameters({context:this.context,queryParameters:r}));let u;this.channel.subscribe!=null&&(u=await this.convertMessage({context:this.context,operation:this.channel.subscribe,origin:"server"}));let l;this.channel.publish!=null&&(l=await this.convertMessage({context:this.context,operation:this.channel.publish,origin:"client"}));let f=[];u!=null&&f.push(u),l!=null&&f.push(l);let o=new eNo({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert(),c=this.channel.servers?.[0]??Object.keys(this.context.spec.servers??{})[0],b=o??this.transformToValidPath(this.channelPath),g=$y(this.channelPath);return{channel:{name:this.context.casingsGenerator.generateName(g),displayName:a,baseUrl:c,path:{head:b,parts:[]},auth:!1,headers:i,queryParameters:r,pathParameters:t,messages:f,availability:await this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({pathHead:b,baseUrl:c})}},inlinedTypes:this.inlinedTypes}}async convertMessage({context:t,operation:r,origin:i}){let n,a=i==="server"?"subscribe":"publish",u=[...this.breadcrumbs,a],l=await t.resolveMaybeReference({schemaOrReference:r.message,breadcrumbs:u});l!=null&&(r.message=l);let f=TCi($y(`${this.channelPath}_${a}`)).replace(/ /g,"");if("oneOf"in r.message){let o=await new hA.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:u,schemaOrReference:r.message,schemaIdOverride:f}).convert();o!=null&&o.schema!=null&&(n=o.schema,this.inlinedTypes={...this.inlinedTypes,...o.inlinedTypes})}else if(t.isMessageWithPayload(r.message)){let s=await t.resolveMaybeReference({schemaOrReference:r.message.payload,breadcrumbs:u});if(s!=null){let c=await new hA.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:u,schemaOrReference:s,schemaIdOverride:f}).convert();c!=null&&c.schema!=null&&(n=c.schema,this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes})}}if(n!=null){let s=n,o=Bf.named({fernFilepath:t.createFernFilepath(),name:s.name.name,typeId:s.name.typeId,default:void 0,inline:!1}),c=P5.reference({bodyType:o,docs:r.description}),b=i==="server"?"subscribe":"publish";return{type:b,displayName:b,origin:i,body:c,availability:await t.getAvailability({node:r,breadcrumbs:this.breadcrumbs}),docs:r.description}}}async convertQueryParameters({context:t,queryParameters:r}){for(let[i,n]of Object.entries(this.channel.parameters??{})){let a=await t.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs});if(a==null)continue;let l=await new __i({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...a,name:i,in:"query",description:n.description,required:n.required??!1}}).convert();l!=null&&(this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes},l.type==="query"&&r.push(l.parameter))}}async convertHeaders({context:t,headers:r}){if(this.channel.bindings?.ws?.headers!=null){let i=this.channel.bindings.ws.headers.required??[];for(let[n,a]of Object.entries(this.channel.bindings.ws.headers.properties??{})){let u=await t.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,n]});if(u==null)continue;let f=await new __i({context:this.context,breadcrumbs:[...this.breadcrumbs,n],parameter:{name:n,in:"header",required:i.includes(n),schema:u,description:"description"in u?u.description:void 0}}).convert();f!=null&&f.type==="header"&&(this.inlinedTypes={...this.inlinedTypes,...f.inlinedTypes},r.push(f.parameter))}}}async convertBindingQueryParameters({context:t,queryParameters:r}){if(this.channel.bindings?.ws?.query!=null){let i=this.channel.bindings.ws.query.required??[];for(let[n,a]of Object.entries(this.channel.bindings.ws.query.properties??{})){let u=await t.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,n]});if(u==null)continue;let f=await new __i({context:this.context,breadcrumbs:[...this.breadcrumbs,n],parameter:{name:n,in:"query",required:i.includes(n),schema:u,description:"description"in u?u.description:void 0}}).convert();f!=null&&f.type==="query"&&(this.inlinedTypes={...this.inlinedTypes,...f.inlinedTypes},r.push(f.parameter))}}}};var GEn=class extends w0{servers;constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r}),this.servers=i}convert(){if(this.servers==null||Object.keys(this.servers).length===0)return;let t=[],r;for(let[i,n]of Object.entries(this.servers)){let a=this.buildSingleBaseUrlEnvironment(this.context,i,n);t.push(a),r==null&&(r=a.id)}return{defaultEnvironment:r,environments:yI.singleBaseUrl({environments:t})}}constructServerUrl(t,r){return r.includes("://")?r:`${t}://${r}`}};var rNo=class extends GEn{constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r,servers:i})}buildSingleBaseUrlEnvironment(t,r,i){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(i.protocol,i.url),docs:void 0}}};var RKs="$message.",gGp="#/channels/",OGp="#/servers/",iNo=class extends HEn{operations;inlinedTypes={};constructor({context:t,breadcrumbs:r,channel:i,channelPath:n,operations:a,group:u}){super({context:t,breadcrumbs:r,channel:i,channelPath:n,group:u}),this.operations=a}async convert(){let t=[],r=[],i=[],a=new $En({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert()??this.channelPath;this.channel.parameters&&await this.convertChannelParameters({pathParameters:t,queryParameters:r,headers:i});let u=Object.entries(this.operations).reduce((o,[c,b])=>{try{this.getChannelPathFromOperation(b)===this.channelPath&&(o[c]=b)}catch{}return o},{}),l=[];for(let[o,c]of Object.entries(u))for(let b of c.messages){let g=await this.context.convertReferenceToTypeReference(b);if(g.ok){let O=P5.reference({bodyType:g.reference,docs:c.description});l.push({type:o,displayName:o,origin:c.action==="send"?"client":"server",body:O,availability:await this.context.getAvailability({node:c,breadcrumbs:this.breadcrumbs}),docs:c.description})}}let f=this.resolveChannelServersFromReference(this.channel.servers??[])??Object.keys(this.context.spec.servers??{})[0],s=this.transformToValidPath(this.channel.address??this.channelPath);return{channel:{name:this.context.casingsGenerator.generateName(a),displayName:a,baseUrl:f,path:{head:s,parts:[]},auth:!1,headers:i,queryParameters:r,pathParameters:t,messages:l,availability:await this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({pathHead:s,baseUrl:f})}},inlinedTypes:this.inlinedTypes}}async convertChannelParameters({pathParameters:t,queryParameters:r,headers:i}){for(let n of Object.values(this.channel.parameters??{})){let a=await this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:[...this.breadcrumbs,"parameters"]});if(a==null)continue;let u=this.convertChannelParameterLocation(n.location);if(u==null)continue;let{type:l,parameterKey:f}=u,o=await new __i({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...a,name:f,in:l}}).convert();if(o!=null)switch(this.inlinedTypes={...this.inlinedTypes,...o.inlinedTypes},o.type){case"path":t.push(o.parameter);break;case"query":r.push(o.parameter);break;case"header":i.push(o.parameter);break}}}convertChannelParameterLocation(t){try{let[r,i]=t.split("#/");if(r==null||i==null){this.context.errorCollector.collect({message:`Invalid location format: ${t}; unable to parse message type and parameter key`,path:this.breadcrumbs});return}if(!r.startsWith(RKs)){this.context.errorCollector.collect({message:`Invalid location format: ${t}; expected ${RKs} prefix`,path:this.breadcrumbs});return}let n=r.substring(RKs.length);if(n!=="header"&&n!=="path"&&n!=="payload"){this.context.errorCollector.collect({message:`Invalid message type: ${n}. Must be one of: header, path, payload`,path:this.breadcrumbs});return}return n==="payload"?{type:"query",parameterKey:i}:{type:n,parameterKey:i}}catch{this.context.errorCollector.collect({message:`Invalid location format: ${t}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`,path:this.breadcrumbs});return}}resolveChannelServersFromReference(t){if(t==null||t.length===0||t[0]==null)return;let r=t[0];if(!r.$ref.startsWith(OGp)){this.context.errorCollector.collect({message:`Failed to resolve server name from server ref ${r.$ref}`,path:this.breadcrumbs});return}let i=r.$ref.substring(OGp.length);if(i==null){this.context.errorCollector.collect({message:`Failed to find server with name ${i}`,path:this.breadcrumbs});return}return i}getChannelPathFromOperation(t){if(!t.channel.$ref.startsWith(gGp))throw new Error(`Failed to resolve channel path from operation ${t.channel.$ref}`);return t.channel.$ref.substring(gGp.length)}};var nNo=class extends GEn{constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r,servers:i})}buildSingleBaseUrlEnvironment(t,r,i){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(i.protocol,i.host),docs:void 0}}};var kva=class extends w0{constructor({context:t,breadcrumbs:r}){super({context:t,breadcrumbs:r})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec,context:this.context}),this.context.spec=await this.resolveExternalRefs({spec:this.context.spec,context:this.context}),this.isAsyncAPIV3(this.context)?await this.convertChannelMessages():await this.convertComponentMessages(),await this.convertSchemas(),await this.convertServers(),await this.convertChannels();let t={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}};return t={...t,...bYr({ir:t,exampleGeneration:this.context.exampleGenerationArgs}),...SFi({ir:t,exampleGeneration:this.context.exampleGenerationArgs})},t}isAsyncAPIV3(t){return parseFloat(t.spec.asyncapi)>=3}async convertChannelMessages(){let t=this.context.spec;for(let[r,i]of Object.entries(t.channels??{}))for(let[n,a]of Object.entries(i.messages??{})){if(!this.context.isMessageWithPayload(a)&&!this.context.isReferenceObject(a))continue;let u=["channels",r,"messages",n],l=await this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:u});if(!this.context.isMessageWithPayload(l))continue;let f=await this.context.resolveMaybeReference({schemaOrReference:l.payload,breadcrumbs:u});if(f==null)continue;let s=`${r}_${n}`;await this.convertSchema({id:s,breadcrumbs:u,schema:f})}}async convertComponentMessages(){for(let[t,r]of Object.entries(this.context.spec.components?.messages??{})){if(r.payload==null)continue;let i=["components","messages",t],n=await this.context.resolveMaybeReference({schemaOrReference:r.payload,breadcrumbs:i});n!=null&&await this.convertSchema({id:t,breadcrumbs:i,schema:n})}}async convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{}))await this.convertSchema({id:t,breadcrumbs:["components","schemas",t],schema:r})}async convertSchema({id:t,breadcrumbs:r,schema:i}){let a=await new hA.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:r,schema:i}).convert();a!=null&&(this.ir.rootPackage.types.push(t),this.ir.types={...this.ir.types,...a.inlinedTypes,[t]:a.typeDeclaration})}async convertServers(){if(this.isAsyncAPIV3(this.context)){let t=this.context.spec.servers,i=new nNo({context:this.context,breadcrumbs:["servers"],servers:t}).convert();i!=null&&(this.ir.environments=i)}else{let t=this.context.spec.servers,i=new rNo({context:this.context,breadcrumbs:["servers"],servers:t}).convert();i!=null&&(this.ir.environments=i)}}async convertChannels(){for(let[t,r]of Object.entries(this.context.spec.channels??{})){let n=new hne.SdkGroupNameExtension({breadcrumbs:["channels",t],operation:r,context:this.context}).convert()?.groups,a;if(this.isAsyncAPIV3(this.context)){let l=this.context.spec.operations??{};a=await new iNo({context:this.context,breadcrumbs:["channels",t],channel:r,channelPath:t,operations:l,group:n}).convert()}else a=await new tNo({context:this.context,breadcrumbs:["channels",t],channel:r,channelPath:t,group:n}).convert();if(a!=null){let u=`channel_${$y(t)}`;this.ir.websocketChannels={...this.ir.websocketChannels,[n?n.join("."):u]:a.channel},this.ir.types={...this.ir.types,...a.inlinedTypes}}}this.addWebsocketsToIr({websocketChannels:this.ir.websocketChannels})}addWebsocketsToIr({websocketChannels:t}){if(t!=null)for(let[r,i]of Object.entries(t))if(r!==""){let n=r.replace("channel_",""),a=r.replace("channel_","subpackage_");this.ir.subpackages[a]==null&&(this.ir.subpackages[a]={name:this.context.casingsGenerator.generateName(n),...this.context.createPackage({name:n})}),this.ir.subpackages[a].websocket=r,this.ir.rootPackage.subpackages.push(a)}else this.ir.rootPackage.websocket=""}};var eba=class extends k2{isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}getTypeIdFromMessageReference(t){let r=t.$ref.match(/\/messages\/(.+)$/);if(!(!r||!r[1]))return r[1]}async convertReferenceToTypeReference(t){let r,i=t.$ref.match(/^.*\/schemas\/(.+)$/),n=t.$ref.match(/^.*\/channels\/([^/]+)\/messages\/(.+)$/),a=t.$ref.match(/^.*\/messages\/(.+)$/);if(i&&i[1])r=i[1];else if(n&&n[2]){let l=n[1],f=n[2];r=`${l}_${f}`}else a&&a[1]&&(r=a[1]);return r==null?{ok:!1}:(await this.resolveReference(t)).resolved?{ok:!0,reference:Bf.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(r),typeId:r,default:void 0,inline:!1})}:{ok:!1}}};var jGp=li(NKs(),1);var UKs=li(NKs(),1);var mGp=["get","post","put","delete","patch"];var aNo=class extends dS{operation;key="x-fern-idempotent";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-idempotent",path:this.breadcrumbs});return}return t}}};var TUD=pu.object({cursor:pu.string(),next_cursor:pu.string(),results:pu.string()}),CUD=pu.object({offset:pu.string(),results:pu.string(),step:pu.string().optional(),"has-next-page":pu.string().optional()}),FKs=pu.union([pu.boolean(),TUD,CUD]);var LKs="$request.",oNo="$response.",uNo=class extends dS{operation;document;key="x-fern-pagination";constructor({breadcrumbs:t,operation:r,document:i,context:n}){super({breadcrumbs:t,context:n}),this.operation=r,this.document=i}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=FKs.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean"){let i=this.getExtensionValue(this.document);if(i==null)return;if(typeof i=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.",path:this.breadcrumbs});return}let n=FKs.safeParse(i);if(!n.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${n.error.message}`,path:this.breadcrumbs});return}if(typeof n.data=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:n.data})}if(typeof r.data=="boolean"){this.context.errorCollector.collect({message:"Pagination extension is a boolean with no global configuration.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:r.data})}convertPaginationConfig({config:t}){let r=t;if("cursor"in r)return{type:"cursor",cursor:k2.maybeTrimPrefix(r.cursor,LKs),nextCursor:k2.maybeTrimPrefix(r.next_cursor,oNo),results:k2.maybeTrimPrefix(r.results,oNo)};let i=t;return{type:"offset",offset:k2.maybeTrimPrefix(i.offset,LKs),results:k2.maybeTrimPrefix(i.results,oNo),step:i.step!=null?k2.maybeTrimPrefix(i.step,LKs):void 0,hasNextPage:i["has-next-page"]!=null?k2.maybeTrimPrefix(i["has-next-page"],oNo):void 0}}};var BUD="$request.",xUD=pu.object({"stream-condition":pu.string().optional(),format:pu.enum(["sse","json"]).optional(),"stream-description":pu.string().optional(),"response-stream":pu.any(),response:pu.any()}),IUD=pu.union([pu.boolean(),xUD]),QEn=class extends dS{operation;key="x-fern-streaming";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=IUD.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-streaming extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean")return r.data?{type:"stream",format:"json"}:void 0;if(r.data["stream-condition"]==null&&r.data.format!=null)return{type:"stream",format:r.data.format};if(r.data["stream-condition"]==null){this.context.errorCollector.collect({message:"Missing required stream-condition property",path:this.breadcrumbs});return}return{type:"streamCondition",format:r.data.format??"json",streamDescription:r.data["stream-description"],streamConditionProperty:k2.maybeTrimPrefix(r.data["stream-condition"],BUD),responseStream:r.data["response-stream"],response:r.data.response}}};var sNo=class extends dS{operation;key="x-fern-webhook";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-webhook",path:this.breadcrumbs});return}return t}}};var cNo=class extends dS{operation;key="x-fern-examples";constructor({context:t,breadcrumbs:r,operation:i}){super({breadcrumbs:r,context:t}),this.operation=i}convert(){let t=this.getExtensionValue(this.operation);return t==null?void 0:(Array.isArray(t)?t:[]).filter(n=>{let a=cF.serialization.ExampleEndpointCallSchema.parse(n);return a.ok||this.context.errorCollector.collect({message:`Failed to parse x-fern-example in ${this.breadcrumbs.join(".")}`,path:this.breadcrumbs}),a.ok})}};var tba=class extends hA.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r,parameter:i})}async convert(){let t,r={};if(this.parameter.schema!=null){let n=await new hA.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required}).convert();n!=null&&(t=n.type,r=n.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}};var lNo=class extends hA.AbstractConverters.AbstractMediaTypeObjectConverter{requestBody;constructor({context:t,breadcrumbs:r,requestBody:i,group:n,method:a}){super({context:t,breadcrumbs:r,group:n,method:a}),this.requestBody=i}async convert(){if(!this.requestBody.content)return;let t=Object.keys(this.requestBody.content).filter(n=>n.includes("json"));for(let n of t){let a=this.handleJsonOrFormContent({contentType:n});if(a!=null)return a}let r=Object.keys(this.requestBody.content).filter(n=>n.includes("multipart"));for(let n of r){let a=this.requestBody.content[n],u=[...this.group,this.method,"Request"].join("_"),l=await this.parseMediaTypeObject({mediaTypeObject:a,schemaId:u});if(l!=null&&l.schema?.shape.type==="object")return{requestBody:FC.fileUpload({contentType:n,docs:this.requestBody.description,name:this.context.casingsGenerator.generateName(u),properties:l.schema?.shape.properties.map(s=>this.convertRequestBodyProperty({property:s,contentType:n})),v2Examples:await this.convertMediaTypeObjectExamples({mediaTypeObject:a,exampleGenerationStrategy:"request"})}),inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:u,inlinedTypes:l.inlinedTypes}),examples:l.examples}}let i=Object.keys(this.requestBody.content).filter(n=>n.includes("urlencoded"));for(let n of i){let a=this.handleJsonOrFormContent({contentType:n});if(a!=null)return a}}async handleJsonOrFormContent({contentType:t}){let r=[...this.group,this.method,"Request"].join("_"),i=this.requestBody.content[t],n=await this.parseMediaTypeObject({mediaTypeObject:i,schemaId:r});if(n!=null)return n.schema?.shape.type==="object"?{requestBody:FC.inlinedRequestBody({contentType:t,docs:this.requestBody.description,name:this.context.casingsGenerator.generateName(r),extendedProperties:n.schema?.shape.extendedProperties,extends:n.schema?.shape.extends,properties:n.schema?.shape.properties,extraProperties:n.schema?.shape.extraProperties,v2Examples:await this.convertMediaTypeObjectExamples({mediaTypeObject:i,exampleGenerationStrategy:"request"})}),inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:r,inlinedTypes:n.inlinedTypes})}:{requestBody:FC.reference({contentType:t,docs:this.requestBody.description,requestBodyType:n.type,v2Examples:await this.convertMediaTypeObjectExamples({mediaTypeObject:i,exampleGenerationStrategy:"request"})}),inlinedTypes:n.inlinedTypes??{}}}convertRequestBodyProperty({property:t,contentType:r}){let{isFile:i,isOptional:n,isArray:a}=this.recursivelyCheckTypeReferenceIsFile({typeReference:t.valueType});return i?a?O5.file(Zre.fileArray({key:t.name,isOptional:n,contentType:r,docs:t.docs})):O5.file(Zre.file({key:t.name,isOptional:n,contentType:r,docs:t.docs})):O5.bodyProperty({...t,contentType:r,style:void 0,name:t.name})}recursivelyCheckTypeReferenceIsFile({typeReference:t,isOptional:r,isArray:i}){return this.context.isList(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.list,isOptional:r,isArray:!0}):this.context.isOptional(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.optional,isOptional:!0,isArray:i}):this.context.isNullable(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.nullable,isOptional:r,isArray:i}):this.context.isFile(t)?{isFile:!0,isOptional:r??!1,isArray:i??!1}:{isFile:!1,isOptional:r??!1,isArray:i??!1}}};var fNo=class extends hA.AbstractConverters.AbstractMediaTypeObjectConverter{responseBody;statusCode;streamingExtension;constructor({context:t,breadcrumbs:r,responseBody:i,group:n,method:a,statusCode:u,streamingExtension:l}){super({context:t,breadcrumbs:r,group:n,method:a}),this.responseBody=i,this.statusCode=u,this.streamingExtension=l}async convert(){let t=Object.keys(this.responseBody.content??{}).filter(n=>n.includes("json")),r=[...this.group,this.method,"Response",this.statusCode].join("_");for(let n of[...t]){let a=this.responseBody.content?.[n],u=await this.parseMediaTypeObject({mediaTypeObject:a,schemaId:r});if(u!=null&&n.includes("json"))return{responseBody:SM.json(GY.response({responseBodyType:u.type,docs:this.responseBody.description,v2Examples:await this.convertMediaTypeObjectExamples({mediaTypeObject:a,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),inlinedTypes:u.inlinedTypes,examples:u.examples}}let i=Object.keys(this.responseBody.content??{}).filter(n=>!n.includes("json"));for(let n of i){let a=this.responseBody.content?.[n],u=await this.parseMediaTypeObject({mediaTypeObject:a,schemaId:r});if(u!=null&&this.isBinarySchema(u))return this.context.settings?.useBytesForBinaryResponse&&this.streamingExtension==null?{responseBody:SM.bytes({docs:this.responseBody.description,v2Examples:await this.convertMediaTypeObjectExamples({mediaTypeObject:a,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),inlinedTypes:{}}:{responseBody:SM.fileDownload({docs:this.responseBody.description,v2Examples:await this.convertMediaTypeObjectExamples({mediaTypeObject:a,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),inlinedTypes:{}}}}isBinarySchema(t){let r=t.type;switch(r.type){case"container":case"named":case"unknown":return!1;case"primitive":return r.primitive.v2==null?!1:r.primitive.v2.type==="string"&&r.primitive.v2.validation?.format==="binary";default:return!1}}};var dNo=class extends hA.AbstractConverters.AbstractMediaTypeObjectConverter{responseError;statusCode;constructor({context:t,breadcrumbs:r,responseError:i,group:n,method:a,statusCode:u}){super({context:t,breadcrumbs:r,group:n,method:a}),this.responseError=i,this.statusCode=u}async convert(){if(!this.responseError.content)return;let t=Object.keys(this.responseError.content).filter(i=>i.includes("json")),r=[...this.group,this.method,"Response",this.statusCode].join("_");for(let i of[...t]){let n=this.responseError.content?.[i],a=await this.parseMediaTypeObject({mediaTypeObject:n,schemaId:r});if(a!=null){if(a.schema!=null)return{error:{error:{...a.schema?.name,errorId:a.schema?.name.typeId},docs:this.responseError.description},inlinedTypes:a.inlinedTypes,examples:a.examples};if(a.type.type==="named")return{error:{error:{name:a.type.name,errorId:a.type.typeId,fernFilepath:a.type.fernFilepath},docs:this.responseError.description},inlinedTypes:a.inlinedTypes,examples:a.examples}}}}};var zUD=/{([^}]+)}/g,JEn=class extends w0{operation;method;path;inlinedTypes={};constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a}){super({context:t,breadcrumbs:r}),this.operation=i,this.method=n,this.path=a}convertHttpMethod(){switch(this.method){case"get":return S7.Get;case"post":return S7.Post;case"put":return S7.Put;case"delete":return S7.Delete;case"patch":return S7.Patch;default:return}}async convertParameters({breadcrumbs:t}){let r=[],i=[],n=[];if(!this.operation.parameters)return{pathParameters:r,queryParameters:i,headers:n};for(let l of this.operation.parameters){let f=await this.context.resolveMaybeReference({schemaOrReference:l,breadcrumbs:t});if(f==null)continue;let o=await new tba({context:this.context,breadcrumbs:t,parameter:f}).convert();if(o!=null)switch(this.inlinedTypes={...this.inlinedTypes,...o.inlinedTypes},o.type){case"path":r.push(o.parameter);break;case"query":i.push(o.parameter);break;case"header":n.push(o.parameter);break}}let u=[...this.path.matchAll(zUD)].map(l=>l[1]).filter(l=>!r.some(f=>f.name.originalName===l));for(let l of u){if(l==null)continue;let f=`${l}_example`;r.push({name:this.context.casingsGenerator.generateName(l),valueType:tba.STRING,docs:void 0,location:"ENDPOINT",variable:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{[f]:await this.generateStringParameterExample({example:void 0})}}})}return{pathParameters:r,queryParameters:i,headers:n}}async convertRequestBody({breadcrumbs:t,group:r,method:i}){if(this.operation.requestBody==null)return;let n=await this.context.resolveMaybeReference({schemaOrReference:this.operation.requestBody,breadcrumbs:t});if(n==null)return null;let u=await new lNo({context:this.context,breadcrumbs:t,requestBody:n,group:r??[],method:i}).convert();if(u!=null)return this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes},{value:u.requestBody,examples:u.examples}}async convertResponseBody({breadcrumbs:t,group:r,method:i,streamingExtension:n}){if(this.operation.responses==null)return;let a,u=!1;for(let[l,f]of Object.entries(this.operation.responses)){let s=parseInt(l);if(!(isNaN(s)||s<200||s>=300&&s<400)){if(a==null&&(a={value:void 0,errors:[],examples:{}}),s>=200&&s<300&&!u){let o=await this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:[...t,l]});if(o==null)continue;let b=await new fNo({context:this.context,breadcrumbs:[...t,l],responseBody:o,group:r??[],method:i,statusCode:l,streamingExtension:n}).convert();b!=null&&(u=!0,this.inlinedTypes={...this.inlinedTypes,...b.inlinedTypes},a.value={statusCode:s,body:b.responseBody})}if(s>=400&&s<500){let o=await this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:[...t,l]});if(o==null)continue;let b=await new dNo({context:this.context,breadcrumbs:[...t,l],responseError:o,group:r??[],method:i,statusCode:l}).convert();b!=null&&(this.inlinedTypes={...this.inlinedTypes,...b.inlinedTypes},a.errors.push(b.error))}}}return a}computeGroupNameAndLocationFromExtensions(){let r=new hne.SdkMethodNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.methodName,n=new hne.SdkGroupNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.groups??[];if(r!=null)return{group:n,method:r}}computeGroupNameFromTagAndOperationId(){let t=this.operation.tags?.[0],r=this.operation.operationId;if(r==null){let a=this.operation.summary!=null?$y(this.operation.summary):$y(`${this.method}_${this.path.split("/").join("_")}`);return t!=null?{group:[t],method:a}:{method:a}}if(t==null)return{method:r};let i=PGp(t),n=PGp(r);return hSe(i,n)?{method:t}:this.computeGroupAndMethodFromTokens({tag:t,tagTokens:i,operationId:r,operationIdTokens:n})}computeGroupAndMethodFromTokens({tag:t,tagTokens:r,operationId:i,operationIdTokens:n}){if(r.some((l,f)=>l!==n[f]))return{group:[t],method:i};let u=n.slice(r.length);return{group:[t],method:$y(u.join("_"))}}async generateStringParameterExample({example:t}){let r=new hA.ExampleConverter({breadcrumbs:this.breadcrumbs,context:this.context,schema:{type:"string"},example:t}),{validExample:i}=await r.convert();return i}};function PGp(e){let t=RUD(e)?NUD(e):FUD(e);return t=t.map(r=>r.toLowerCase()),t=exe(t),t}function RUD(e){return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)}function NUD(e){return e.split(/(?=[A-Z])/)}function FUD(e){return e.split(/[^a-zA-Z0-9]+/)}var pNo=class e extends JEn{idempotent;servers;streamingExtensionConverter;idToAuthScheme;static AUTHORIZATION_HEADER="Authorization";constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a,idempotent:u,servers:l,idToAuthScheme:f}){super({context:t,breadcrumbs:r,operation:i,method:n,path:a}),this.idempotent=u,this.servers=l,this.idToAuthScheme=f,this.streamingExtensionConverter=new QEn({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context})}async convert(){let t=this.convertHttpMethod();if(t==null)return;let{group:r,method:i}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),n=this.streamingExtensionConverter.convert(),{headers:a,pathParameters:u,queryParameters:l}=await this.convertParameters({breadcrumbs:[...this.breadcrumbs,"parameters"]}),f=await this.convertRequestBody({breadcrumbs:[...this.breadcrumbs,"requestBody"],group:r,method:i}),s=f?.value,o=await this.convertResponseBody({breadcrumbs:[...this.breadcrumbs,"responses"],group:r,method:i,streamingExtension:n}),c=o?.value,b=o!=null?o.errors:[],g=this.operation.servers?.[0]??this.servers?.[0]??this.context.spec.servers?.[0],O=[];this.context.namespace!=null&&O.push(this.context.namespace),O.push(...r??[]),O.push(i);let m=k7(this.path),P=g!=null?mZt.getServerName({server:g,context:this.context}):void 0,E=this.convertExamples({pathHead:m.head,httpMethod:t,baseUrl:P}),q=new Set(this.operation.security?.flatMap(D=>Object.keys(D))??[]),A=this.authSchemeToHeaders(Array.from(q));return A.length>0&&a.push(...A),{group:r,errors:{},endpoint:{id:O.join("."),displayName:this.operation.summary,method:t,name:this.context.casingsGenerator.generateName(i),baseUrl:P,path:m,pathParameters:u,queryParameters:l,headers:a.filter((D,C,z)=>C===z.findIndex($=>$.name.wireValue===D.name.wireValue)),requestBody:s,sdkRequest:void 0,response:c,errors:b,auth:this.operation.security!=null||this.context.spec.security!=null,availability:await this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),docs:this.operation.description,userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:this.idempotent??!1,basePath:void 0,fullPath:m,allPathParameters:u,pagination:void 0,transport:void 0,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:E},source:Xre.openapi()},inlinedTypes:this.inlinedTypes,servers:this.operation.servers?.filter(D=>!this.context.spec.servers?.some(C=>C.url===D.url))}}authSchemeToHeaders(t){let r=[];for(let i of t){let n=this.idToAuthScheme?.[i];if(n!=null)switch(n.type){case"bearer":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},valueType:w0.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0});break;case"basic":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},valueType:w0.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0});break;case"header":r.push({name:n.name,valueType:w0.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0});break}}return r}convertExamples({pathHead:t,httpMethod:r,baseUrl:i}){let a=new cNo({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation}).convert();return a==null?{}:Object.fromEntries(a.map((u,l)=>[u.id??l.toString(),{request:{docs:void 0,endpoint:{method:r,path:t},baseUrl:void 0,environment:i,auth:void 0,pathParameters:u["path-parameters"]??{},queryParameters:u["query-parameters"]??{},headers:u.headers??{},requestBody:u.request},response:{docs:void 0,statusCode:void 0,body:Ks.V2HttpEndpointResponseBody.json(u.response)},codeSamples:u["code-samples"]?.map(f=>({docs:void 0,language:("language"in f?f.language:f.sdk)??void 0,code:f.code}))}]))}};var KEn=class extends JEn{constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a}){super({context:t,breadcrumbs:r,operation:i,method:n,path:a})}async convert(){if(this.operation.requestBody==null){this.context.errorCollector.collect({message:"Skipping webhook because no request body present",path:this.breadcrumbs});return}let t=this.convertHttpMethod();if(t==null)return;if(t!=="POST"&&t!=="GET"){this.context.errorCollector.collect({message:"Skipping webhook because non-POST or GET method",path:this.breadcrumbs});return}let{group:r,method:i}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),n=[...this.breadcrumbs,"Payload"],{headers:a,pathParameters:u,queryParameters:l}=await this.convertParameters({breadcrumbs:n}),f=await this.convertRequestBody({breadcrumbs:n,group:r,method:i}),s;if(f?.value.type==="inlinedRequestBody")s=aV.inlinedPayload({name:f.value.name,extends:f.value.extends,properties:f.value.properties});else if(f?.value.type==="reference")s=aV.reference({payloadType:f.value.requestBodyType,docs:f.value.docs});else return;return{group:r,webhook:{id:`${r?.join(".")??""}.${i}`,name:this.context.casingsGenerator.generateName(i),displayName:this.operation.summary,method:t,headers:a,payload:s,examples:[],availability:await this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),docs:this.operation.description,v2Examples:void 0},inlinedTypes:this.inlinedTypes}}};var _No=class extends w0{pathItem;path;servers;idToAuthScheme;constructor({context:t,breadcrumbs:r,pathItem:i,path:n,servers:a,idToAuthScheme:u}){super({context:t,breadcrumbs:r}),this.pathItem=i,this.path=n,this.servers=a,this.idToAuthScheme=u}async convert(){let t=[],r=[],i={};for(let n of mGp){let a=this.pathItem[n];if(a==null)continue;let u=[...this.breadcrumbs,n],l=await this.tryParseAsWebhook({operationBreadcrumbs:u,operation:a,method:n,context:this.context});if(l!=null){r.push(l),Object.assign(i,l.inlinedTypes);continue}new QEn({breadcrumbs:u,operation:a,context:this.context}).convert()!=null;let o=await this.tryParseAsHttpEndpoint({operationBreadcrumbs:u,operation:a,method:n});o!=null&&(t.push(o),Object.assign(i,o.inlinedTypes))}return{endpoints:t,webhooks:r,inlinedTypes:i}}async tryParseAsWebhook({operation:t,method:r,operationBreadcrumbs:i,context:n}){return new sNo({breadcrumbs:i,operation:t,context:n}).convert()?await new KEn({context:this.context,breadcrumbs:i,operation:t,method:UKs.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path}).convert():void 0}async tryParseAsHttpEndpoint({operation:t,method:r,operationBreadcrumbs:i}){new uNo({breadcrumbs:i,operation:t,document:this.context.spec,context:this.context}).convert()!=null;let l=new aNo({breadcrumbs:i,operation:t,context:this.context}).convert();return await new pNo({context:this.context,breadcrumbs:i,operation:t,method:UKs.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,idempotent:l,idToAuthScheme:this.idToAuthScheme}).convert()}};var hNo=class extends w0{securityScheme;constructor({context:t,breadcrumbs:r,securityScheme:i}){super({context:t,breadcrumbs:r}),this.securityScheme=i}convert(){switch(this.securityScheme.type){case"http":{if(this.securityScheme.scheme==="bearer")return NC.bearer({token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:this.securityScheme.description});if(this.securityScheme.scheme==="basic")return NC.basic({username:this.context.casingsGenerator.generateName("username"),password:this.context.casingsGenerator.generateName("password"),usernameEnvVar:void 0,passwordEnvVar:void 0,docs:this.securityScheme.description});break}case"apiKey":{if(this.securityScheme.in==="header")return NC.header({name:{name:this.context.casingsGenerator.generateName(this.securityScheme.name),wireValue:this.securityScheme.name},valueType:Bf.container(Tv.optional(Bf.primitive({v1:"STRING",v2:wp.string({default:void 0,validation:void 0})}))),prefix:void 0,headerEnvVar:void 0,docs:this.securityScheme.description});break}case"oauth2":return NC.bearer({token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:this.securityScheme.description})}}};var rba=class extends w0{constructor({breadcrumbs:t,context:r}){super({breadcrumbs:t,context:r})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec,context:this.context}),this.context.spec=await this.resolveExternalRefs({spec:this.context.spec,context:this.context});let t=await this.convertSecuritySchemes();await this.convertSchemas(),await this.convertWebhooks();let{endpointLevelServers:r,errors:i}=await this.convertPaths({idToAuthScheme:t});this.convertServers({endpointLevelServers:r});let n={...this.ir,errors:i,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}};return n={...n,...bYr({ir:n,exampleGeneration:this.context.exampleGenerationArgs}),...SFi({ir:n,exampleGeneration:this.context.exampleGenerationArgs})},n}async convertSecuritySchemes(){if(this.context.authOverrides)return this.ir.auth=BKs({rawApiFileSchema:this.context.authOverrides,casingsGenerator:this.context.casingsGenerator}),{};let t=new Set(this.context.spec.security?.flatMap(n=>Object.keys(n))??[]),r={},i=[];for(let[n,a]of Object.entries(this.context.spec.components?.securitySchemes??{})){let u=await this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:["components","securitySchemes",n]});if(u==null)continue;let f=new hNo({context:this.context,breadcrumbs:["components","securitySchemes",n],securityScheme:u}).convert();f!=null&&(t.size===0||t.has(n))?i.push(f):f!=null&&(r[n]=f)}return i.length>0&&(this.ir.auth={requirement:"ANY",schemes:i,docs:void 0}),r}convertServers({endpointLevelServers:t}){if(this.context.environmentOverrides){this.ir.environments=zEn({rawApiFileSchema:this.context.environmentOverrides,casingsGenerator:this.context.casingsGenerator});return}let i=new mZt({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();i!=null&&(this.ir.environments=i.value)}async convertSchemas(){let t=this.context.getGroup({groupParts:[],namespace:this.context.namespace}),r=this.getOrCreatePackage({group:t});for(let[i,n]of Object.entries(this.context.spec.components?.schemas??{})){let u=await new hA.SchemaConverters.SchemaConverter({context:this.context,id:i,breadcrumbs:["components","schemas",i],schema:n}).convert();u!=null&&(r.types.push(i),this.ir.types={...this.ir.types,...u.inlinedTypes,[i]:u.typeDeclaration})}}async convertWebhooks(){let t={};for(let[,r]of Object.entries(this.context.spec.webhooks??{})){if(r==null){this.context.errorCollector.collect({message:"Skipping empty webhook",path:this.breadcrumbs});return}if(!("post"in r)){this.context.errorCollector.collect({message:"Skipping webhook because non-POST method",path:this.breadcrumbs});return}if(r.post?.operationId==null){this.context.errorCollector.collect({message:"Skipping webhook because no operation id present",path:this.breadcrumbs});return}let i=r.post.operationId,a=await new KEn({context:this.context,breadcrumbs:["webhooks",i],operation:r.post,method:jGp.OpenAPIV3.HttpMethods.POST,path:i}).convert();if(a!=null){let u=a.group?.join(".")??i;t[u]==null&&(t[u]=[]),t[u].push(i);let l=this.getOrCreatePackage({group:a.group});this.ir.webhookGroups[u]==null&&(this.ir.webhookGroups[u]=[]),this.ir.webhookGroups[u].push(a.webhook),l.webhooks=u,this.ir.types={...this.ir.types,...a.inlinedTypes}}}}async convertPaths({idToAuthScheme:t}){let r=[],i={};for(let[n,a]of Object.entries(this.context.spec.paths??{})){if(a==null)continue;let l=await new _No({context:this.context,breadcrumbs:["paths",n],pathItem:a,path:n}).convert();if(l!=null){for(let f of l.endpoints){let s=this.context.getGroup({groupParts:f.group,namespace:this.context.namespace}),o=this.getOrCreatePackage({group:f.group}),c=[...s].map(O=>this.context.casingsGenerator.generateName(O)),b=c[c.length-1],g=s.join(".");if(o.service=o.service??`service_${g}`,this.ir.services[o.service]==null&&(this.ir.services[o.service]=this.createNewService({allParts:c,finalpart:b})),this.ir.services[o.service]?.endpoints.push(f.endpoint),f.servers&&f.servers[0]!=null&&r.push(f.servers[0]),f.errors)for(let[O,m]of Object.entries(f.errors))i[O]=m}for(let f of l.webhooks){let s=this.context.getGroup({groupParts:f.group,namespace:this.context.namespace}),o=this.getOrCreatePackage({group:f.group}),c=s.join(".");this.ir.webhookGroups[c]??=[],this.ir.webhookGroups[c].push(f.webhook),o.webhooks=c}this.ir.types={...this.ir.types,...l.inlinedTypes}}}return{endpointLevelServers:r,errors:i}}createNewService({allParts:t,finalpart:r}){return{name:{fernFilepath:{allParts:t,packagePath:t.slice(0,-1),file:r}},displayName:void 0,basePath:k7(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0}}};var iba=class extends k2{isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}async convertReferenceToTypeReference(t){let r=this.getTypeIdFromSchemaReference(t);return r==null?{ok:!1}:(await this.resolveReference(t)).resolved?{ok:!0,reference:Bf.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(r),typeId:r,default:void 0,inline:!1})}:{ok:!1}}};var yNo=class extends hA.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r,parameter:i})}async convert(){let t,r={};if(this.parameter.schema!=null){let n=await new hA.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required}).convert();n!=null&&(t=n.type,r=n.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}};var LUD=pu.object({description:pu.string().optional(),required:pu.boolean().optional(),deprecated:pu.boolean().optional(),allowEmptyValue:pu.boolean().optional(),style:pu.string().optional(),explode:pu.boolean().optional(),allowReserved:pu.boolean().optional(),schema:pu.any().optional(),example:pu.any().optional(),examples:pu.record(pu.string(),pu.any()).optional(),content:pu.record(pu.string(),pu.any()).optional()}),UUD=LUD.extend({name:pu.string(),in:pu.string()}),VUD=pu.array(UUD),vNo=class extends dS{operation;key="x-fern-parameters";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null)try{return VUD.parse(t)}catch(r){this.context.errorCollector.collect({message:`Failed to parse x-fern-parameters extension: ${r instanceof Error?r.message:String(r)}`,path:this.breadcrumbs});return}}};var bNo=class extends w0{static STRING=Bf.primitive({v1:"STRING",v2:wp.string({default:void 0,validation:void 0})});method;pathParameters;queryParameters;headers;constructor({context:t,breadcrumbs:r,method:i,pathParameters:n=[],queryParameters:a=[],headers:u=[]}){super({context:t,breadcrumbs:r}),this.method=i,this.pathParameters=n,this.queryParameters=a,this.headers=u}async convert(){let t={},r="";for(let l of this.pathParameters)r+=`/{${l.name.originalName}}`;let i=k7(r),n=[];for(let[l,f]of this.method.params.entries()){let s;if(this.context.isReferenceObject(f)){let g=await this.context.resolveReference(f);if(g.resolved)s=g.value;else continue}else s=f;let o=[this.method.name,"Param",s.name].join("_"),b=await new hA.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[...this.breadcrumbs,`params[${l}]`],schemaIdOverride:o,context:this.context,schemaOrReference:s.schema}).convert();b!=null&&(n.push({docs:s.description,availability:await this.context.getAvailability({node:f,breadcrumbs:[...this.breadcrumbs,"parameters"]}),name:this.context.casingsGenerator.generateNameAndWireValue({name:s.name,wireValue:s.name}),valueType:b.type,v2Examples:b.schema?.v2Examples}),t={...b.inlinedTypes,...t,...b.schema!=null?{[o]:b.schema}:{}})}let a;if(this.method.result!=null){let l=await this.context.resolveMaybeReference({schemaOrReference:this.method.result,breadcrumbs:[...this.breadcrumbs,"result"]});if(l!=null){let f=new hA.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"result"],context:this.context,schemaOrReference:l.schema}),s=[...this.method.name,"Result"].join("_"),o=await f.convert();o!=null&&(a={docs:l.description,v2Examples:o?.schema?.v2Examples,responseBodyType:o.type},t={...o.inlinedTypes,...t,...o.schema!=null?{[s]:o.schema}:{}})}}return{endpoint:{baseUrl:void 0,basePath:void 0,auth:!1,method:"POST",id:this.method.name,docs:this.method.description,name:this.context.casingsGenerator.generateName(this.method.name),headers:this.headers,displayName:this.method.name,pathParameters:this.pathParameters,queryParameters:this.queryParameters,allPathParameters:this.pathParameters,path:i,fullPath:i,requestBody:n.length>0?FC.inlinedRequestBody({name:this.context.casingsGenerator.generateName([this.method.name,"Request"].join("_")),docs:void 0,properties:n,extends:[],extendedProperties:[],contentType:"application/json",extraProperties:!1,v2Examples:void 0}):void 0,sdkRequest:void 0,response:a!=null?{body:SM.json(GY.response(a)),statusCode:void 0}:void 0,errors:[],idempotent:!1,pagination:void 0,userSpecifiedExamples:[],autogeneratedExamples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:await this.convertExamples()},transport:void 0,availability:void 0,source:Xre.openrpc()},inlinedTypes:t}}async convertExamples(){let t={},r=0;if(this.method.examples&&this.method.examples.length>0){for(let i of this.method.examples??[]){let n;if(this.context.isReferenceObject(i)){let f=await this.context.resolveReference(i);if(f.resolved)n=f.value;else continue}else n=i;let a;if(n.result)if(this.context.isReferenceObject(n.result)){let f=await this.context.resolveReference(n.result);f.resolved&&(a=f.value)}else a=n.result;let u=n.name??`Example ${r+1}`,l=[];if(n.params&&Array.isArray(n.params)){l=[];for(let f of n.params)if(this.context.isReferenceObject(f)){let s=await this.context.resolveReference(f);if(s.resolved)l.push(s.value);else continue}else l.push(f)}t[u]={request:{docs:void 0,endpoint:{method:"POST",path:"/{apiKey}"},baseUrl:void 0,environment:void 0,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:l.map(f=>f.value)??void 0},response:{docs:void 0,statusCode:void 0,body:a?.value?Ks.V2HttpEndpointResponseBody.json({jsonrpc:"2.0",id:n.examplePairedRequest?.id||"1",result:a.value}):void 0},codeSamples:[]}}++r}return t}};var nba=class extends w0{constructor({context:t,breadcrumbs:r}){super({context:t,breadcrumbs:r})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec,context:this.context}),this.convertServers({}),await this.convertSchemas(),await this.convertMethods();let t={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}};return t={...t,...bYr({ir:t,exampleGeneration:this.context.exampleGenerationArgs}),...SFi({ir:t,exampleGeneration:this.context.exampleGenerationArgs})},t}convertServers({endpointLevelServers:t}){let i=new mZt({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();i!=null&&(this.ir.environments=i.value)}async convertSchemas(){let t=this.context.getGroup({groupParts:[],namespace:this.context.namespace}),r=this.getOrCreatePackage({group:t});for(let[i,n]of Object.entries(this.context.spec.components?.schemas??{})){let u=await new hA.SchemaConverters.SchemaConverter({context:this.context,id:i,breadcrumbs:["components","schemas",i],schema:n}).convert();u!=null&&(r.types.push(i),this.ir.types={...this.ir.types,...u.inlinedTypes,[i]:u.typeDeclaration})}}async convertMethods(){let r=new vNo({context:this.context,breadcrumbs:["methods"],operation:this.context.spec}).convert(),i=[],n=[],a=[];if(r&&r.length>0)for(let[f,s]of r.entries()){let c=await new yNo({context:this.context,breadcrumbs:[...this.breadcrumbs,`x-fern-parameters[${f}]`],parameter:s}).convert();if(c!=null)switch(c.type){case"path":{i.push(c.parameter);break}case"query":{n.push(c.parameter);break}case"header":{a.push(c.parameter);break}}}let u=this.context.getGroup({groupParts:[],namespace:this.context.namespace}),l=this.getOrCreatePackage({group:u});for(let f of this.context.spec.methods??[]){let s=await this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:["methods"]});if(s==null)continue;let c=await new bNo({context:this.context,breadcrumbs:["methods"],method:s,pathParameters:i,queryParameters:n,headers:a}).convert();if(c!=null){l.service==null&&(l.service="service_root");let b=[...u].map(O=>this.context.casingsGenerator.generateName(O)),g=b[b.length-1];this.ir.services[l.service]==null&&(this.ir.services[l.service]={name:{fernFilepath:{allParts:b,packagePath:b.slice(0,-1),file:g}},displayName:void 0,basePath:k7(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0}),this.ir.services[l.service]?.endpoints.push(c.endpoint),this.ir.types={...this.ir.types,...c.inlinedTypes}}}}};var aba=class extends k2{isReferenceObject(t){return t!=null&&"$ref"in t}async convertReferenceToTypeReference(t){let r=this.getTypeIdFromSchemaReference(t);return r==null?{ok:!1}:(await this.resolveReference(t)).resolved?{ok:!0,reference:Bf.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(r),typeId:r,default:void 0,inline:!1})}:{ok:!1}}};var wGp={[Yh.GenerationLanguage.PHP]:new Set(["abstract","and","as","break","callable","case","catch","class","clone","const","continue","declare","default","do","echo","else","elseif","enddeclare","endfor","endforeach","endif","endswitch","endwhile","extends","final","finally","fn","for","foreach","function","global","goto","list","if","implements","include","include_once","instanceof","insteadof","interface","match","namespace","new","or","parent","Parent","print","private","protected","public","readonly","require","require_once","return","static","switch","throw","trait","try","use","var","while","xor","yield"].flatMap(e=>[e,dx(e)])),[Yh.GenerationLanguage.TYPESCRIPT]:new Set(["any","as","boolean","break","case","catch","class","const","constructor","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","let","module","new","null","number","of","package","private","protected","public","require","return","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","Date","Error","File","Object","Record"]),[Yh.GenerationLanguage.JAVA]:new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","false","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","true","try","void","volatile","while"]),[Yh.GenerationLanguage.PYTHON]:new Set(["False","None","True","and","as","assert","async","","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","float","int","complex","bool","uuid","list","set","map","long","self","all"]),[Yh.GenerationLanguage.GO]:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[Yh.GenerationLanguage.RUBY]:new Set(["__ENCODING__","__LINE__","__FILE__","alias","and","begin","break","case","class","def","defined","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield","Object","JSON","Date","DateTime"]),[Yh.GenerationLanguage.CSHARP]:new Set(["abstract","as","base","bool","break","byte","case","catch","char","checked","class","const","continue","decimal","default","delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","goto","if","implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","operator","out","override","params","private","protected","public","readonly","ref","return","sbyte","sealed","short","sizeof","stackalloc","static","string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","ushort","using","virtual","void","volatile","while","add","and","alias","ascending","args","async","","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","managed","nameof","nint","not","notnull","nuint","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value","var","when","where","with","yield"]),[Yh.GenerationLanguage.SWIFT]:new Set([])};var WUD=["go","ruby"];function VKs({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let u=c=>({unsafeName:c,safeName:HUD({name:c,keywords:$UD({generationLanguage:e,keywords:t})})}),l=$y(n),f=dx(l),s=qCi(n),o=DCi(l);return r&&(!JUD(o)&&(e==null||WUD.includes(e))&&(l=o.map((c,b)=>{if(b>0){let g=gNo(c);if(g!=null)return g;if(ONo(c))return c.toUpperCase()}return c}).join(""),f=o.map((c,b)=>{let g=gNo(c);return g??(ONo(c)?c.toUpperCase():b===0?dx(c):c)}).join("")),s=n.split(" ").map(c=>c.split(/(\d+)/).map(qCi).join("")).join("_")),{originalName:n,camelCase:u(a?.casingOverrides?.camel??l),snakeCase:u(a?.casingOverrides?.snake??s),screamingSnakeCase:u(a?.casingOverrides?.["screaming-snake"]??s.toUpperCase()),pascalCase:u(a?.casingOverrides?.pascal??f)}},generateNameAndWireValue:({name:n,wireValue:a,opts:u})=>({name:i.generateName(n,u),wireValue:a})};return i}function HUD({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":QUD(e)?"_"+e:e}function $UD({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return wGp[e]}var GUD=/^[0-9]/;function QUD(e){return GUD.test(e)}function JUD(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=gNo(i)!=null||ONo(i),a=gNo(t)!=null||ONo(t);return n&&a})}function gNo(e){return YUD.get(e.toUpperCase())}function ONo(e){return KUD.has(e.toUpperCase())}var KUD=new Set(["ACL","API","ASCII","CPU","CSS","DNS","EOF","GUID","HTML","HTTP","HTTPS","ID","IP","JSON","LHS","QPS","RAM","RHS","RPC","SAML","SCIM","SLA","SMTP","SQL","SSH","SSO","TCP","TLS","TTL","UDP","UI","UID","UUID","URI","URL","UTF8","VM","XML","XMPP","XSRF","XSS"]),YUD=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);var SGp=require("fs/promises");async function WKs({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let i=(await(0,SGp.readFile)(t)).toString(),n;try{n=JSON.parse(i)}catch{n=Gd.load(i)}return r!=null?await rEn({absoluteFilePathToOverrides:r,context:e,data:n}):n}var nN=class extends Oha{type="oss";allSpecs;specs;sources;loader;constructor({allSpecs:t,specs:r,...i}){super({...i,respectReadonlySchemas:r.every(n=>n.settings?.respectReadonlySchemas),respectNullableSchemas:r.every(n=>n.settings?.respectNullableSchemas),onlyIncludeReferencedSchemas:r.every(n=>n.settings?.onlyIncludeReferencedSchemas),inlinePathParameters:r.every(n=>n.settings?.inlinePathParameters),objectQueryParameters:r.every(n=>n.settings?.objectQueryParameters),useBytesForBinaryResponse:r.filter(n=>n.type==="openapi"&&n.source.type==="openapi").some(n=>n.settings?.useBytesForBinaryResponse),respectForwardCompatibleEnums:r.filter(n=>n.type==="openapi"&&n.source.type==="openapi").some(n=>n.settings?.respectForwardCompatibleEnums),exampleGeneration:r[0]?.settings?.exampleGeneration}),this.specs=r,this.allSpecs=t,this.sources=this.convertSpecsToIdentifiableSources(r),this.loader=new b9t(this.absoluteFilePath)}async getOpenAPIIr({context:t,relativePathToDependency:r},i){let n=await aRe({context:t,specs:this.specs,relativePathToDependency:r});return kNi({context:t,documents:await this.loader.loadDocuments({context:t,specs:n}),options:{...i,respectReadonlySchemas:i?.respectReadonlySchemas??this.respectReadonlySchemas,respectNullableSchemas:i?.respectNullableSchemas??this.respectNullableSchemas,onlyIncludeReferencedSchemas:i?.onlyIncludeReferencedSchemas??this.onlyIncludeReferencedSchemas,inlinePathParameters:i?.inlinePathParameters??this.inlinePathParameters,objectQueryParameters:i?.objectQueryParameters??this.objectQueryParameters,exampleGeneration:i?.exampleGeneration??this.exampleGeneration,useBytesForBinaryResponse:i?.useBytesForBinaryResponse??this.useBytesForBinaryResponse}})}async getIntermediateRepresentation({context:t,audiences:r}){let i=await aRe({context:t,specs:this.specs}),n=await this.loader.loadDocuments({context:t,specs:i}),a=new EFi(r),u=this.generatorsConfiguration?.api?.auth!=null?{...this.generatorsConfiguration?.api}:void 0;u&&t.logger.trace("Using auth overrides from generators configuration");let l=this.generatorsConfiguration?.api?.environments!=null?{...this.generatorsConfiguration?.api}:void 0;l&&t.logger.trace("Using environment overrides from generators configuration");let f=this.generatorsConfiguration?.api?.headers!=null?{...this.generatorsConfiguration?.api}:void 0;f&&t.logger.trace("Using global header overrides from generators configuration");let s;for(let o of n){let c=new WEn({logger:t.logger}),b;switch(o.type){case"openapi":{let O=new iba({namespace:o.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:o.value,exampleGenerationArgs:{disabled:!1},errorCollector:c,authOverrides:u,environmentOverrides:l,globalHeaderOverrides:f});b=await new rba({context:O}).convert();break}case"asyncapi":{let O=new eba({namespace:o.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:o.value,exampleGenerationArgs:{disabled:!1},errorCollector:c});b=await new kva({context:O}).convert();break}default:c.collect({message:`Unsupported document type: ${o}`,path:[]});break}c.hasErrors()&&(t.logger.info(`${o.type==="openapi"?"OpenAPI":"AsyncAPI"} Importer encountered errors:`),c.logErrors());let g=VKs({generationLanguage:"typescript",keywords:void 0,smartCasing:!1});b!=null&&(s=s===void 0?b:NRo(s,b,g))}for(let o of this.allSpecs)if(o.type==="openrpc"){let c=new WEn({logger:t.logger}),b=new aba({namespace:o.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:await WKs({context:t,absoluteFilePath:o.absoluteFilepath,absoluteFilePathToOverrides:o.absoluteFilepathToOverrides}),exampleGenerationArgs:{disabled:!1},errorCollector:c}),O=await new nba({context:b}).convert();c.hasErrors()&&(t.logger.info("OpenRPC Importer encountered errors:"),c.logErrors());let m=VKs({generationLanguage:"typescript",keywords:void 0,smartCasing:!1});O!=null&&(s=s===void 0?O:NRo(s,O,m))}if(s===void 0)throw new Error("Failed to generate intermediate representation");return s}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new mDe({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:i,cliVersion:this.cliVersion,sources:this.sources})}getAbsoluteFilePaths(){return[this.absoluteFilePath,...this.specs.flatMap(t=>[t.type==="protobuf"?t.absoluteFilepathToProtobufTarget:t.absoluteFilepath,t.absoluteFilepathToOverrides]).filter(g0)]}getSources(){return this.sources}convertSpecsToIdentifiableSources(t){let r=new Set,i=[];return t.reduce((n,a)=>{let u=a.type==="protobuf"?a.absoluteFilepathToProtobufRoot:a.absoluteFilepath;return r.has(u)||(r.add(u),n.push({type:a.type,id:Uie(),absoluteFilePath:u})),n},i)}};var DGp={None:"none",Header:"header"};var WNo={};jo(WNo,{ConjureAliasDeclaration:()=>ENo,ConjureArgument:()=>LNo,ConjureArgumentWithParamType:()=>FNo,ConjureAuthDefinition:()=>kEn,ConjureAuthDefinitionType:()=>RNo,ConjureDefinitions:()=>INo,ConjureEndpointDefinition:()=>UNo,ConjureEnumDeclaration:()=>BNo,ConjureEnumVariant:()=>CNo,ConjureEnumWithDocs:()=>TNo,ConjureObjectDeclaration:()=>qNo,ConjureParamType:()=>NNo,ConjurePrimitive:()=>DNo,ConjureService:()=>VNo,ConjureServiceName:()=>SNo,ConjureType:()=>b_i,ConjureTypeDeclaration:()=>xNo,ConjureTypeReference:()=>g_i,ConjureTypeWithDocs:()=>MNo,ConjureTypes:()=>zNo,ConjureUnionDeclaration:()=>ANo,DefinitionFile:()=>eQp,WithDocs:()=>PZt,commons:()=>JKs,conjure:()=>KKs,services:()=>YKs,types:()=>XKs});var JKs={};jo(JKs,{WithDocs:()=>PZt});var kd={};jo(kd,{JsonError:()=>YEn,ParseError:()=>XEn,any:()=>UGp,bigint:()=>MGp,boolean:()=>VGp,booleanLiteral:()=>LGp,date:()=>AGp,discriminant:()=>XGp,enum_:()=>PNo,getObjectLikeUtils:()=>m9t,getObjectUtils:()=>AFi,getSchemaUtils:()=>oq,isProperty:()=>v_i,lazy:()=>qGp,lazyObject:()=>RGp,list:()=>wNo,number:()=>WGp,object:()=>jNo,objectWithoutOptionalProperties:()=>zGp,optional:()=>HKs,property:()=>CGp,record:()=>QGp,set:()=>JGp,string:()=>HGp,stringLiteral:()=>FGp,transform:()=>$Ks,undiscriminatedUnion:()=>YGp,union:()=>kGp,unknown:()=>$Gp,withParsedProperties:()=>QKs});var ij={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 RM(e,t){return`Expected ${t}. Received ${XUD(e)}.`}function XUD(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 k5(e){return{...e,json:EGp(e.json),parse:EGp(e.parse)}}function EGp(e){return(t,r)=>{let i=e(t,r),{skipValidation:n=!1}=r??{};return!i.ok&&n?(console.warn(["Failed to validate.",...i.errors.map(a=>" - "+(a.path.length>0?`${a.path.join(".")}: ${a.message}`:a.message))].join(`
|
|
1957
|
+
`}async function aRe({context:e,specs:t,relativePathToDependency:r}){let i=new Ezo({context:e}),n=t.filter(l=>l.type==="openapi").map(l=>({...l,relativePathToDependency:r})),a=t.filter(l=>l.type==="protobuf"),u=await Promise.all(a.map(async l=>$8D({generator:i,protobufSpec:l,relativePathToDependency:r})));return[...n,...u]}async function $8D({generator:e,protobufSpec:t,relativePathToDependency:r}){return{type:"openapi",absoluteFilepath:await e.generate({absoluteFilepathToProtobufRoot:t.absoluteFilepathToProtobufRoot,absoluteFilepathToProtobufTarget:t.absoluteFilepathToProtobufTarget,relativeFilepathToProtobufRoot:t.relativeFilepathToProtobufRoot,local:t.generateLocally}),absoluteFilepathToOverrides:t.absoluteFilepathToOverrides,settings:t.settings,source:{type:"protobuf",relativePathToDependency:r,root:t.absoluteFilepathToProtobufRoot,file:t.absoluteFilepathToProtobufTarget}}}var x$p=require("fs"),TEn=require("fs/promises");var I$p=require("os"),z$p=li(require("path"),1),R$p=require("stream/promises"),N$p=li(IRo(),1),F$p=li(hre(),1);var jKs=li(rIi(),1);var pP;(function(e){e.FILE_READ="FILE_READ",e.FILE_PARSE="FILE_PARSE",e.FILE_MISSING="FILE_MISSING",e.STRUCTURE_VALIDATION="STRUCTURE_VALIDATION",e.JSONSCHEMA_VALIDATION="JSONSCHEMA_VALIDATION",e.DEPENDENCY_NOT_LISTED="DEPENDENCY_NOT_LISTED",e.FAILED_TO_LOAD_DEPENDENCY="FAILED_TO_LOAD_DEPENDENCY",e.EXPORTING_PACKAGE_MARKER_OTHER_KEYS="EXPORTING_PACKAGE_MARKER_OTHER_KEYS",e.EXPORT_PACKAGE_HAS_DEFINITIONS="EXPORT_PACKAGE_HAS_DEFINITIONS",e.MISCONFIGURED_DIRECTORY="MISCONFIGURED_DIRECTORY"})(pP||(pP={}));var mLD=vJr();async function L$p({dependencyName:e,dependenciesConfiguration:t,context:r,rootApiFile:i,cliVersion:n,settings:a,loadAPIWorkspace:u}){let l,f={type:pP.FAILED_TO_LOAD_DEPENDENCY,dependencyName:e},s=t.dependencies[e];return s==null?f={type:pP.DEPENDENCY_NOT_LISTED,dependencyName:e}:await r.runInteractiveTask({name:`Download ${MLD(s)}`},async o=>{switch(s.type){case"version":l=await DLD({context:o,dependency:s,cliVersion:n,settings:a,loadAPIWorkspace:u});return;case"local":l=await SLD({context:o,dependency:s,cliVersion:n,settings:a,loadAPIWorkspace:u});return;default:Mo(s)}}),l!=null?{didSucceed:!0,definition:l}:{didSucceed:!1,failure:f}}var U$p="dependencies";var PLD="metadata.json",jLD=".fern";function wLD(e){return Lu(Hl.of((0,I$p.homedir)()),Xa.of(jLD),Xa.of(U$p),Xa.of(e.organization),Xa.of(e.apiName),Xa.of(e.version))}async function SLD({dependency:e,context:t,cliVersion:r,settings:i,loadAPIWorkspace:n}){if(n==null){t.failWithoutThrowing("Failed to load api definition");return}t.logger.info("Parsing...");let a=await n({absolutePathToWorkspace:e.absoluteFilepath,context:t,cliVersion:r,workspaceName:void 0});if(!a.didSucceed){t.failWithoutThrowing("Failed to load api definition",a.failures);return}t.logger.info("Modifying source filepath ...");let u=await a.workspace.getDefinition({context:t,relativePathToDependency:Xa.of(e.path)},i);return t.logger.info("Loaded..."),u}async function DLD({dependency:e,context:t,cliVersion:r,settings:i,loadAPIWorkspace:n}){let a=wLD(e),u=Lu(a,Xa.of(U$p)),l=Lu(a,Xa.of(PLD)),f;if(!await Cf(u)||!await Cf(l)){t.logger.info("Downloading manifest...");let c=await mLD.definitionRegistry.get(jKs.FernFiddle.OrganizationId(e.organization),jKs.FernFiddle.ApiId(e.apiName),e.version);if(!c.ok){c.error._visit({orgDoesNotExistError:()=>{t.failWithoutThrowing("Organization does not exist")},apiDoesNotExistError:()=>{t.failWithoutThrowing("API does not exist")},versionDoesNotExistError:()=>{t.failWithoutThrowing("Version does not exist")},_other:m=>{t.failWithoutThrowing("Failed to download API manifest",m)}});return}let b=c.body.yamlSchemaVersion!=null?parseInt(c.body.yamlSchemaVersion):void 0,g=lNi(r),O=lNi(c.body.cliVersion);if(b!=null){if(b>1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a higher version of fern. Upgrade this workspace to ${c.body.cliVersion}`);return}else if(b<1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a lower version of fern. Upgrade it to ${r}`);return}}else if(g.major!==O.major||g.minor!==O.minor){t.failWithoutThrowing(`CLI version is ${c.body.cliVersion}. Expected ${g.major}.${g.minor}.x (to match current workspace).`);return}t.logger.info("Downloading..."),t.logger.debug("Remote URL: "+c.body.definitionS3DownloadUrl),await(0,TEn.mkdir)(u,{recursive:!0});try{await ELD({s3PreSignedReadUrl:c.body.definitionS3DownloadUrl,absolutePathToLocalOutput:u})}catch(m){t.failWithoutThrowing("Failed to download API",m);return}f=c.body,await(0,TEn.writeFile)(l,JSON.stringify(f))}else f=JSON.parse((await(0,TEn.readFile)(l)).toString());if(t.logger.info("Parsing..."),n==null){t.failWithoutThrowing("Failed to load API");return}let s=await n({absolutePathToWorkspace:u,context:t,cliVersion:f.cliVersion,workspaceName:void 0});if(!s.didSucceed){t.failWithoutThrowing("Failed to parse dependency after downloading",s.failures);return}if(s.workspace.type==="oss"){t.failWithoutThrowing("Dependency must be a fern workspace.");return}return await s.workspace.getDefinition({context:t},i)}async function ELD({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}){let r=await YR.get(e,{responseType:"stream"}),i=await F$p.default.dir(),n=z$p.default.join(i.path,"api.tgz");await(0,R$p.pipeline)(r.data,(0,x$p.createWriteStream)(n)),await(0,N$p.extract)({file:n,cwd:t})}function MLD(e){switch(e.type){case"version":return`@${e.organization}/${e.apiName}`;case"local":return`${e.path}`;default:Mo(e)}}var eGp=li(Q$p(),1);function zRo(e,t){for(let[r,i]of KN(e))qLD({relativeFilepath:r,failure:i,logger:t})}function qLD({relativeFilepath:e,failure:t,logger:r}){switch(t.type){case pP.MISCONFIGURED_DIRECTORY:r.error("Misconfigured fern directory: please see the docs at https://buildwithfern.com/learn/api-definition/introduction/what-is-the-fern-folder");break;case pP.FILE_READ:r.error("Failed to open file: "+e);break;case pP.FILE_MISSING:r.error("Missing file: "+e);break;case pP.FILE_PARSE:t.error instanceof Waa?r.error(kie({title:`Failed to parse ${e}: ${t.error.reason}`,subtitle:t.error.mark.snippet})):r.error("Failed to parse file: "+e);break;case pP.STRUCTURE_VALIDATION:for(let i of t.error.issues)for(let{title:n,subtitle:a}of TLD(i))r.error(kie({title:n,subtitle:a,breadcrumbs:[e,...i.path]}));break;case pP.FAILED_TO_LOAD_DEPENDENCY:r.error("Failed to load dependency: "+t.dependencyName);break;case pP.DEPENDENCY_NOT_LISTED:r.error(`Dependency is not listed in ${CZa}: `+t.dependencyName);break;case pP.EXPORT_PACKAGE_HAS_DEFINITIONS:r.error("Exported package contains API definitions: "+t.pathToPackage);break;case pP.EXPORTING_PACKAGE_MARKER_OTHER_KEYS:r.error(`${t.pathOfPackageMarker} has an export so it cannot define other keys.`);break;case pP.JSONSCHEMA_VALIDATION:t.error.error!=null&&r.error(kie({title:t.error.error.message??"Unknown error",breadcrumbs:[e,...t.error.error.instancePath.split("/").filter(i=>i!=="")]}));for(let i of t.error.allErrors)i!==t.error.error&&r.debug(kie({title:i.message??"Unknown error",breadcrumbs:[e,...i.instancePath.split("/").filter(n=>n!=="")]}));break;default:Mo(t)}}function TLD(e){switch(e.code){case Wl.invalid_type:return[{title:"Incorrect type",subtitle:`Expected ${Ws.underline(e.expected)} but received ${Ws.underline(e.received)}`}];case Wl.unrecognized_keys:return e.keys.map(t=>({title:"Unexpected key",subtitle:`Encountered unexpected key ${Ws.underline(t)}`}));case Wl.invalid_enum_value:return[{title:"Unrecognized value",subtitle:`Allowed values: ${e.options.map(t=>Ws.underline(t)).join(", ")}`}];case Wl.invalid_union:case Wl.invalid_arguments:case Wl.invalid_return_type:case Wl.invalid_date:case Wl.invalid_string:case Wl.too_small:case Wl.too_big:case Wl.invalid_intersection_types:case Wl.not_multiple_of:case Wl.custom:default:return[{title:e.message}]}}var J$p=require("fs/promises");async function K$p(e,t){let r=[];for(let i of await pxe(e,t))r.push(await CLD({relativeFilepath:KA(e,i),absoluteFilepath:i}));return r}async function CLD({relativeFilepath:e,absoluteFilepath:t}){return{relativeFilepath:e,absoluteFilepath:t,fileContents:(await(0,J$p.readFile)(t)).toString()}}async function Y$p(e){let t={},r={};function i(n){try{t[n.relativeFilepath]={defaultUrl:void 0,contents:Gd.load(n.fileContents,{schema:Gd.CORE_SCHEMA}),rawContents:n.fileContents}}catch(a){r[n.relativeFilepath]={type:pP.FILE_PARSE,error:a}}}return await Promise.all(e.map(i)),Object.keys(r).length>0?{didSucceed:!1,failures:r}:{didSucceed:!0,files:t}}async function X$p({dependenciesConfiguration:e,structuralValidationResult:t,context:r,cliVersion:i,settings:n,loadAPIWorkspace:a}){let u={},l={},f={};return await Promise.all(KN(t.packageMarkers).map(async([s,o])=>{if(o.contents.export==null)u[s]=o;else{let{export:c,...b}=o.contents;if(MY(b)>0)f[s]={type:pP.EXPORTING_PACKAGE_MARKER_OTHER_KEYS,pathOfPackageMarker:s};else{let g=Zd(s);if(k4t(t.namedDefinitionFiles).some(m=>m!==s&&m.startsWith(g)))f[s]={type:pP.EXPORT_PACKAGE_HAS_DEFINITIONS,pathToPackage:g};else{let m=await L$p({dependencyName:typeof o.contents.export=="string"?o.contents.export:o.contents.export.dependency,dependenciesConfiguration:e,context:r,rootApiFile:t.rootApiFile.contents,cliVersion:i,settings:n,loadAPIWorkspace:a});m.didSucceed?l[Zd(s)]={definition:m.definition,url:typeof o.contents.export=="object"?o.contents.export.url:void 0}:f[s]=m.failure}}}})),MY(f)>0?{didSucceed:!1,failures:f}:{didSucceed:!0,packageMarkers:u,importedDefinitions:l}}var Z$p=li(require("path"),1);var DKs={};jo(DKs,{additionalProperties:()=>zLD,default:()=>NLD,definitions:()=>RLD,properties:()=>xLD,required:()=>ILD,type:()=>BLD});var BLD="object",xLD={docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"default-url":{oneOf:[{type:"string"},{type:"null"}]},"default-environment":{oneOf:[{type:"string"},{type:"null"}]},environments:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/environments.EnvironmentSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/auth.ApiAuthSchema"},{type:"null"}]},"auth-schemes":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/auth.AuthSchemeDeclarationSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},name:{type:"string"},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},"error-discrimination":{oneOf:[{$ref:"#/definitions/file.ErrorDiscriminationSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},errors:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"idempotency-headers":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},variables:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/variables.VariableDeclarationSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"null"}]},version:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},ILD=["name"],zLD=!1,RLD={"environments.SingleBaseUrlEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},url:{type:"string"}},required:["url"],additionalProperties:!1},"environments.MultipleBaseUrlsEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},urls:{type:"object",additionalProperties:{type:"string"}}},required:["urls"],additionalProperties:!1},"environments.EnvironmentSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/environments.SingleBaseUrlEnvironmentSchema"},{$ref:"#/definitions/environments.MultipleBaseUrlsEnvironmentSchema"}]},"auth.AuthSchemeReferenceSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{type:"string"}},required:["scheme"],additionalProperties:!1},"auth.AnyAuthItem":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"}]},"auth.AnyAuthSchemesSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},any:{type:"array",items:{$ref:"#/definitions/auth.AnyAuthItem"}}},required:["any"],additionalProperties:!1},"auth.ApiAuthSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"},{$ref:"#/definitions/auth.AnyAuthSchemesSchema"}]},"auth.OAuthAccessTokenRequestPropertiesSchema":{type:"object",properties:{"client-id":{oneOf:[{type:"string"},{type:"null"}]},"client-secret":{oneOf:[{type:"string"},{type:"null"}]},scopes:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthAccessTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthGetTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthRefreshTokenRequestPropertiesSchema":{type:"object",properties:{"refresh-token":{type:"string"}},required:["refresh-token"],additionalProperties:!1},"auth.OAuthRefreshTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthRefreshTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"oauth"},type:{const:"client-credentials"},scopes:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"client-id-env":{oneOf:[{type:"string"},{type:"null"}]},"client-secret-env":{oneOf:[{type:"string"},{type:"null"}]},"token-prefix":{oneOf:[{type:"string"},{type:"null"}]},"token-header":{oneOf:[{type:"string"},{type:"null"}]},"get-token":{$ref:"#/definitions/auth.OAuthGetTokenEndpointSchema"},"refresh-token":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenEndpointSchema"},{type:"null"}]}},required:["scheme","type","get-token"],additionalProperties:!1},"auth.HeaderAuthSchemeSchema":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},header:{type:"string"},type:{oneOf:[{type:"string"},{type:"null"}]},prefix:{oneOf:[{type:"string"},{type:"null"}]}},required:["header"],additionalProperties:!1},"auth.AuthVariable":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.BasicAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"basic"},username:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]},password:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.BearerAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"bearer"},token:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.AuthSchemeDeclarationSchema":{anyOf:[{$ref:"#/definitions/auth.OAuthSchemeSchema"},{$ref:"#/definitions/auth.HeaderAuthSchemeSchema"},{$ref:"#/definitions/auth.BasicAuthSchemeSchema"},{$ref:"#/definitions/auth.BearerAuthSchemeSchema"}]},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"file.PropertyBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"property"},"property-name":{type:"string"}},required:["strategy","property-name"],additionalProperties:!1},"file.StatusCodeBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"status-code"}},required:["strategy"],additionalProperties:!1},"file.ErrorDiscriminationSchema":{anyOf:[{$ref:"#/definitions/file.PropertyBasedErrorDiscrimination"},{$ref:"#/definitions/file.StatusCodeBasedErrorDiscrimination"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"variables.VariableDeclarationDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"variables.VariableDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/variables.VariableDeclarationDetailed"}]},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"versioning.VersionValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionValue":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionValueDetailed"}]},"versioning.VersionDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionDeclarationHeaderObjectSchema"}]},"versioning.VersionDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/versioning.VersionValue"}},header:{$ref:"#/definitions/versioning.VersionDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1}},NLD={type:BLD,properties:xLD,required:ILD,additionalProperties:zLD,definitions:RLD};var EKs={};jo(EKs,{additionalProperties:()=>ULD,default:()=>WLD,definitions:()=>VLD,properties:()=>LLD,type:()=>FLD});var FLD="object",LLD={docs:{oneOf:[{type:"string"},{type:"null"}]},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]}},ULD=!1,VLD={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{type:"boolean"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1}},WLD={type:FLD,properties:LLD,additionalProperties:ULD,definitions:VLD};var MKs={};jo(MKs,{additionalProperties:()=>GLD,default:()=>JLD,definitions:()=>QLD,properties:()=>$LD,type:()=>HLD});var HLD="object",$LD={imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},navigation:{oneOf:[{$ref:"#/definitions/file.Navigation"},{type:"null"}]},export:{oneOf:[{$ref:"#/definitions/file.Export"},{type:"null"}]}},GLD=!1,QLD={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{type:"boolean"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1},"file.Navigation":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"file.ExportDetailed":{type:"object",properties:{dependency:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]}},required:["dependency"],additionalProperties:!1},"file.Export":{anyOf:[{type:"string"},{$ref:"#/definitions/file.ExportDetailed"}]}},JLD={type:HLD,properties:$LD,additionalProperties:GLD,definitions:QLD};function k$p({files:e,absolutePathToDefinition:t}){let r,i={},n={},a={};for(let[u,l]of KN(e)){let f=l.contents,s=o=>{a[u]={type:pP.JSONSCHEMA_VALIDATION,error:o}};if(u===XN){let o=yQr(f,DKs);if(o.success){let c=cF.serialization.RootApiFileSchema.parseOrThrow(f);r={defaultUrl:c["default-url"],contents:c,rawContents:l.rawContents}}else s(o)}else if(Z$p.default.basename(u)===nS){let o=yQr(f,MKs);if(o.success){let c=cF.serialization.PackageMarkerFileSchema.parseOrThrow(f);n[u]={defaultUrl:typeof c.export=="object"?c.export.url:void 0,contents:c,rawContents:l.rawContents}}else s(o)}else{let o=yQr(f,EKs);if(o.success){let c=cF.serialization.DefinitionFileSchema.parseOrThrow(f);i[u]={defaultUrl:void 0,contents:c,rawContents:l.rawContents,absoluteFilePath:Lu(t,u)}}else s(o)}}return r==null?{didSucceed:!1,failures:{[Xa.of(XN)]:{type:pP.FILE_MISSING},...a}}:Object.keys(a).length>0?{didSucceed:!1,failures:a}:{didSucceed:!0,namedDefinitionFiles:i,rootApiFile:r,packageMarkers:n}}var yZt=class extends r9t{type="fern";context;fernWorkspaces={};loadAPIWorkspace;constructor({context:t,loadAPIWorkspace:r,...i}){super(i),this.context=t,this.loadAPIWorkspace=r}async getDefinition({context:t},r){return(await this.toFernWorkspace({context:t},r)).definition}async toFernWorkspace({context:t},r){let i=(0,eGp.default)(r??{}),n=this.fernWorkspaces[i];if(n==null){let a=t||this.context,u=Lu(this.absoluteFilePath,Xa.of(i5)),l=await Dbs({absolutePathToWorkspace:this.absoluteFilePath,context:a}),f=await K$p(u,"{yml,yaml}"),s=await Y$p(f);if(!s.didSucceed)return zRo(s.failures,a.logger),a.failAndThrow();let o=k$p({files:s.files,absolutePathToDefinition:u});if(!o.didSucceed)return zRo(o.failures,a.logger),a.failAndThrow();let c=await X$p({dependenciesConfiguration:l,structuralValidationResult:o,context:a,cliVersion:this.cliVersion,settings:r,loadAPIWorkspace:this.loadAPIWorkspace});if(!c.didSucceed)return zRo(c.failures,a.logger),a.failAndThrow();n=new mDe({absoluteFilePath:this.absoluteFilePath,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:l,workspaceName:this.workspaceName,definition:{absoluteFilePath:u,rootApiFile:o.rootApiFile,namedDefinitionFiles:o.namedDefinitionFiles,packageMarkers:c.packageMarkers,importedDefinitions:c.importedDefinitions},cliVersion:this.cliVersion,sources:[]}),this.fernWorkspaces[i]=n}return n}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};function k7(e){let t=YLD(e),{value:r,done:i}=AKs(t,"{");return i?{head:r,parts:[]}:{head:r,parts:[...KLD(t)]}}function*KLD(e){let t;do{let{value:r}=AKs(e,"}"),i=AKs(e,"{");t=i.done,yield{pathParameter:r,tail:i.value}}while(!t)}function*YLD(e){for(let t of e)yield t}function AKs(e,t){let r="",i=e.next();for(;i.done!==!0&&i.value!==t;)r+=i.value,i=e.next();return{value:r,done:i.done??!1}}function Yva(e){let t=2166136261;function r(n,a){if(typeof n=="object"&&n!=null){if(a>64){i("[MaxDepthExceeded]");return}if(Array.isArray(n)){i("[");for(let u=0;u<n.length;u++)u>0&&i(","),r(n[u],a+1);i("]")}else i("{"),Object.keys(n).sort().forEach((l,f)=>{f>0&&i(","),i(l),i(":"),r(n[l],a+1)}),i("}")}else i(String(n))}function i(n){for(let a=0;a<n.length;a++){let u=n.charCodeAt(a);t^=u,t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24),t>>>=0}}return r(e,0),t.toString(16)}function vZt({typeReference:e,typeDeclarations:t}){if(e.type==="container"&&e.container.type==="optional")return!0;if(e.type==="named"){let r=t?.[e.typeId];if(r?.shape.type==="alias"&&r?.shape.resolvedType.type==="container"&&r?.shape.resolvedType.container.type==="optional")return!0}return!1}function tGp({fieldName:e,containerType:t,maxDepth:r,currentDepth:i,typeDeclarations:n,skipOptionalProperties:a}){if(i>=r)return bZt({containerType:t});switch(t.type){case"list":{let u=aq({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?bZt({containerType:t}):{type:"success",example:YO.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:YO.literal({literal:t.literal._visit({boolean:u=>Td.boolean(u),string:u=>Td.string({original:u}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:t.literal._visit({boolean:u=>u,string:u=>u,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":{if(a)return bZt({containerType:t});let u=aq({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?bZt({containerType:t}):{type:"success",example:YO.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"nullable":{if(a)return bZt({containerType:t});let u=aq({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?bZt({containerType:t}):{type:"success",example:YO.nullable({nullable:u.example,valueType:t.nullable}),jsonExample:u.jsonExample}}case"set":{let u=aq({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?bZt({containerType:t}):{type:"success",example:YO.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=aq({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a}),l=aq({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"||l.type==="failure"?bZt({containerType:t}):{type:"success",example:YO.map({map:[{key:u.example,value:l.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:l.jsonExample}}}default:Mo(t)}}function bZt({containerType:e}){switch(e.type){case"list":return{type:"success",example:YO.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:YO.literal({literal:e.literal._visit({boolean:t=>Td.boolean(t),string:t=>Td.string({original:t}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:e.literal._visit({boolean:t=>t,string:t=>t,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":return{type:"success",example:YO.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:YO.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:YO.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:YO.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:Mo(e)}}function iGp({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return tUD({fieldName:e,default_:XLD(t.v2),validation:ZLD(t.v2)});case"BASE_64":return{type:"success",example:Td.base64(My.BASE64),jsonExample:My.BASE64};case"BOOLEAN":return{type:"success",example:Td.boolean(My.BOOLEAN),jsonExample:My.BOOLEAN};case"DATE":return{type:"success",example:Td.date(My.DATE),jsonExample:My.DATE};case"DATE_TIME":return{type:"success",example:Td.datetime({datetime:new Date(My.DATE_TIME),raw:My.DATE_TIME}),jsonExample:My.DATE_TIME};case"DOUBLE":return rUD({fieldName:e,validation:kLD(t.v2)});case"FLOAT":return{type:"success",example:Td.float(My.FLOAT),jsonExample:My.FLOAT};case"INTEGER":return iUD({fieldName:e,validation:eUD(t.v2)});case"UINT_64":return{type:"success",example:Td.uint64(My.INT64),jsonExample:My.INT64};case"UINT":return{type:"success",example:Td.uint(My.UINT),jsonExample:My.UINT};case"BIG_INTEGER":return{type:"success",example:Td.bigInteger(My.INT64.toString()),jsonExample:`${My.INT64}`};case"LONG":return{type:"success",example:Td.long(My.INT64),jsonExample:My.INT64};case"UUID":return{type:"success",example:Td.uuid(My.UUID),jsonExample:My.UUID};default:Mo(t.v1)}}function XLD(e){if(e?.type==="string")return e.default}function ZLD(e){if(e?.type==="string")return e.validation}function kLD(e){if(e?.type==="double")return e.validation}function eUD(e){if(e?.type==="integer")return e.validation}function rGp(e){if(e<=My.SAMPLE_STRINGS.length){let t=My.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return My.SAMPLE_STRINGS[My.SAMPLE_STRINGS.length-1]+".".repeat(e-My.SAMPLE_STRINGS.length)}function tUD({fieldName:e,default_:t,validation:r}){if(t!=null)return{type:"success",example:Td.string({original:t}),jsonExample:t};if(r){let n=r.minLength,a=r.maxLength;if(n){let u=rGp(n);return{type:"success",example:Td.string({original:u}),jsonExample:u}}else if(a){let u=rGp(a);return{type:"success",example:Td.string({original:u}),jsonExample:u}}}let i=e??My.STRING;return{type:"success",example:Td.string({original:i}),jsonExample:i}}function rUD({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Td.double(r),jsonExample:r};if(i)return{type:"success",example:Td.double(i),jsonExample:i}}return{type:"success",example:Td.double(My.DOUBLE),jsonExample:My.DOUBLE}}function iUD({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Td.integer(r),jsonExample:r};if(i)return{type:"success",example:Td.integer(i),jsonExample:i}}return{type:"success",example:Td.integer(My.INT),jsonExample:My.INT}}function xEn({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=aq({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:l,jsonExample:f}=u;return{type:"success",example:uw.alias({value:l}),jsonExample:f}}case"enum":{let u=r.shape.values[0];return u==null?{type:"failure",message:"No enum values present"}:{type:"success",example:uw.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u={},l=[];if(r.shape.extends!=null)for(let c of r.shape.extends){let b=t[c.typeId];if(b==null)continue;let g=xEn({fieldName:e,typeDeclaration:b,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});g!=null&&g.type==="success"&&g.example.type==="object"&&(Object.assign(u,g.jsonExample),l.push(...g.example.properties))}let f=nUD({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:n,maxDepth:i,skipOptionalProperties:a});if(f.type==="failure")return f;let{example:s,jsonExample:o}=f;return{type:"success",example:uw.object({...s,properties:[...l,...s.properties]}),jsonExample:Object.assign({},u,o)}}case"undiscriminatedUnion":{let u=0;for(let l of r.shape.members){let f=aq({fieldName:e,typeReference:l.type,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});if(f.type==="failure"){++u;continue}let{example:s,jsonExample:o}=f;return{type:"success",example:uw.undiscriminatedUnion({index:u,singleUnionType:s}),jsonExample:o}}break}case"union":{let u=r.shape.discriminant,l={};if(r.shape.baseProperties!=null)for(let f of r.shape.baseProperties){let s=aq({fieldName:f.name.wireValue,typeReference:f.valueType,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});s.type==="success"&&(l[f.name.wireValue]=s.jsonExample)}for(let f of r.shape.types){let s=f.shape._visit({noProperties:()=>({type:"success",example:uw.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:lF.noProperties()}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,...l}}),samePropertiesAsObject:o=>{let c=t[o.typeId];if(c==null)return{type:"failure",message:`Failed to find type declaration with id ${o.typeId}`};let b=xEn({currentDepth:n,maxDepth:i,fieldName:e,typeDeclaration:c,typeDeclarations:t,skipOptionalProperties:a});if(b==null)return{type:"failure",message:"Failed to generate example for type reference"};if(b.type==="failure")return b;let{example:g,jsonExample:O}=b;return{type:"success",example:uw.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:lF.samePropertiesAsObject({typeId:c.name.typeId,object:g.type==="object"?g:{properties:[]}})}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,...typeof O=="object"?O:{},...l}}},singleProperty:o=>{let c=aq({currentDepth:n+1,maxDepth:i,fieldName:e,typeReference:o.type,typeDeclarations:t,skipOptionalProperties:a});if(c.type==="failure")return c;let{example:b,jsonExample:g}=c;return{type:"success",example:uw.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:lF.singleProperty(b)}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,[o.name.wireValue]:g,...l}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(s.type!=="failure")return s}}}return{type:"failure",message:"Failed to generate example for type reference"}}function nUD({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:i,maxDepth:n,currentDepth:a,skipOptionalProperties:u}){let l={},f=[];for(let s of[...r.properties??[],...r.extendedProperties??[]]){let o=aq({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:i,currentDepth:a+1,maxDepth:n,skipOptionalProperties:u});if(o.type==="failure"&&!vZt({typeDeclarations:i,typeReference:s.valueType}))return{type:"failure",message:`Failed to generate required property ${s.name.wireValue} b/c ${o.message}`};if(o.type==="failure")continue;let{example:c,jsonExample:b}=o;f.push({name:s.name,originalTypeDeclaration:t.name,value:c}),l[s.name.wireValue]=b}return{type:"success",example:uw.object({properties:f}),jsonExample:l}}function aq({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){if(n>i)return{type:"failure",message:"Exceeded max depth"};switch(t.type){case"named":{let u=r[t.typeId];if(u==null)return{type:"failure",message:`Failed to find type declaration with id ${t.typeId}`};let l=xEn({fieldName:e,typeDeclaration:u,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(l==null)return{type:"failure",message:"Failed to generate example for type declaration"};if(l.type==="failure")return l;let{example:f,jsonExample:s}=l;return{type:"success",example:{jsonExample:s,shape:Ph.named({shape:f,typeName:u.name})},jsonExample:s}}case"container":{let u=tGp({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure"){let{example:s,jsonExample:o}=bZt({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:Ph.container(s)},jsonExample:o}}let{example:l,jsonExample:f}=u;return{type:"success",example:{jsonExample:f,shape:Ph.container(l)},jsonExample:f}}case"primitive":{let{jsonExample:u,example:l}=iGp({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:Ph.primitive(l)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:Ph.unknown(u)},jsonExample:u}}}}function wFi(e,t){let r=[];for(let i of e){let n=aq({fieldName:i.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,value:n.example})}return{type:"success",example:r,jsonExample:void 0}}function IEn(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&vZt({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=aq({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,value:n.example})}return{type:"success",example:r,jsonExample:void 0}}function RRo(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&vZt({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=aq({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??10,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,shape:i.allowMultiple?B2.exploded():B2.single(),value:n.example})}return{type:"success",example:r,jsonExample:void 0}}var qKs=Bf.primitive({v1:Zb.String,v2:wp.string({default:void 0,validation:void 0})});function Xva({ir:e,endpoint:t,service:r,typeDeclarations:i,skipOptionalRequestProperties:n,generationResponse:a}){let u={name:void 0,endpointHeaders:[],endpointPathParameters:[],queryParameters:[],servicePathParameters:[],serviceHeaders:[],rootPathParameters:[],request:void 0,response:Qq.ok(uC.body(void 0)),docs:void 0},l=wFi(t.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(l.type==="failure")return l;u.endpointPathParameters=l.example;let f=wFi(r.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(f.type==="failure")return f;u.servicePathParameters=f.example;let s=wFi(e.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(s.type==="failure")return s;u.rootPathParameters=s.example;let o=RRo(t.queryParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:10});if(o.type==="failure")return o;u.queryParameters=o.example;let c=IEn(t.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(c.type==="failure")return c;u.endpointHeaders=c.example;let b=IEn(r.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(b.type==="failure")return b;if(u.serviceHeaders=b.example,t.requestBody!=null)switch(t.requestBody.type){case"bytes":return{type:"failure",message:"Bytes request unsupported"};case"fileUpload":return{type:"failure",message:"File upload unsupported"};case"inlinedRequestBody":{let g={},O=[];if(t.requestBody.extends!=null)for(let m of t.requestBody.extends){let P=i[m.typeId];if(P==null)throw new Error(`Failed to find extended type declaration with id ${m.typeId}`);let E=xEn({typeDeclaration:P,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});E!=null&&E.type==="success"&&Object.assign(g,E.jsonExample)}for(let m of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let P=aq({fieldName:m.name.wireValue,typeReference:m.valueType,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});if(P.type==="failure"&&!vZt({typeDeclarations:i,typeReference:m.valueType}))return{type:"failure",message:`Failed to generate required property ${m.name.wireValue} b/c ${P.message}`};if(P.type==="failure")continue;let{example:E,jsonExample:q}=P;O.push({name:m.name,originalTypeDeclaration:void 0,value:E}),g[m.name.wireValue]=q}u.request=uG.inlinedRequestBody({jsonExample:g,properties:O});break}case"reference":{let g=aq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.request=uG.reference(O);break}default:Mo(t.requestBody)}if(a.type==="success"&&t.response?.body!=null)switch(t.response.body.type){case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":{let g=aq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=Qq.ok(uC.body({...O,jsonExample:m}));break}case"streamParameter":{let g;switch(t.response.body.nonStreamResponse.type){case"bytes":return{type:"failure",message:"Bytes unsupported"};case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":g=aq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":g=aq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:qKs,skipOptionalProperties:!1});break;default:Mo(t.response.body.nonStreamResponse)}if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=Qq.ok(uC.body({...O,jsonExample:m}));break}case"streaming":{let g;switch(t.response.body.value.type){case"sse":{if(g=aq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=Qq.ok(uC.sse([{data:{...O,jsonExample:m},event:""}]));break}case"json":{if(g=aq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=Qq.ok(uC.stream([{...O,jsonExample:m}]));break}case"text":{if(g=aq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:qKs,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=Qq.ok(uC.stream([{...O,jsonExample:m}]));break}default:Mo(t.response.body.value)}break}case"text":{let g=aq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:qKs,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=Qq.ok(uC.body({...O,jsonExample:m}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:Mo(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=Qq.error({body:void 0,error:a.declaration.name});else{let g=aq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:a.declaration.type,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.response=Qq.error({body:O,error:a.declaration.name})}try{return{type:"success",example:{id:Yva(u),url:aUD(t,u),...u},jsonExample:void 0}}catch(g){return{type:"failure",message:`Parse failure with exceptions ${g}`}}}function aUD(e,t){let r={};[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.fullPath.head+e.fullPath.parts.map(n=>r[n.pathParameter]+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function aGp({ir:e,channel:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let n={name:void 0,pathParameters:[],headers:[],queryParameters:[],messages:[],docs:void 0},a=wFi(t.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(a.type==="failure")return a;n.pathParameters.push(...a.example);let u=wFi(e.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(u.type==="failure")return u;n.pathParameters.push(...u.example);let l=RRo(t.queryParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:10});if(l.type==="failure")return l;n.queryParameters=l.example;let f=IEn(t.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(f.type==="failure")return f;n.headers.push(...f.example);let s=IEn(e.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(s.type==="failure")return s;n.headers.push(...s.example);let c=t.messages.filter(O=>O.origin==="client")[0];if(c!=null){let O=nGp({message:c,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:c.type,body:O})}let g=t.messages.filter(O=>O.origin==="server")[0];if(g!=null){let O=nGp({message:g,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:g.type,body:O})}return{type:"success",example:{...n,url:oUD(t,n)},jsonExample:void 0}}function nGp({message:e,typeDeclarations:t,skipOptionalRequestProperties:r}){if(e.body.type==="inlinedBody")return;let i=aq({currentDepth:0,maxDepth:10,typeDeclarations:t,typeReference:e.body.bodyType,skipOptionalProperties:r});if(i.type==="success")return WSe.reference(i.example)}function oUD(e,t){let r={};[...t.pathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.path.head+e.path.parts.map(n=>r[n.pathParameter]+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function gZt(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{},i=Object.values(t)[0],n=Object.values(r)[0];return{userExample:i,autoExample:n}}function oGp({service:e,endpoint:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let n={pathParameters:{},queryParameters:{},headers:{}};for(let a of t.pathParameters){let{userExample:u,autoExample:l}=gZt(a.v2Examples);u!==void 0?n.pathParameters[a.name.originalName]=u:l!==void 0&&(n.pathParameters[a.name.originalName]=l)}for(let a of t.queryParameters){let{userExample:u,autoExample:l}=gZt(a.v2Examples);if(u!==void 0)n.queryParameters[a.name.name.originalName]=u;else if(l!==void 0){if(i&&vZt({typeReference:a.valueType,typeDeclarations:r}))continue;n.queryParameters[a.name.name.originalName]=l}}for(let a of t.headers){let{userExample:u,autoExample:l}=gZt(a.v2Examples);if(u!==void 0)n.headers[a.name.name.originalName]=u;else if(l!==void 0){if(i&&vZt({typeReference:a.valueType,typeDeclarations:r}))continue;n.headers[a.name.name.originalName]=l}}return n}function uGp({endpoint:e,service:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let{pathParameters:n,queryParameters:a,headers:u}=oGp({service:t,endpoint:e,typeDeclarations:r,skipOptionalRequestProperties:i}),l={endpoint:{method:e.method,path:e.path.head},baseUrl:void 0,environment:e.baseUrl,auth:void 0,pathParameters:n,queryParameters:a,headers:u,requestBody:void 0,docs:void 0};if(e.requestBody!=null)switch(e.requestBody.type){case"bytes":break;case"fileUpload":{let{userExample:f,autoExample:s}=gZt(e.requestBody.v2Examples),o=f??s;l.requestBody=o;break}case"inlinedRequestBody":{let{userExample:f,autoExample:s}=gZt(e.requestBody.v2Examples),o=f??s;l.requestBody=o;break}case"reference":{let{userExample:f,autoExample:s}=gZt(e.requestBody.v2Examples),o=f??s;l.requestBody=o;break}default:Mo(e.requestBody)}return l}function cGp({endpoint:e,typeDeclarations:t,skipOptionalRequestProperties:r}){let i={statusCode:e.response?.statusCode,body:void 0,docs:void 0};if(e.response==null)return i;if(e.response.body==null)return e.source?.type==="openrpc"&&(i.body=N8t.json(sGp(null))),i;switch(e.response.body.type){case"bytes":break;case"fileDownload":break;case"text":break;case"json":{let n=e.response.body.value;if(n.type==="response"){let{userExample:a,autoExample:u}=gZt(n.v2Examples),l=a??u;if(l!==void 0){let f=e.source?.type==="openrpc"?sGp(l):l;i.body=N8t.json(f)}}break}case"streaming":break;case"streamParameter":break;default:Mo(e.response.body)}return i}function sGp(e,t=1){return{id:t,jsonrpc:"2.0",result:e}}function lGp({ir:e,endpoint:t,service:r,typeDeclarations:i,skipOptionalRequestProperties:n}){let a={request:void 0,response:void 0,codeSamples:void 0};return a.request=uGp({endpoint:t,service:r,typeDeclarations:i,skipOptionalRequestProperties:n}),a.response=cGp({endpoint:t,typeDeclarations:i,skipOptionalRequestProperties:n}),{name:`${t.name.originalName}_example`,example:a}}function bYr({ir:e,exampleGeneration:t}){for(let[r,i]of Object.entries(e.services))for(let n of i.endpoints){if(n.userSpecifiedExamples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let a=Xva({ir:e,service:i,endpoint:n,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples,generationResponse:{type:"success"}});if(a.type==="failure")continue;let{example:u}=a;n.autogeneratedExamples=[{example:u}]}for(let[r,i]of Object.entries(e.websocketChannels??{})){if(i.examples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let n=aGp({ir:e,channel:i,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});if(n.type==="failure")continue;let{example:a}=n;i.examples=[...i.examples,a]}return e}function SFi({ir:e,exampleGeneration:t}){for(let[r,i]of Object.entries(e.services))for(let n of i.endpoints){if(Object.keys(n.v2Examples?.userSpecifiedExamples??{}).length>0)continue;let a=lGp({ir:e,service:i,endpoint:n,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});n.v2Examples==null&&(n.v2Examples={userSpecifiedExamples:{},autogeneratedExamples:{}}),n.v2Examples.autogeneratedExamples={[a.name]:a.example}}return e}function NRo(e,t,r){let{environments:i,changedBaseUrlIds1:n,changedBaseUrlIds2:a}=uUD(e.environments,t.environments,r),{services:u,websocketChannels:l}=sUD(e,t,n,a);return{apiName:e.apiName,basePath:e.basePath,selfHosted:e.selfHosted&&t.selfHosted,apiDisplayName:e.apiDisplayName??t.apiDisplayName,apiDocs:e.apiDocs??t.apiDocs,auth:e.auth??t.auth,headers:[...e.headers??[],...t.headers??[]],environments:i,types:{...e.types??{},...t.types??{}},constants:{...e.constants??{},...t.constants??{}},errors:{...e.errors??{},...t.errors??{}},services:u,webhookGroups:{...e.webhookGroups??{},...t.webhookGroups??{}},subpackages:{...e.subpackages??{},...t.subpackages??{}},websocketChannels:l,rootPackage:{service:e.rootPackage.service??t.rootPackage.service,types:[...e.rootPackage.types??[],...t.rootPackage.types??[]],errors:[...e.rootPackage.errors??[],...t.rootPackage.errors??[]],subpackages:[...e.rootPackage.subpackages??[],...t.rootPackage.subpackages??[]],fernFilepath:e.rootPackage.fernFilepath??t.rootPackage.fernFilepath,webhooks:e.rootPackage.webhooks??t.rootPackage.webhooks,websocket:e.rootPackage.websocket??t.rootPackage.websocket,hasEndpointsInTree:e.rootPackage.hasEndpointsInTree||t.rootPackage.hasEndpointsInTree,navigationConfig:e.rootPackage.navigationConfig??t.rootPackage.navigationConfig,docs:e.rootPackage.docs??t.rootPackage.docs},fdrApiDefinitionId:e.fdrApiDefinitionId??t.fdrApiDefinitionId,apiVersion:e.apiVersion??t.apiVersion,idempotencyHeaders:[...e.idempotencyHeaders??[],...t.idempotencyHeaders??[]],pathParameters:[...e.pathParameters??[],...t.pathParameters??[]],errorDiscriminationStrategy:e.errorDiscriminationStrategy??t.errorDiscriminationStrategy,variables:[...e.variables??[],...t.variables??[]],serviceTypeReferenceInfo:e.serviceTypeReferenceInfo??t.serviceTypeReferenceInfo,readmeConfig:e.readmeConfig??t.readmeConfig,sourceConfig:e.sourceConfig??t.sourceConfig,publishConfig:e.publishConfig??t.publishConfig,dynamic:e.dynamic??t.dynamic,sdkConfig:e.sdkConfig??t.sdkConfig}}function uUD(e,t,r){if(e==null&&t==null)return{environments:void 0,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(t==null)return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(e==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(JSON.stringify(e)===JSON.stringify(t))return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let i=fGp(e),n=fGp(t);if(i&&n&&e.environments.type==="singleBaseUrl"&&t.environments.type==="singleBaseUrl")return{environments:{defaultEnvironment:e.defaultEnvironment??t.defaultEnvironment,environments:yI.singleBaseUrl({environments:[...e.environments.environments,...t.environments.environments]})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let a=i?t.defaultEnvironment:e.defaultEnvironment,u=e.environments,l=t.environments;if(u.type==="singleBaseUrl"&&l.type==="singleBaseUrl"){let f=i?l:u,s=i?u:l,o={},{deconflictedEnvironments2:c,changedBaseUrlIds2:b}=cUD(f,s,r);if(f.environments[0]==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let g="Base",O=r.generateName("Base");return f.environments.forEach(m=>{o[m.id]=g}),{environments:{defaultEnvironment:a,environments:yI.multipleBaseUrls({baseUrls:[{id:g,name:O},...c.environments.map(m=>({id:m.id,name:m.name}))],environments:f.environments.map(m=>({id:m.id,name:m.name,urls:{[g]:m.url,...Object.fromEntries(c.environments.map(P=>[P.id,P.url]))},docs:void 0}))})},changedBaseUrlIds1:i?b:o,changedBaseUrlIds2:i?o:b}}if(u.type==="multipleBaseUrls"&&l.type==="singleBaseUrl"||u.type==="singleBaseUrl"&&l.type==="multipleBaseUrls"){let f=u.type==="singleBaseUrl"?u:l,s=u.type==="multipleBaseUrls"?u:l,{deconflictedEnvironments1:o,changedBaseUrlIds1:c}=lUD(f,s,r);return{environments:{defaultEnvironment:a,environments:yI.multipleBaseUrls({baseUrls:[...s.baseUrls,...o.environments.map(b=>({id:b.id,name:b.name}))],environments:s.environments.map(b=>({...b,urls:{...b.urls,...Object.fromEntries(o.environments.map(g=>[g.id,g.url]))}}))})},changedBaseUrlIds1:u.type==="singleBaseUrl"?c:void 0,changedBaseUrlIds2:u.type==="singleBaseUrl"?void 0:c}}if(u.type==="multipleBaseUrls"&&l.type==="multipleBaseUrls"){let{deconflictedEnvironments:f,changedBaseUrlIds:s}=fUD(u,l,r);return{environments:{defaultEnvironment:a,environments:yI.multipleBaseUrls({baseUrls:[...u.baseUrls,...f.baseUrls],environments:u.environments.flatMap(o=>f.environments.map(c=>({...o,urls:{...o.urls,...c.urls}})))})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:s}}return{environments:e??t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0}}function sUD(e,t,r,i){if(r!=null)for(let[u,l]of Object.entries(r)){for(let f of Object.values(e.services))for(let s of Object.values(f.endpoints))s.baseUrl==u&&(s.baseUrl=l);for(let f of Object.values(e.websocketChannels??{}))f.baseUrl==u&&(f.baseUrl=l)}if(i!=null)for(let[u,l]of Object.entries(i)){for(let f of Object.values(t.services))for(let s of Object.values(f.endpoints))s.baseUrl==u&&(s.baseUrl=l);for(let f of Object.values(t.websocketChannels??{}))f.baseUrl==u&&(f.baseUrl=l)}let n={...e.services??{},...t.services??{}},a={...e.websocketChannels??{},...t.websocketChannels??{}};return{services:n,websocketChannels:a}}function cUD(e,t,r){let i={},n=new Set(e.environments.map(s=>s.id)),a=new Set(e.environments.map(s=>s.name)),u=new Map(e.environments.map(s=>[s.url,s.id])),l=t.environments.filter(s=>{let o=u.get(s.url);return o!=null?(i[s.id]=o,!1):!0}).map(s=>{if(n.has(s.id)||a.has(s.name)){let o=TKs(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s});return{deconflictedEnvironments2:yI.singleBaseUrl({environments:l}),changedBaseUrlIds2:i}}function lUD(e,t,r){let i={},n=new Set(t.baseUrls.map(f=>f.id)),a=new Set(t.baseUrls.map(f=>f.name)),u=e.environments.map(f=>{if(n.has(f.id)||a.has(f.name)){let s=TKs(f.id,n);return i[f.id]=s,{...f,id:s,name:r.generateName(s)}}return f});return{deconflictedEnvironments1:yI.singleBaseUrl({environments:u}),changedBaseUrlIds1:i}}function fUD(e,t,r){let i={},n=new Set(e.baseUrls.map(s=>s.id)),a=new Set(e.baseUrls.map(s=>s.name)),u=t.baseUrls.map(s=>{if(n.has(s.id)||a.has(s.name)){let o=TKs(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s}),l=t.environments.map(s=>({...s,urls:Object.fromEntries(Object.entries(s.urls).map(([o,c])=>[i[o]??o,c]))}));return{deconflictedEnvironments:yI.multipleBaseUrls({baseUrls:u,environments:l}),changedBaseUrlIds:i}}function fGp(e){return e.environments.type==="singleBaseUrl"?e.environments.environments.some(t=>t.url&&(t.url.startsWith("ws://")||t.url.startsWith("wss://"))):e.environments.type==="multipleBaseUrls"?e.environments.environments.some(t=>Object.values(t.urls).some(r=>r&&(r.startsWith("ws://")||r.startsWith("wss://")))):!1}function TKs(e,t){let r=e,i=1;for(;t.has(r);)r=`${e}-${i}`,i++;return r}function BKs({rawApiFileSchema:e,casingsGenerator:t}){if(e.auth==null)return{docs:void 0,requirement:Uxe.All,schemes:[]};let r=typeof e.auth!="string"?e.auth.docs:void 0;return Ixi(e.auth,{single:i=>{let n=dGp({reference:i,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t});return{docs:r,requirement:Uxe.All,schemes:[n]}},any:({any:i})=>({docs:r,requirement:Uxe.Any,schemes:i.map(n=>dGp({reference:n,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t}))})})}function dGp({reference:e,authSchemeDeclarations:t,casingsGenerator:r}){let i=(a,u)=>{let l=t?.[a];if(l==null)throw new Error("Unknown auth scheme: "+a);return nua(l,{header:f=>NC.header({docs:u,name:r.generateNameAndWireValue({name:f.name??a,wireValue:f.header}),valueType:Bf.primitive({v1:Zb.String,v2:wp.string({default:void 0,validation:void 0})}),prefix:f.prefix,headerEnvVar:f.env}),basic:f=>pGp({casingsGenerator:r,docs:u,rawScheme:f}),bearer:f=>CKs({casingsGenerator:r,docs:u,rawScheme:f}),oauth:f=>CKs({casingsGenerator:r,docs:u,rawScheme:void 0})})},n=typeof e=="string"?e:e.scheme;switch(n){case"bearer":case"oauth":return CKs({casingsGenerator:r,docs:void 0,rawScheme:void 0});case"basic":return pGp({casingsGenerator:r,docs:void 0,rawScheme:void 0});default:return i(n,typeof e!="string"?e.docs:void 0)}}function CKs({casingsGenerator:e,docs:t,rawScheme:r}){return NC.bearer({docs:t,token:e.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function pGp({casingsGenerator:e,docs:t,rawScheme:r}){return NC.basic({docs:t,username:e.generateName(r?.username?.name??"username"),usernameEnvVar:r?.username?.env,password:e.generateName(r?.password?.name??"password"),passwordEnvVar:r?.password?.env})}function zEn({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:XQr(i,{singleBaseUrl:()=>yI.singleBaseUrl(dUD({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>yI.multipleBaseUrls(pUD({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})}}function dUD({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>XQr(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:_Gp(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function pUD({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>XQr(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:nd(a.urls,u=>_Gp(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function _Gp(e){return e.endsWith("/")?e.slice(0,-1):e}function CDe(e){return e.allParts.map(t=>t.originalName).join("/")}var em={generateTypeId:e=>`type_${CDe(e.fernFilepath)}:${e.name.originalName}`,generateErrorId:e=>`error_${CDe(e.fernFilepath)}:${e.name.originalName}`,generateServiceId:e=>`service_${CDe(e.fernFilepath)}`,generateServiceIdFromFernFilepath:e=>`service_${CDe(e)}`,generateSubpackageId:e=>`subpackage_${CDe(e)}`,generateEndpointId:(e,t)=>{let r=CDe(e.fernFilepath),i=t.name.originalName;return`endpoint_${r}.${i}`},generateWebhookGroupId:e=>`webhooks_${CDe(e)}`,generateWebhookId:(e,t)=>`webhooks_${CDe(e)}.${t}`,generateWebSocketChannelId:e=>`channel_${CDe(e)}`};function REn(e){return e.type!=null}var FRo=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:f,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=f,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=em.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=em.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=em.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)}};function DFi(e){let t={};for(let[r,i]of Object.entries(e))if(typeof i!="string")for(let n of i.audiences??[])t[n]==null&&(t[n]=new Set),t[n]?.add(r);return t}var EFi=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=_UD(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let u=em.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=em.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=em.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&Dz(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=em.generateServiceId(t.name),a=r.id,u=new Set,l=new Set,f=new Set;for(let s of[...t.headers,...r.headers])Dz(s.valueType,u,f);for(let s of[...t.pathParameters,...r.pathParameters])Dz(s.valueType,u,f);for(let s of r.queryParameters)Dz(s.valueType,u,f);if(i!=null&&i.request!=null&&typeof i.request!="string"){let s=DFi(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:s}}r.requestBody!=null&&FC._visit(r.requestBody,{inlinedRequestBody:s=>{for(let o of s.extends)LRo(o,u,f);for(let o of s.properties)Dz(o.valueType,u,f);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&oC(i.request.body)){let o=DFi(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:s})=>{Dz(s,u,f)},fileUpload:({properties:s})=>{for(let o of s)O5._visit(o,{file:Go,bodyProperty:({valueType:c})=>{Dz(c,u,f)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+o.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&SM._visit(r.response.body,{fileDownload:Go,json:s=>{Dz(s.responseBodyType,u,f)},streaming:s=>{s._visit({sse:o=>Dz(o.payload,u,f),json:o=>Dz(o.payload,u,f),text:Go,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.type)}})},streamParameter:s=>{s.streamResponse._visit({sse:o=>Dz(o.payload,u,f),json:o=>Dz(o.payload,u,f),text:Go,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.streamResponse.type)}}),s.nonStreamResponse.type==="json"&&Dz(s.nonStreamResponse.value.responseBodyType,u,f)},text:Go,bytes:Go,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(s=>{l.add(em.generateErrorId(s.error)),f.add(s.error.fernFilepath)}),this.endpoints[a]={endpointId:a,serviceId:n,referencedTypes:u,referencedErrors:l,referencedSubpackages:f}}markEndpointForAudience(t,r,i){if(this.hasAudience(i)){let n=em.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&&aV._visit(r.payload,{inlinedPayload:l=>{for(let f of l.extends)LRo(f,a,u);for(let f of l.properties)Dz(f.valueType,a,u);if(i?.payload!=null&&typeof i.payload=="object"&&!REn(i.payload)){let f=DFi(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:f}}},reference:({payloadType:l})=>{Dz(l,a,u)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),u.add(t),this.webhooks[n]={webhookId:n,referencedTypes:a,referencedSubpackages:u}}markWebhookForAudiences(t,r,i){let n=r.id;n!=null&&this.hasAudience(i)&&(this.webhooksNeededForAudience.add(n),this.addSubpackages(t))}addChannel(t,r,i,n){if(r==null)return;let a=new Set,u=new Set;for(let l of i.messages)P5._visit(l.body,{reference:({bodyType:f})=>{Dz(f,a,u)},inlinedBody:f=>{for(let s of f.extends)LRo(s,a,u);for(let s of f.properties)Dz(s.valueType,a,u)},_other:()=>{}});u.add(t),this.channels[r]={channelId:r,referencedTypes:a,referencedSubpackages:u}}markChannelForAudiences(t,r,i){r!=null&&this.hasAudience(i)&&(this.channelsNeededForAudience.add(r),this.addSubpackages(t))}build(){let t=new Set,r=new Set;for(let l of this.endpointsNeededForAudience.keys()){let f=this.getEndpointNode(l);for(let s of f.referencedErrors){if(r.has(s))continue;r.add(s);let o=this.getErrorNode(s);this.addReferencedTypes(t,o.referencedTypes)}this.addReferencedTypes(t,f.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let l of this.webhooksNeededForAudience.keys()){let f=this.getWebhookNode(l);this.addReferencedTypes(t,f.referencedTypes)}for(let l of this.channelsNeededForAudience.keys()){let f=this.getChannelNode(l);this.addReferencedTypes(t,f.referencedTypes)}let i={},n={},a={},u={};if(this.audiences.type==="filtered"){for(let[l,f]of Object.entries(this.properties)){if(!t.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=f.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,f]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=f.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}n[l]=s.size>0?s:void 0}for(let[l,f]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=f.parametersByAudience[o];c?.forEach(b=>{s.add(b)})}a[l]=s.size>0?s:void 0}for(let[l,f]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=f.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}u[l]=s.size>0?s:void 0}}return new FRo({types:t,properties:i,errors:r,requestProperties:n,queryParameters:a,environments:this.environmentsNeededForAudience,services:this.servicesNeededForAudience,endpoints:this.endpointsNeededForAudience,webhooks:this.webhooksNeededForAudience,webhookPayloadProperties:u,subpackages:this.subpackagesNeededForAudience,channels:this.channelsNeededForAudience})}markTypeForService(t,r){let i=this.typesReferencedByService[t]??=new Set;if(i.has(r))return;i.add(r);let n=this.getTypeNode(t);for(let a of n.allDescendants)this.markTypeForService(a,r)}addReferencedTypes(t,r){for(let i of r){if(t.has(i))continue;t.add(i);let n=this.getTypeNode(i);if(this.audiences.type==="filtered")for(let a of this.audiences.audiences){let u=n.descendantsByAudience[a];if(u!=null)u.forEach(l=>{t.add(l)});else{n.allDescendants.forEach(l=>{t.add(l)});break}}else n.allDescendants.forEach(a=>{t.add(a)})}}getTypeNode(t){let r=this.types[t];if(r==null)throw new Error(`Failed to find type node with id ${t}`);return r}getErrorNode(t){let r=this.errors[t];if(r==null)throw new Error(`Failed to find error node with id ${t}`);return r}getEndpointNode(t){let r=this.endpoints[t];if(r==null)throw new Error(`Failed to find endpoint node with id ${t}`);return r}getWebhookNode(t){let r=this.webhooks[t];if(r==null)throw new Error(`Failed to find webhook node with id ${t}`);return r}getChannelNode(t){let r=this.channels[t];if(r==null)throw new Error(`Failed to find channel node with id ${t}`);return r}hasNoAudiences(){return this.audiences.type==="none"}hasAudience(t){let r=this.audiences;switch(r.type){case"none":return!0;case"filtered":return t.some(i=>r.audiences.has(i));default:Mo(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(em.generateSubpackageId(i))}}};function _UD(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:Mo(e)}}function Dz(e,t,r){Bf._visit(e,{container:i=>{hUD(i,t,r)},named:i=>{LRo(i,t,r)},primitive:Go,unknown:Go,_other:Go})}function LRo(e,t,r){t.add(em.generateTypeId(e)),r.add(e.fernFilepath)}function hUD(e,t,r){Tv._visit(e,{list:i=>{Dz(i,t,r)},map:i=>{Dz(i.keyType,t,r),Dz(i.valueType,t,r)},optional:i=>{Dz(i,t,r)},nullable:i=>{Dz(i,t,r)},set:i=>{Dz(i,t,r)},literal:Go,_other:Go})}var hne={};jo(hne,{FernAvailabilityExtension:()=>URo,FernEnumExtension:()=>VRo,FernIgnoreExtension:()=>MFi,FernOptionalExtension:()=>WRo,FernTypeExtension:()=>GRo,SdkGroupNameExtension:()=>HRo,SdkMethodNameExtension:()=>$Ro});var dS=class{breadcrumbs;context;constructor(t){this.breadcrumbs=t.breadcrumbs,this.context=t.context}getExtensionValue(t){if(!(typeof t!="object"||t==null))return t[this.key]}};var URo=class extends dS{node;key="x-fern-availability";constructor({breadcrumbs:t,node:r,context:i}){super({breadcrumbs:t,context:i}),this.node=r}async convert(){let t=this.getExtensionValue(this.node);if(t==null||typeof t!="string")return;switch(t.toUpperCase().replace(/[-_\s]/g,"_")){case"IN_DEVELOPMENT":return g5.InDevelopment;case"PRE_RELEASE":return g5.PreRelease;case"GENERAL_AVAILABILITY":return g5.GeneralAvailability;case"DEPRECATED":return g5.Deprecated;default:return}}};var yUD=pu.object({snake:pu.string().optional(),camel:pu.string().optional(),screamingSnake:pu.string().optional(),pascal:pu.string().optional()}),vUD=pu.object({description:pu.string().optional(),name:pu.string().optional(),casing:yUD.optional()}),hGp=pu.record(vUD);var VRo=class extends dS{schema;key="x-fern-enum";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t==null)return;let r=hGp.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-enum extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data}};var MFi=class extends dS{operation;key="x-fern-ignore";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-ignore",path:this.breadcrumbs});return}return t}}};var WRo=class extends dS{parameter;key="x-fern-optional";constructor({breadcrumbs:t,parameter:r,context:i}){super({breadcrumbs:t,context:i}),this.parameter=r}convert(){let t=this.getExtensionValue(this.parameter);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-optional",path:this.breadcrumbs});return}return t}}};var HRo=class extends dS{operation;key="x-fern-sdk-group-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(i=>typeof i=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{groups:r}}};var $Ro=class extends dS{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null&&typeof t=="string")return{methodName:t}}};var GRo=class extends dS{schema;key="x-fern-type";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t!=null&&typeof t=="string")return t}};var w0=class{ir;breadcrumbs=[];context;static STRING=Ks.TypeReference.primitive({v1:"STRING",v2:Ks.PrimitiveTypeV2.string({default:void 0,validation:void 0})});constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r,this.ir={auth:{docs:void 0,requirement:Ks.AuthSchemesRequirement.All,schemes:[]},selfHosted:!1,types:{},services:{},errors:{},webhookGroups:{},websocketChannels:void 0,headers:[],idempotencyHeaders:[],apiVersion:void 0,apiDisplayName:void 0,apiDocs:void 0,basePath:void 0,pathParameters:[],errorDiscriminationStrategy:Ks.ErrorDiscriminationStrategy.statusCode(),variables:[],serviceTypeReferenceInfo:{sharedTypes:[],typesReferencedOnlyByService:{}},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,environments:void 0,fdrApiDefinitionId:void 0,rootPackage:r.createPackage(),subpackages:{},sdkConfig:{hasFileDownloadEndpoints:!1,hasPaginatedEndpoints:!1,hasStreamingEndpoints:!1,isAuthMandatory:!0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}}}}async resolveExternalRefs({spec:t,context:r}){let i=[t];for(;i.length>0;){let n=i.shift();n!=null&&(Array.isArray(n)?await this.resolveExternalRefsInArray(n,r,i):typeof n=="object"&&await this.resolveExternalRefsInObject(n,r,i))}return t}async resolveExternalRefsInArray(t,r,i){for(let n=0;n<t.length;n++)t[n]=await this.resolveReferenceChain(t[n],r,i)}async resolveExternalRefsInObject(t,r,i){for(let[n,a]of Object.entries(t))t[n]=await this.resolveReferenceChain(a,r,i)}async resolveReferenceChain(t,r,i){let n=t;if(!this.context.isReferenceObject(n))return i.push(n),t;for(;this.context.isReferenceObject(n);){let a=this.context.isExternalReference(n.$ref),u=await r.resolveReference({$ref:n.$ref});if(u.resolved){if(n=u.value,a)return n}else return t}return t}removeXFernIgnores({document:t,context:r,breadcrumbs:i=[]}){return Array.isArray(t)?t.filter((n,a)=>!new MFi({breadcrumbs:[...i,String(a)],operation:n,context:r}).convert()).map((n,a)=>this.removeXFernIgnores({document:n,context:r,breadcrumbs:[...i,String(a)]})):t!=null&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([n,a])=>!new MFi({breadcrumbs:[...i,n],operation:a,context:r}).convert()).map(([n,a])=>[n,this.removeXFernIgnores({document:a,context:r,breadcrumbs:[...i,n]})])):t}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...t??[]),r.length==0)return this.ir.rootPackage;let i=this.ir.rootPackage;for(let n=0;n<r.length;n++){let a=$y(r[n]),l=`subpackage_${r.slice(0,n+1).map(s=>$y(s)).join(".")}`;this.ir.subpackages[l]==null&&(this.ir.subpackages[l]={name:this.context.casingsGenerator.generateName(a),...this.context.createPackage({name:a})});let f=this.ir.subpackages[l];i.subpackages.includes(l)||i.subpackages.push(l),i=f}return i}};var yGp={[Yh.GenerationLanguage.PHP]:new Set(["abstract","and","as","break","callable","case","catch","class","clone","const","continue","declare","default","do","echo","else","elseif","enddeclare","endfor","endforeach","endif","endswitch","endwhile","extends","final","finally","fn","for","foreach","function","global","goto","list","if","implements","include","include_once","instanceof","insteadof","interface","match","namespace","new","or","parent","Parent","print","private","protected","public","readonly","require","require_once","return","static","switch","throw","trait","try","use","var","while","xor","yield"].flatMap(e=>[e,dx(e)])),[Yh.GenerationLanguage.TYPESCRIPT]:new Set(["any","as","boolean","break","case","catch","class","const","constructor","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","let","module","new","null","number","of","package","private","protected","public","require","return","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","Date","Error","File","Object","Record"]),[Yh.GenerationLanguage.JAVA]:new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","false","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","true","try","void","volatile","while"]),[Yh.GenerationLanguage.PYTHON]:new Set(["False","None","True","and","as","assert","async","","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","float","int","complex","bool","uuid","list","set","map","long","self","all"]),[Yh.GenerationLanguage.GO]:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[Yh.GenerationLanguage.RUBY]:new Set(["__ENCODING__","__LINE__","__FILE__","alias","and","begin","break","case","class","def","defined","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield","Object","JSON","Date","DateTime"]),[Yh.GenerationLanguage.CSHARP]:new Set(["abstract","as","base","bool","break","byte","case","catch","char","checked","class","const","continue","decimal","default","delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","goto","if","implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","operator","out","override","params","private","protected","public","readonly","ref","return","sbyte","sealed","short","sizeof","stackalloc","static","string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","ushort","using","virtual","void","volatile","while","add","and","alias","ascending","args","async","","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","managed","nameof","nint","not","notnull","nuint","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value","var","when","where","with","yield"]),[Yh.GenerationLanguage.SWIFT]:new Set([])};var bUD=["go","ruby"];function BDe({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let u=c=>({unsafeName:c,safeName:gUD({name:c,keywords:OUD({generationLanguage:e,keywords:t})})}),l=$y(n),f=dx(l),s=qCi(n),o=DCi(l);return r&&(!jUD(o)&&(e==null||bUD.includes(e))&&(l=o.map((c,b)=>{if(b>0){let g=QRo(c);if(g!=null)return g;if(JRo(c))return c.toUpperCase()}return c}).join(""),f=o.map((c,b)=>{let g=QRo(c);return g??(JRo(c)?c.toUpperCase():b===0?dx(c):c)}).join("")),s=n.split(" ").map(c=>c.split(/(\d+)/).map(qCi).join("")).join("_")),{originalName:n,camelCase:u(a?.casingOverrides?.camel??l),snakeCase:u(a?.casingOverrides?.snake??s),screamingSnakeCase:u(a?.casingOverrides?.["screaming-snake"]??s.toUpperCase()),pascalCase:u(a?.casingOverrides?.pascal??f)}},generateNameAndWireValue:({name:n,wireValue:a,opts:u})=>({name:i.generateName(n,u),wireValue:a})};return i}function gUD({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":PUD(e)?"_"+e:e}function OUD({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return yGp[e]}var mUD=/^[0-9]/;function PUD(e){return mUD.test(e)}function jUD(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=QRo(i)!=null||JRo(i),a=QRo(t)!=null||JRo(t);return n&&a})}function QRo(e){return SUD.get(e.toUpperCase())}function JRo(e){return wUD.has(e.toUpperCase())}var wUD=new Set(["ACL","API","ASCII","CPU","CSS","DNS","EOF","GUID","HTML","HTTP","HTTPS","ID","IP","JSON","LHS","QPS","RAM","RHS","RPC","SAML","SCIM","SLA","SMTP","SQL","SSH","SSO","TCP","TLS","TTL","UDP","UI","UID","UUID","URI","URL","UTF8","VM","XML","XMPP","XSRF","XSS"]),SUD=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);var k2=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;authOverrides;environmentOverrides;globalHeaderOverrides;constructor(t){this.args=t,this.spec=t.spec,this.settings=t.settings,this.errorCollector=t.errorCollector,this.logger=t.logger,this.generationLanguage=t.generationLanguage,this.smartCasing=t.smartCasing,this.namespace=t.namespace,this.casingsGenerator=BDe({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs,this.authOverrides=t.authOverrides,this.environmentOverrides=t.environmentOverrides,this.globalHeaderOverrides=t.globalHeaderOverrides}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=t.filter((n,a)=>!(/^\d+$/.test(n)||e.BREADCRUMBS_TO_IGNORE.includes(n)||a===0&&n==="components"||a===1&&n==="schemas"||t[0]==="paths"&&(a===0||a===1&&["get","post","put","delete","patch"].includes(n)||a===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&n==="parameters"))),i=$y(r.join("_"));return i.charAt(0).toUpperCase()+i.slice(1)}createPackage(t={}){return{fernFilepath:this.createFernFilepath(t),service:void 0,types:[],errors:[],subpackages:[],docs:void 0,webhooks:void 0,websocket:void 0,hasEndpointsInTree:!1,navigationConfig:void 0}}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],i=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:i?[...r,i]:r,packagePath:r,file:i}}async resolveReference(t){let r=this.spec,i,n=!1,a=null,u;if(this.isExternalReference(t.$ref)){n=!0;let f=t.$ref.split("#"),s=f[0];if(i=f[1],!s)return{resolved:!1};u=s;let o=await fetch(s);if(!o.ok)return{resolved:!1};try{let c=await o.text();try{a=JSON.parse(c),r=a}catch{a=Gd.load(c),r=a}if(r==null)return{resolved:!1}}catch{return{resolved:!1}}if(!i)return{resolved:!0,value:r}}let l=(i??t.$ref).replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(f=>f.replace(/~1/g,"/"));for(let f of l){if(typeof r!="object"||r==null)return{resolved:!1};r=r[f]}if(r==null)return{resolved:!1};if(n&&typeof r=="object"&&r!==null){let f=new Set;f.add(t.$ref),r=await this.resolveNestedExternalReferences(r,a,f,u)}return{resolved:!0,value:r}}async resolveNestedExternalReferences(t,r,i,n){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let u=[];for(let l of t)u.push(await this.resolveNestedExternalReferences(l,r,i,n));return u}if(this.isReferenceObject(t)){let u=t.$ref;if(this.isExternalReference(u)){if(i.has(u))return t;i.add(u);let l=await this.resolveReference({$ref:u});if(i.delete(u),l.resolved)return l.value}else{let l=`${n}${u}`;if(i.has(l))return t;i.add(l);let f=r,s=u.substring(2).split("/").map(o=>o.replace(/~1/g,"/").replace(/~0/g,"~"));for(let o of s){if(typeof f!="object"||f===null)return t;f=f[o]}if(f!=null){let o=await this.resolveNestedExternalReferences(f,r,i,n);return i.delete(u),o}i.delete(u)}return t}let a={};for(let[u,l]of Object.entries(t))typeof l=="object"&&l!==null?a[u]=await this.resolveNestedExternalReferences(l,r,i,n):a[u]=l;return a}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let i=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?i.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),i}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:i}){if(t==null)return[];let n=[];if(t.example!=null){let a=this.generateUniqueName({prefix:i??`${r.join("_")}_example`,existingNames:[]});n.push([a,t.example])}return t.examples!=null&&n.push(...Object.entries(t.examples)),n}async resolveMaybeReference({schemaOrReference:t,breadcrumbs:r}){if(this.isReferenceObject(t)){let i=await this.resolveReference(t);if(!i.resolved){this.errorCollector.collect({message:`Failed to resolve reference: ${t.$ref}`,path:r});return}return i.value}return t}async resolveExample(t){if(!this.isReferenceObject(t))return t;let r=await this.resolveReference(t);return r.resolved?this.returnExampleValue(r.value):void 0}async resolveExampleWithValue(t){if(!this.isReferenceObject(t))return this.returnExampleValue(t);let r=await this.resolveReference(t);return r.resolved?this.returnExampleValue(r.value):void 0}returnExampleValue(t){return this.isExampleWithValue(t)?t.value:t}async getPropertyAccess(t){let r=t;for(;this.isReferenceObject(r);){let i=await this.resolveReference(r);if(!i.resolved)return;r=i.value}if(!(r.readOnly&&r.writeOnly)){if(r.readOnly)return vJt.ReadOnly;if(r.writeOnly)return vJt.WriteOnly}}async getAvailability({node:t,breadcrumbs:r}){for(;this.isReferenceObject(t);){let a=await this.resolveReference(t);if(!a.resolved)return;t=a.value}let n=await new hne.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(n!=null)return{status:n,message:void 0};if(t.deprecated===!0)return{status:g5.Deprecated,message:void 0}}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t){return Bf.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t??"defaultName"),typeId:t,default:void 0,inline:!1})}typeReferenceToDeclaredTypeName(t){if(t.type!=="named")return;let r=t.typeId;return{typeId:r,fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(r)}}removeSchemaFromInlinedTypes({id:t,inlinedTypes:r}){return Object.fromEntries(Object.entries(r).filter(([i])=>i!==t))}static maybeTrimPrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}generateUniqueName({prefix:t,existingNames:r}){if(!r.includes(t))return t;let i=0;for(;r.includes(`${t}_${i}`);)i++;return`${t}_${i}`}isReferenceObject(t){return typeof t=="object"&&t!==null&&"$ref"in t}isExternalReference(t){return t.startsWith("http://")||t.startsWith("https://")}isExampleWithValue(t){return typeof t=="object"&&t!=null&&"value"in t}isOptional(t){return t.type==="container"&&t.container.type==="optional"}isNullable(t){return t.type==="container"&&t.container.type==="nullable"}isList(t){return t.type==="container"&&t.container.type==="list"}isFile(t){return t.type==="primitive"&&t.primitive.v2?.type==="string"&&t.primitive.v2.validation?.format==="binary"}getAsString(t){if(typeof t=="string")return t}getAsInteger(t){if(typeof t=="number"&&Number.isInteger(t))return t}getAsNumber(t){if(typeof t=="number")return t}getAsBoolean(t){if(typeof t=="boolean")return t}getAsArray(t){if(Array.isArray(t))return t}getAsObject(t){if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}getGroup({groupParts:t,namespace:r}){let i=[];return r!=null&&i.push(r),i.push(...t??[]),i}};var hA={};jo(hA,{AbstractConverters:()=>IKs,ExampleConverter:()=>OZt,SchemaConverters:()=>xKs,ServersConverter:()=>mZt});var IKs={};jo(IKs,{AbstractMediaTypeObjectConverter:()=>YRo,AbstractParameterConverter:()=>XRo});var OZt=class e extends w0{MAX_DEPTH=12;EXAMPLE_STRING="foo";EXAMPLE_NUMBER=42;EXAMPLE_BOOLEAN=!0;EXAMPLE_INTEGER=42;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;constructor({breadcrumbs:t,context:r,schema:i,example:n,depth:a=0,exampleGenerationStrategy:u,generateOptionalProperties:l=!1}){super({breadcrumbs:t,context:r}),this.example=n,this.schema=i,this.depth=a,this.exampleGenerationStrategy=u,this.generateOptionalProperties=l}async convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};let t=await this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs});return t==null?{isValid:!1,coerced:!1,validExample:null,errors:[{message:"Schema is not resolvable",path:this.breadcrumbs}]}:typeof t!="object"?{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Schema should be an object: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]}:"nullable"in t&&t.nullable===!0&&this.example===null?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:Array.isArray(t.type)?this.convertSchemaTypeArray({resolvedSchema:t}):t.type=="null"?this.convertNull():t.type=="boolean"?await this.convertBoolean():t.enum!=null?this.convertEnum(t):t.type=="number"?await this.convertNumber():t.type=="string"?await this.convertString():t.type=="integer"?await this.convertInteger():t.type=="array"?this.convertArray({resolvedSchema:t}):"oneOf"in t&&t.oneOf!=null?this.convertOneOf({resolvedSchema:t}):"anyOf"in t&&t.anyOf!=null?this.convertAnyOf({resolvedSchema:t}):t.type=="object"||t.properties!=null||t.allOf!=null?this.convertObject({resolvedSchema:t}):typeof t=="object"&&Object.keys(t).length===0?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Unsupported schema type: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]}}convertNull(){let t=this.example===null;return t?{isValid:t,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Example is not null: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}async convertBoolean(){let t=typeof this.example=="boolean";if(t)return{isValid:t,coerced:!1,validExample:this.example,errors:[]};let r=this.context.isReferenceObject(this.schema)?(await this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs}))?.default:this.schema.default;return typeof r=="boolean"?{isValid:!0,coerced:!1,validExample:r,errors:[]}:{isValid:!1,coerced:!1,validExample:await this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_BOOLEAN,errors:[{message:`Example is not a boolean: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}async convertEnum(t){let r=t.enum?.includes(this.example)??!1;if(r)return{isValid:r,coerced:!1,validExample:this.example,errors:[]};let i=this.context.isReferenceObject(this.schema)?(await this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs}))?.default:this.schema.default;return i!==void 0&&t.enum?.includes(i)?{isValid:!0,coerced:!1,validExample:i,errors:[]}:{isValid:r,coerced:!1,validExample:t.enum?.[0],errors:[{message:`Example is not one of the allowed enum values: ${JSON.stringify(t.enum,null,2)}`,path:this.breadcrumbs}]}}async convertNumber(){if(typeof this.example=="number")return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};let t=Number(this.example);if(!isNaN(t))return{isValid:!0,coerced:!0,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?(await this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs}))?.default:this.schema.default;return typeof r=="number"?{isValid:!0,coerced:!1,validExample:r,errors:[]}:{isValid:!1,coerced:!1,validExample:await this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}async convertString(){if(typeof this.example=="string")return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};if(typeof this.example!="object"&&!Array.isArray(this.example)&&this.example!=null)return{isValid:!0,coerced:!0,validExample:String(this.example),errors:[]};let t=this.context.isReferenceObject(this.schema)?(await this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs}))?.default:this.schema.default;return typeof t=="string"?{isValid:!0,coerced:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,validExample:await this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_STRING,errors:[{message:`Example cannot be converted to string: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}async convertInteger(){if(typeof this.example=="number"&&Number.isInteger(this.example))return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};if(typeof this.example=="string"){let r=Number(this.example);if(!isNaN(r)&&Number.isInteger(r))return{isValid:!0,coerced:!0,validExample:r,errors:[]}}let t=this.context.isReferenceObject(this.schema)?(await this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs}))?.default:this.schema.default;return typeof t=="number"&&Number.isInteger(t)?{isValid:!0,coerced:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,validExample:await this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_INTEGER,errors:[{message:`Example is not an integer: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}async convertArray({resolvedSchema:t}){if(t.type!="array")return{isValid:!1,coerced:!1,validExample:null,errors:[]};t.items==null&&(t.items={type:"string"});let r=Array.isArray(this.example)?this.example:[this.example],i=await Promise.all(r.map(async(a,u)=>await new e({breadcrumbs:[...this.breadcrumbs,`Item[${u}]`],context:this.context,schema:t.items,example:a,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy}).convert())),n=i.every(a=>a?.isValid??!1);return{isValid:n,coerced:!1,validExample:i.map(a=>a.validExample),errors:n?[]:i.flatMap(a=>a.errors)}}async convertObject({resolvedSchema:t}){if(t.type=="object"&&t.properties==null&&t.allOf==null)return{isValid:!0,coerced:!1,validExample:this.example??{},errors:[]};let r=typeof this.example!="object"||this.example==null?{}:this.example,i=await Promise.all(Object.entries(t.properties??{}).map(async([l,f])=>{if(typeof f!="object")return{key:l,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("readOnly"in f&&f.readOnly===!0&&"writeOnly"in f&&f.writeOnly===!0)return{key:l,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("readOnly"in f&&f.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:l,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("writeOnly"in f&&f.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:l,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};let s=!(l in r)||!("nullable"in f)&&r[l]==null||"nullable"in f&&f.nullable===!0&&r[l]===void 0,o=!t.required?.includes(l);if(s&&o){if(this.example===void 0&&this.generateOptionalProperties){let c=new e({breadcrumbs:[...this.breadcrumbs,l],context:this.context,schema:f,example:void 0,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy});return{key:l,result:await c.convert()}}return{key:l,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}}}else{let b=await new e({breadcrumbs:[...this.breadcrumbs,l],context:this.context,schema:f,example:r[l],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy}).convert();return{key:l,result:b}}})),n=await Promise.all((t.allOf??[]).map(async(l,f)=>await new e({breadcrumbs:[...this.breadcrumbs,`allOf[${f}]`],context:this.context,schema:{...t,...l,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy}).convert())),a=i.every(l=>l.result.isValid)&&n.every(l=>l.isValid),u=Object.fromEntries(i.map(({key:l,result:f})=>[l,f.validExample]).filter(([l,f])=>f!==void 0));for(let l of n)if(typeof l.validExample=="object"&&l.validExample!==null){let f=l.validExample;u={...u,...Object.fromEntries(Object.entries(f).filter(([s,o])=>o!==void 0))}}if(Object.keys(u).length===0){let l=n.find(f=>f.validExample!==void 0&&(typeof f.validExample!="object"||f.validExample===null));l&&(u=l.validExample)}return{isValid:a,coerced:!1,validExample:u,errors:[...i.flatMap(({result:l})=>l.errors),...n.flatMap(l=>l.errors)]}}async convertSchemaTypeArray({resolvedSchema:t}){if(!Array.isArray(t.type))return{isValid:!1,coerced:!1,validExample:null,errors:[]};if(t.type.length===1)return await new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:{...t,type:t.type[0]},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy}).convert();let r=await Promise.all(t.type.map(async(u,l)=>await new e({breadcrumbs:[...this.breadcrumbs,`type[${l}]`],context:this.context,schema:{...t,type:u},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy}).convert())),i=r.some(u=>u?.isValid??!1),a=r.find(u=>u.isValid)?.validExample??r[0]?.validExample??null;return{isValid:i,coerced:!1,validExample:a,errors:i?[]:r.flatMap(u=>u?.errors??[])}}async convertOneOf({resolvedSchema:t}){if(!("oneOf"in t)||t.oneOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=await Promise.all(t.oneOf.map(async(u,l)=>await new e({breadcrumbs:[...this.breadcrumbs,`oneOf[${l}]`],context:this.context,schema:{...t,...u,oneOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy}).convert())),i=r.filter(u=>u.isValid),n=i.length>0,a;return n?a=i.find(l=>!l.coerced)?.validExample??i[0]?.validExample:a=r[0]?.validExample,{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(u=>u.errors)}}async convertAnyOf({resolvedSchema:t}){if(!("anyOf"in t)||t.anyOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=await Promise.all(t.anyOf.map(async(u,l)=>await new e({breadcrumbs:[...this.breadcrumbs,`anyOf[${l}]`],context:this.context,schema:u,example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy}).convert())),i=r.filter(u=>u.isValid),n=i.length>0,a;return n?a=i.find(l=>!l.coerced)?.validExample??i[0]?.validExample:a=r[0]?.validExample,{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(u=>u.errors)}}async maybeResolveSchemaExample(t){let r=await this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs});if(r!=null){if("example"in r)return r.example;if("examples"in r)return Object.values(r.examples??{})[0]}}};var xKs={};jo(xKs,{ArraySchemaConverter:()=>VEn,EnumSchemaConverter:()=>NEn,ObjectSchemaConverter:()=>FEn,OneOfSchemaConverter:()=>LEn,PrimitiveSchemaConverter:()=>UEn,SchemaConverter:()=>p_i,SchemaOrReferenceConverter:()=>zX});function vGp(e){return x2({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return Bf.primitive({v1:"BASE_64",v2:wp.base64({})});case"BOOLEAN":return Bf.primitive({v1:"BOOLEAN",v2:wp.boolean({default:void 0})});case"DATE":return Bf.primitive({v1:"DATE",v2:wp.date({})});case"DATE_TIME":return Bf.primitive({v1:"DATE_TIME",v2:wp.dateTime({})});case"FLOAT":return Bf.primitive({v1:"FLOAT",v2:wp.float({})});case"DOUBLE":return Bf.primitive({v1:"DOUBLE",v2:wp.double({default:void 0,validation:void 0})});case"UINT":return Bf.primitive({v1:"UINT",v2:wp.uint({})});case"UINT_64":return Bf.primitive({v1:"UINT_64",v2:wp.uint64({})});case"INTEGER":return Bf.primitive({v1:"INTEGER",v2:wp.integer({default:void 0,validation:void 0})});case"LONG":return Bf.primitive({v1:"LONG",v2:wp.long({default:void 0})});case"STRING":return Bf.primitive({v1:"STRING",v2:wp.string({default:void 0,validation:void 0})});case"UUID":return Bf.primitive({v1:"UUID",v2:wp.uuid({})});case"BIG_INTEGER":return Bf.primitive({v1:"BIG_INTEGER",v2:wp.bigInteger({default:void 0})});default:return}},unknown:()=>Bf.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return Bf.container(Tv.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return Bf.container(Tv.list(t))},optional:t=>{if(t!=null)return Bf.container(Tv.optional(t))},nullable:t=>{if(t!=null)return Bf.container(Tv.nullable(t))},set:t=>{if(t!=null)return Bf.container(Tv.set(t))},literal:t=>Bf.container(Tv.literal(t._visit({string:r=>m5.string(r),boolean:r=>m5.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var NEn=class extends w0{schema;maybeFernEnum;constructor({context:t,breadcrumbs:r,schema:i,maybeFernEnum:n}){super({context:t,breadcrumbs:r}),this.schema=i,this.maybeFernEnum=n}convert(){if(!this.schema.enum)return;let r=this.schema.enum.filter(n=>typeof n=="string"||typeof n=="number").map(n=>{let a=n.toString(),u=this.maybeFernEnum?.[a],l=u?.name??a;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:l,wireValue:a}),docs:u?.description,availability:void 0,casing:u?.casing}});if(r.length===0){this.context.errorCollector.collect({message:`Received enum schema with no valid values: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}let i=this.context.getAsString(this.schema.default);return{type:KO.enum({default:i!=null?r.find(n=>n.name.wireValue===i):void 0,values:r})}}};var DUD=Bf.primitive({v1:"STRING",v2:wp.string({default:void 0,validation:void 0})}),KRo=class extends w0{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}async convert(){let r=await new zX({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schema}).convert();if(r!=null){let i=Bf.container(Tv.map({keyType:DUD,valueType:r.type}));return{type:KO.alias({aliasOf:i,resolvedType:i}),inlinedTypes:r.inlinedTypes}}}};async function Zva({properties:e,required:t,breadcrumbs:r,context:i,errorCollector:n}){let a=[],u={};for(let[l,f]of Object.entries(e??{})){let s=[...r,"properties",l];if(typeof f!="object"){n.collect({message:`Schema property ${l} should be an object`,path:s});continue}let o=i.convertBreadcrumbsToName(s),c="nullable"in f?f.nullable:!1,g=await new zX({context:i,breadcrumbs:s,schemaOrReference:f,schemaIdOverride:o,wrapAsOptional:!t.includes(l),wrapAsNullable:c}).convert();g!=null&&(a.push({name:i.casingsGenerator.generateNameAndWireValue({name:l,wireValue:l}),valueType:g.type,docs:f.description,availability:g.availability,propertyAccess:await i.getPropertyAccess(f),v2Examples:g.schema?.v2Examples??{userSpecifiedExamples:{},autogeneratedExamples:{}}}),u={...u,...g.inlinedTypes})}return{convertedProperties:a,inlinedTypesFromProperties:u}}var FEn=class extends w0{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}async convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:KO.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),inlinedTypes:{}};let{convertedProperties:r,inlinedTypesFromProperties:i}=await Zva({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector}),n=[],a=i;for(let[u,l]of(this.schema.allOf??[]).entries()){if(this.context.isReferenceObject(l)){let o=await this.context.convertReferenceToTypeReference(l);o.ok&&n.push(o.reference);continue}let{convertedProperties:f,inlinedTypesFromProperties:s}=await Zva({properties:l.properties??{},required:[...this.schema.required??[],...l.required??[]],breadcrumbs:[...this.breadcrumbs,"allOf",u.toString()],context:this.context,errorCollector:this.context.errorCollector});r.push(...f),a={...a,...s}}return{type:KO.object({properties:r,extends:n.map(u=>this.context.typeReferenceToDeclaredTypeName(u)).filter(g0),extendedProperties:[],extraProperties:t}),inlinedTypes:a}}};var LEn=class extends w0{schema;id;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlinedTypes:a}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n}async convert(){return this.shouldConvertAsNullableSchemaOrReference()?await this.convertAsNullableSchemaOrReference():this.schema.discriminator!=null&&!await this.unionVariantsContainLiteral({discriminantProperty:this.schema.discriminator.propertyName})?await this.convertAsDiscriminatedUnion():this.convertAsUndiscriminatedUnion()}async unionVariantsContainLiteral({discriminantProperty:t}){for(let[r,i]of Object.entries(this.schema.discriminator?.mapping??{})){let n=await this.context.resolveReference({$ref:i});if(n.resolved&&!Object.keys(n.value.properties??{}).includes(t))return!1}return!0}async convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=[],r={};for(let[a,u]of Object.entries(this.schema.discriminator.mapping??{})){let l=new zX({context:this.context,schemaOrReference:{$ref:u},breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",a]}),f=this.context.getTypeIdFromSchemaReference({$ref:u}),s=await l.convert();if(s?.type!=null&&f!=null){let o=this.context.casingsGenerator.generateNameAndWireValue({name:a,wireValue:a});t.push({docs:void 0,discriminantValue:o,availability:s.availability,displayName:void 0,shape:sG.samePropertiesAsObject({typeId:f,name:this.context.casingsGenerator.generateName(f),fernFilepath:{allParts:[],packagePath:[],file:void 0}})}),r={...r,...s.inlinedTypes}}}let{convertedProperties:i,inlinedTypesFromProperties:n}=await Zva({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});return{type:KO.union({baseProperties:i,discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:[],types:t}),inlinedTypes:{...r,...n}}}async convertAsUndiscriminatedUnion(){if(!this.schema.oneOf&&!this.schema.anyOf||this.schema.anyOf?.length===0&&this.schema.oneOf?.length===0)return;let t=[],r={};for(let[i,n]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(n)){let f=await this.context.convertReferenceToTypeReference(n);f.ok&&t.push({type:f.reference,docs:n.description});continue}let a=this.context.convertBreadcrumbsToName([`${this.id}_${i}`]),l=await new p_i({context:this.context,id:a,breadcrumbs:[...this.breadcrumbs,`oneOf[${i}]`],schema:n}).convert();l!=null&&(t.push({type:this.context.createNamedTypeReference(a),docs:n.description}),r={...r,...l.inlinedTypes,[a]:l.typeDeclaration})}return{type:KO.undiscriminatedUnion({members:t}),inlinedTypes:r}}shouldConvertAsNullableSchemaOrReference(){return this.schema.oneOf!=null?this.schema.oneOf.some(t=>"type"in t&&t.type==="null"):this.schema.anyOf!=null?this.schema.anyOf.some(t=>"type"in t&&t.type==="null"):!1}removeNullFromOneOfOrAnyOf(){let t=this.schema.oneOf??this.schema.anyOf,r=this.schema.oneOf!=null?"oneOf":"anyOf";if(t==null)return;let i=t.filter(n=>!("type"in n&&n.type==="null"));if(i.length===0){this.context.errorCollector.collect({message:`Received ${r} schema with no valid non-null types: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}return i.length===1?{...this.schema,[r]:void 0,...i[0]}:{...this.schema,[r]:i}}async convertAsNullableSchemaOrReference(){let t=this.removeNullFromOneOfOrAnyOf();if(t==null)return;let i=await new zX({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(i==null)return;let n=this.wrapInNullable(i.type);return{type:KO.alias({aliasOf:n,resolvedType:n}),inlinedTypes:i.inlinedTypes}}wrapInNullable(t){return Bf.container(Tv.nullable(t))}};var UEn=class extends w0{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){switch(this.schema.type){case"string":{let t=this.context.getAsString(this.schema.const);return t!=null?Bf.container(Tv.literal(m5.string(t))):Bf.primitive({v1:"STRING",v2:wp.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":case"integer":switch(this.schema.format){case"double":return Bf.primitive({v1:"DOUBLE",v2:wp.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Bf.primitive({v1:"FLOAT",v2:wp.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Bf.primitive({v1:"INTEGER",v2:wp.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Bf.primitive({v1:"LONG",v2:wp.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return Bf.primitive({v1:"UINT",v2:wp.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Bf.primitive({v1:"UINT_64",v2:wp.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Bf.primitive({v1:"INTEGER",v2:wp.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"boolean":{let t=this.context.getAsBoolean(this.schema.const);return t!=null?Bf.container(Tv.literal(m5.boolean(t))):Bf.primitive({v1:"BOOLEAN",v2:wp.boolean({default:this.schema.default})})}default:return}}getNumberValidation(t){return{max:t.maximum,min:t.minimum,exclusiveMax:typeof t.exclusiveMaximum=="boolean"?t.exclusiveMaximum:void 0,exclusiveMin:typeof t.exclusiveMinimum=="boolean"?t.exclusiveMinimum:void 0,multipleOf:t.multipleOf}}getStringValidation(t){return{minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,format:t.format}}};var p_i=class e extends w0{schema;id;inlined;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlined:a=!1}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n,this.inlined=a}async convert(){let t=await this.tryConvertFernTypeDeclaration();return t!=null?{typeDeclaration:t,inlinedTypes:{}}:this.convertSchema()}async convertSchema(){if(this.schema.enum?.length){let n=new hne.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),u=new NEn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,maybeFernEnum:n}).convert();if(u!=null)return{typeDeclaration:await this.createTypeDeclaration({shape:u.type}),inlinedTypes:{}}}if(this.schema.allOf?.length===1&&this.schemaOnlyHasAllowedKeys(["allOf"])&&this.schema.allOf[0]!=null){let i;if(this.context.isReferenceObject(this.schema.allOf[0])){let n=await this.context.resolveReference(this.schema.allOf[0]);n.resolved&&(i=n.value)}else i=this.schema.allOf[0];if(i!=null){let a=await new e({context:this.context,breadcrumbs:[...this.breadcrumbs,"allOf","0"],schema:i,id:this.id,inlined:!0}).convert();if(a?.typeDeclaration?.shape.type!=="object")return a}}let r=new UEn({context:this.context,schema:this.schema}).convert();if(r!=null)return{typeDeclaration:await this.createTypeDeclaration({shape:KO.alias({aliasOf:r,resolvedType:r})}),inlinedTypes:{}};if(this.schema.type==="array"){let n=await new VEn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(n!=null)return{typeDeclaration:await this.createTypeDeclaration({shape:KO.alias({aliasOf:n.typeReference,resolvedType:n.typeReference})}),inlinedTypes:n.inlinedTypes}}if(Array.isArray(this.schema.type)&&this.schema.type.length>0){if(this.schema.type.length===1)this.schema.type=this.schema.type[0];else{let i=this.schema.type;this.schema.type=void 0,this.schema.oneOf=i.map(n=>({type:n}))}return this.convertSchema()}if(this.schema.oneOf!=null||this.schema.anyOf!=null){let n=await new LEn({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,inlinedTypes:{}}).convert();if(n!=null)return{typeDeclaration:await this.createTypeDeclaration({shape:n.type}),inlinedTypes:n.inlinedTypes}}if(typeof this.schema.additionalProperties=="object"&&this.schema.additionalProperties!=null&&!this.schema.properties&&!this.schema.allOf){let n=await new KRo({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema.additionalProperties}).convert();if(n!=null)return{typeDeclaration:await this.createTypeDeclaration({shape:n.type}),inlinedTypes:n.inlinedTypes}}if(this.schema.type==="object"||this.schema.properties!=null||this.schema.allOf!=null){let n=await new FEn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(n!=null)return{typeDeclaration:await this.createTypeDeclaration({shape:n.type}),inlinedTypes:n.inlinedTypes}}this.context.errorCollector.collect({message:`Failed to convert schema object: ${JSON.stringify(this.schema,null,2)}`,path:this.breadcrumbs})}async tryConvertFernTypeDeclaration(){let r=new hne.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r!=null){let i=await this.createTypeDeclarationFromFernType({fernType:r});if(i!=null)return i}}async createTypeDeclaration({shape:t}){let r=await this.convertSchemaExamples();return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:await this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:new Set,source:void 0,inline:this.inlined,v2Examples:r}}convertDeclaredTypeName(){return{typeId:this.id,fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(this.id)}}schemaOnlyHasAllowedKeys(t){let i=[...["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],...t];return Object.keys(this.schema).every(a=>i.includes(a))}async createTypeDeclarationFromFernType({fernType:t}){let r=vGp(t);if(r!=null)return{name:this.convertDeclaredTypeName(),shape:KO.alias({aliasOf:r,resolvedType:r}),autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:await this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:new Set,source:void 0,inline:this.inlined,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}async convertSchemaExamples(){let t={userSpecifiedExamples:{},autogeneratedExamples:{}},r=this.context.getExamplesFromSchema({schema:this.schema,breadcrumbs:this.breadcrumbs});if(r.length===0){let i=await this.generateOrValidateExample({example:void 0,ignoreErrors:!0});return t.autogeneratedExamples={[`${this.id}_example_autogenerated`]:i},t}return t.userSpecifiedExamples=await this.convertUserSpecifiedExamples(r),t}async convertUserSpecifiedExamples(t){let r={};for(let[i,n]of t.entries()){let a=await this.context.resolveExample(n),u=await this.generateOrValidateExample({example:a});r[`${this.id}_example_${i}`]=u}return r}async generateOrValidateExample({example:t,ignoreErrors:r}){let i=new OZt({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n,errors:a}=await i.convert();return r||a.forEach(u=>{this.context.errorCollector.collect({message:u.message,path:u.path})}),n}};var zX=class extends w0{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:i,schemaIdOverride:n,wrapAsOptional:a=!1,wrapAsNullable:u=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=i,this.schemaIdOverride=n,this.wrapAsOptional=a,this.wrapAsNullable=u}async convert(){return this.context.isReferenceObject(this.schemaOrReference)?this.convertReferenceObject({reference:this.schemaOrReference}):this.convertSchemaObject({schema:this.schemaOrReference})}async convertReferenceObject({reference:t}){let r=await this.context.convertReferenceToTypeReference(t);if(!r.ok){this.context.errorCollector.collect({message:`Failed to convert reference to type reference: ${t.$ref}`,path:this.breadcrumbs});return}return{type:this.wrapTypeReference(r.reference),inlinedTypes:{}}}async convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),i=new p_i({context:this.context,breadcrumbs:this.breadcrumbs,schema:t,id:r}),n=await this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs}),a=await i.convert();if(a!=null){let u=a.typeDeclaration.shape;return u.type==="alias"?{type:this.wrapTypeReference(u.aliasOf),schema:a.typeDeclaration,inlinedTypes:a.inlinedTypes,availability:n}:{type:this.wrapTypeReference(this.context.createNamedTypeReference(r)),schema:a.typeDeclaration,inlinedTypes:{...a.inlinedTypes,[r]:a.typeDeclaration},availability:n}}}wrapTypeReference(t){return this.wrapAsOptional&&this.wrapAsNullable?this.wrapInOptional(this.wrapInNullable(t)):this.wrapAsOptional?this.wrapInOptional(t):this.wrapAsNullable?this.wrapInNullable(t):t}wrapInOptional(t){return Bf.container(Tv.optional(t))}wrapInNullable(t){return Bf.container(Tv.nullable(t))}};var VEn=class e extends w0{static LIST_UNKNOWN=Bf.container(Tv.list(Bf.unknown()));schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}async convert(){if(this.schema.items==null)return{typeReference:e.LIST_UNKNOWN,inlinedTypes:{}};let r=await new zX({context:this.context,breadcrumbs:[...this.breadcrumbs,"items"],schemaOrReference:this.schema.items}).convert();return r!=null?{typeReference:Bf.container(Tv.list(r.type)),inlinedTypes:r.inlinedTypes}:{typeReference:e.LIST_UNKNOWN,inlinedTypes:{}}}};var YRo=class extends w0{group;method;constructor({context:t,breadcrumbs:r,group:i,method:n}){super({context:t,breadcrumbs:r}),this.group=i,this.method=n}async parseMediaTypeObject({mediaTypeObject:t,schemaId:r}){if(t==null||t.schema==null)return;let n=await new zX({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaOrReference:t.schema,schemaIdOverride:r}).convert();if(n==null)return;let a=t.examples!=null?Object.fromEntries(await Promise.all(Object.entries(t.examples).map(async([u,l])=>[u,this.context.isReferenceObject(l)?await this.context.resolveReference(l):l]))):void 0;return{...n,examples:a}}async convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:r,exampleGenerationStrategy:i}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},a=t?.schema,u=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`});for(let[l,f]of u){let s=await this.context.resolveExampleWithValue(f);s!=null&&(a!=null?n.userSpecifiedExamples[l]=await this.generateOrValidateExample({schema:a,example:s,exampleGenerationStrategy:i}):n.userSpecifiedExamples[l]=s)}if(Object.keys(n.userSpecifiedExamples).length===0&&a!=null){let l=`${[...this.group,this.method].join("_")}_example`;n.autogeneratedExamples[l]=await this.generateOrValidateExample({schema:a,example:void 0,ignoreErrors:!0,generateOptionalProperties:r,exampleGenerationStrategy:i})}return n}async generateOrValidateExample({schema:t,example:r,ignoreErrors:i,generateOptionalProperties:n,exampleGenerationStrategy:a}){let u=await this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs});if(u==null)return;let l=this.context.getExamplesFromSchema({schema:u,breadcrumbs:this.breadcrumbs}),f=new OZt({breadcrumbs:this.breadcrumbs,context:this.context,schema:u,example:r??l[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:a}),{validExample:s,errors:o}=await f.convert();return i||o.forEach(c=>{this.context.errorCollector.collect({message:c.message,path:c.path})}),s}};var XRo=class e extends w0{static STRING=Bf.primitive({v1:"STRING",v2:wp.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Bf.container(Tv.optional(e.STRING));parameter;constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r}),this.parameter=i}async convertToOutput({schema:t,typeReference:r,inlinedTypes:i}){let n=await this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??e.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,v2Examples:await this.convertParameterExamples({schema:t}),availability:n},inlinedTypes:i};case"header":return{type:"header",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??e.OPTIONAL_STRING,env:void 0,v2Examples:await this.convertParameterExamples({schema:t}),availability:n},inlinedTypes:i};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:this.parameter.description,valueType:r??e.STRING,location:"ENDPOINT",variable:void 0,v2Examples:await this.convertParameterExamples({schema:t})},inlinedTypes:i};default:return}}async convertParameterExamples({schema:t}){let r={userSpecifiedExamples:{},autogeneratedExamples:{}},i=this.parameter.example,n=this.parameter.examples;for(let[a,u]of Object.entries(n??{})){let l=await this.context.resolveExampleWithValue(u);l!=null&&(r.userSpecifiedExamples[a]=await this.generateOrValidateExample({schema:t,example:l}))}if(i!=null){let a=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(r.userSpecifiedExamples)});r.userSpecifiedExamples[a]=await this.generateOrValidateExample({schema:t,example:i})}if(Object.keys(r.userSpecifiedExamples).length===0){let a=`${this.parameter.name}_example`;r.autogeneratedExamples[a]=await this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0})}return r}async generateOrValidateExample({schema:t,ignoreErrors:r,example:i}){let n=new OZt({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:i}),{validExample:a,errors:u}=await n.convert();return r||u.forEach(l=>{this.context.errorCollector.collect({message:l.message,path:l.path})}),a}};var ZRo=class extends dS{server;key="x-fern-server-name";constructor({breadcrumbs:t,server:r,context:i}){super({breadcrumbs:t,context:i}),this.server=r}convert(){let t=this.getExtensionValue(this.server);if(!(t==null||typeof t!="string"))return t}};var zKs="Base",mZt=class e extends w0{servers;endpointLevelServers;constructor({breadcrumbs:t,context:r,servers:i,endpointLevelServers:n}){super({breadcrumbs:t,context:r}),this.servers=i,this.endpointLevelServers=n}convert(){if(this.servers==null||this.servers.length===0||this.servers[0]==null)return;if(this.endpointLevelServers!=null&&this.endpointLevelServers.length>0){let r={id:zKs,name:this.context.casingsGenerator.generateName(zKs)},i=this.endpointLevelServers.map(u=>{let l=e.getServerName({server:u,context:this.context});return{id:l,name:this.context.casingsGenerator.generateName(l)}}).filter((u,l,f)=>f.findIndex(s=>s.id===u.id)===l),n=[r,...i],a=this.servers.map(u=>{let l=e.getServerName({server:u,context:this.context}),f=this.endpointLevelServers?.map(s=>[e.getServerName({server:s,context:this.context}),this.getServerUrl(s)]);return{id:l,name:this.context.casingsGenerator.generateName(l),urls:{[zKs]:this.getServerUrl(u),...Object.fromEntries(f??[])},docs:u.description}});return{value:{defaultEnvironment:a[0]?.id,environments:yI.multipleBaseUrls({baseUrls:n,environments:a})},defaultUrl:e.getServerName({server:this.servers[0],context:this.context})}}let t=this.withExplodedServers(this.servers).map(r=>{let i=e.getServerName({server:r,context:this.context});return{id:i,name:this.context.casingsGenerator.generateName(i),url:this.getServerUrl(r),docs:r.description}}).filter(g0);return{value:{defaultEnvironment:t[0]?.id,environments:yI.singleBaseUrl({environments:t})}}}static getServerName({server:t,context:r}){return new ZRo({breadcrumbs:[],server:t,context:r}).convert()??t.description??t.url}getServerUrl(t){if(t.variables==null)return t.url;let r=t.url;for(let[i,n]of Object.entries(t.variables))n.default!=null&&(r=r.replace(`{${i}}`,n.default));return r}withExplodedServers(t){return t.flatMap(r=>{if(r.variables==null)return[r];let i=Object.entries(r.variables).filter(([l,f])=>f.enum!=null&&f.enum.length>0);if(i.length===0)return[r];let n=i[0];if(n==null)return[r];let[a,u]=n;return u.enum==null?[r]:u.enum.map(l=>{let f=r.url.replace(`{${a}}`,l),s={};for(let[c,b]of Object.entries(r.variables??{}))c!==a&&(s[c]=b);let o={...r,url:f,variables:Object.keys(s).length>0?s:void 0,"x-fern-server-name":r.description?`${r.description}_${l}`:`${l}`,description:r.description};return this.withExplodedServers([o])[0]})}).filter(g0)}};var WEn=class{errors=[];logger;constructor({logger:t}){this.logger=t}collect(t){this.errors.push(t)}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}logErrors(){for(let t of this.errors)this.logger.log(G0.Info,kie({title:t.message,breadcrumbs:t.path,subtitle:t.path!=null?eh.dim(t.path.join(" -> ")):void 0}))}};var EUD=pu.object({type:pu.string(),channelId:pu.string().optional(),messageId:pu.string(),value:pu.any()}),MUD=pu.object({summary:pu.string().optional(),description:pu.string().optional(),queryParameters:pu.record(pu.string()).optional(),headers:pu.record(pu.string()).optional(),messages:pu.array(EUD)}),bGp=pu.array(MUD);var kRo=class extends dS{channel;key="x-fern-examples";constructor({breadcrumbs:t,channel:r,context:i}){super({breadcrumbs:t??[],context:i}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(t==null)return;let r=bGp.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-examples extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data.map(i=>({summary:i.summary,description:i.description,queryParameters:i.queryParameters,headers:i.headers,messages:i.messages.map(n=>({type:n.type,channelId:n.channelId,messageId:n.messageId,value:n.value}))}))}};var HEn=class extends w0{channel;channelPath;group;inlinedTypes={};constructor({context:t,breadcrumbs:r,channel:i,channelPath:n,group:a}){super({context:t,breadcrumbs:r}),this.channel=i,this.channelPath=n,this.group=a}convertExamples({pathHead:t,baseUrl:r}){let n=new kRo({context:this.context,breadcrumbs:this.breadcrumbs,channel:this.channel}).convert();return n==null?{}:Object.fromEntries(n.map((a,u)=>[u.toString(),{channel:{method:"GET",path:t},baseUrl:void 0,environment:r,auth:void 0,pathParameters:{userSpecifiedExamples:{},autogeneratedExamples:{}},queryParameters:{userSpecifiedExamples:a.queryParameters??{},autogeneratedExamples:{}},headers:{userSpecifiedExamples:a.headers??{},autogeneratedExamples:{}},messages:a.messages.map(l=>({type:l.messageId,body:l.value}))}]))}transformToValidPath(t){return t.startsWith("/")?t:"/"+t}};var __i=class extends hA.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r,parameter:i})}async convert(){let t,r={},n=new hne.FernOptionalExtension({breadcrumbs:this.breadcrumbs,parameter:this.parameter,context:this.context}).convert()??this.parameter.required??!1,a=this.parameter.schema??{...this.parameter,type:"string",enum:this.parameter.enum,default:this.parameter.default,example:this.parameter.example,examples:Object.values(this.parameter.examples??{}),required:void 0},l=await new hA.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaIdOverride:this.parameter.name,schemaOrReference:a,wrapAsOptional:n}).convert();return l!=null&&(t=l.type,r=l.inlinedTypes??{}),this.convertToOutput({schema:a,typeReference:t,inlinedTypes:r})}};var eNo=class extends dS{channel;key="x-fern-address";constructor({breadcrumbs:t,channel:r,context:i}){super({breadcrumbs:t,context:i}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(!(t==null||typeof t!="string"))return t}};var $En=class extends dS{channel;key="x-fern-display-name";constructor({breadcrumbs:t,channel:r,context:i}){super({breadcrumbs:t,context:i}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(!(t==null||typeof t!="string"))return t}};var tNo=class extends HEn{inlinedTypes={};constructor({context:t,breadcrumbs:r,channel:i,channelPath:n,group:a}){super({context:t,breadcrumbs:r,channel:i,channelPath:n,group:a})}async convert(){let t=[],r=[],i=[],a=new $En({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert()??this.channelPath;this.channel.parameters&&await this.convertQueryParameters({context:this.context,queryParameters:r}),this.channel.bindings?.ws!=null&&(await this.convertHeaders({context:this.context,headers:i}),await this.convertBindingQueryParameters({context:this.context,queryParameters:r}));let u;this.channel.subscribe!=null&&(u=await this.convertMessage({context:this.context,operation:this.channel.subscribe,origin:"server"}));let l;this.channel.publish!=null&&(l=await this.convertMessage({context:this.context,operation:this.channel.publish,origin:"client"}));let f=[];u!=null&&f.push(u),l!=null&&f.push(l);let o=new eNo({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert(),c=this.channel.servers?.[0]??Object.keys(this.context.spec.servers??{})[0],b=o??this.transformToValidPath(this.channelPath),g=$y(this.channelPath);return{channel:{name:this.context.casingsGenerator.generateName(g),displayName:a,baseUrl:c,path:{head:b,parts:[]},auth:!1,headers:i,queryParameters:r,pathParameters:t,messages:f,availability:await this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({pathHead:b,baseUrl:c})}},inlinedTypes:this.inlinedTypes}}async convertMessage({context:t,operation:r,origin:i}){let n,a=i==="server"?"subscribe":"publish",u=[...this.breadcrumbs,a],l=await t.resolveMaybeReference({schemaOrReference:r.message,breadcrumbs:u});l!=null&&(r.message=l);let f=TCi($y(`${this.channelPath}_${a}`)).replace(/ /g,"");if("oneOf"in r.message){let o=await new hA.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:u,schemaOrReference:r.message,schemaIdOverride:f}).convert();o!=null&&o.schema!=null&&(n=o.schema,this.inlinedTypes={...this.inlinedTypes,...o.inlinedTypes})}else if(t.isMessageWithPayload(r.message)){let s=await t.resolveMaybeReference({schemaOrReference:r.message.payload,breadcrumbs:u});if(s!=null){let c=await new hA.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:u,schemaOrReference:s,schemaIdOverride:f}).convert();c!=null&&c.schema!=null&&(n=c.schema,this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes})}}if(n!=null){let s=n,o=Bf.named({fernFilepath:t.createFernFilepath(),name:s.name.name,typeId:s.name.typeId,default:void 0,inline:!1}),c=P5.reference({bodyType:o,docs:r.description}),b=i==="server"?"subscribe":"publish";return{type:b,displayName:b,origin:i,body:c,availability:await t.getAvailability({node:r,breadcrumbs:this.breadcrumbs}),docs:r.description}}}async convertQueryParameters({context:t,queryParameters:r}){for(let[i,n]of Object.entries(this.channel.parameters??{})){let a=await t.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs});if(a==null)continue;let l=await new __i({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...a,name:i,in:"query",description:n.description,required:n.required??!1}}).convert();l!=null&&(this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes},l.type==="query"&&r.push(l.parameter))}}async convertHeaders({context:t,headers:r}){if(this.channel.bindings?.ws?.headers!=null){let i=this.channel.bindings.ws.headers.required??[];for(let[n,a]of Object.entries(this.channel.bindings.ws.headers.properties??{})){let u=await t.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,n]});if(u==null)continue;let f=await new __i({context:this.context,breadcrumbs:[...this.breadcrumbs,n],parameter:{name:n,in:"header",required:i.includes(n),schema:u,description:"description"in u?u.description:void 0}}).convert();f!=null&&f.type==="header"&&(this.inlinedTypes={...this.inlinedTypes,...f.inlinedTypes},r.push(f.parameter))}}}async convertBindingQueryParameters({context:t,queryParameters:r}){if(this.channel.bindings?.ws?.query!=null){let i=this.channel.bindings.ws.query.required??[];for(let[n,a]of Object.entries(this.channel.bindings.ws.query.properties??{})){let u=await t.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,n]});if(u==null)continue;let f=await new __i({context:this.context,breadcrumbs:[...this.breadcrumbs,n],parameter:{name:n,in:"query",required:i.includes(n),schema:u,description:"description"in u?u.description:void 0}}).convert();f!=null&&f.type==="query"&&(this.inlinedTypes={...this.inlinedTypes,...f.inlinedTypes},r.push(f.parameter))}}}};var GEn=class extends w0{servers;constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r}),this.servers=i}convert(){if(this.servers==null||Object.keys(this.servers).length===0)return;let t=[],r;for(let[i,n]of Object.entries(this.servers)){let a=this.buildSingleBaseUrlEnvironment(this.context,i,n);t.push(a),r==null&&(r=a.id)}return{defaultEnvironment:r,environments:yI.singleBaseUrl({environments:t})}}constructServerUrl(t,r){return r.includes("://")?r:`${t}://${r}`}};var rNo=class extends GEn{constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r,servers:i})}buildSingleBaseUrlEnvironment(t,r,i){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(i.protocol,i.url),docs:void 0}}};var RKs="$message.",gGp="#/channels/",OGp="#/servers/",iNo=class extends HEn{operations;inlinedTypes={};constructor({context:t,breadcrumbs:r,channel:i,channelPath:n,operations:a,group:u}){super({context:t,breadcrumbs:r,channel:i,channelPath:n,group:u}),this.operations=a}async convert(){let t=[],r=[],i=[],a=new $En({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert()??this.channelPath;this.channel.parameters&&await this.convertChannelParameters({pathParameters:t,queryParameters:r,headers:i});let u=Object.entries(this.operations).reduce((o,[c,b])=>{try{this.getChannelPathFromOperation(b)===this.channelPath&&(o[c]=b)}catch{}return o},{}),l=[];for(let[o,c]of Object.entries(u))for(let b of c.messages){let g=await this.context.convertReferenceToTypeReference(b);if(g.ok){let O=P5.reference({bodyType:g.reference,docs:c.description});l.push({type:o,displayName:o,origin:c.action==="send"?"client":"server",body:O,availability:await this.context.getAvailability({node:c,breadcrumbs:this.breadcrumbs}),docs:c.description})}}let f=this.resolveChannelServersFromReference(this.channel.servers??[])??Object.keys(this.context.spec.servers??{})[0],s=this.transformToValidPath(this.channel.address??this.channelPath);return{channel:{name:this.context.casingsGenerator.generateName(a),displayName:a,baseUrl:f,path:{head:s,parts:[]},auth:!1,headers:i,queryParameters:r,pathParameters:t,messages:l,availability:await this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({pathHead:s,baseUrl:f})}},inlinedTypes:this.inlinedTypes}}async convertChannelParameters({pathParameters:t,queryParameters:r,headers:i}){for(let n of Object.values(this.channel.parameters??{})){let a=await this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:[...this.breadcrumbs,"parameters"]});if(a==null)continue;let u=this.convertChannelParameterLocation(n.location);if(u==null)continue;let{type:l,parameterKey:f}=u,o=await new __i({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...a,name:f,in:l}}).convert();if(o!=null)switch(this.inlinedTypes={...this.inlinedTypes,...o.inlinedTypes},o.type){case"path":t.push(o.parameter);break;case"query":r.push(o.parameter);break;case"header":i.push(o.parameter);break}}}convertChannelParameterLocation(t){try{let[r,i]=t.split("#/");if(r==null||i==null){this.context.errorCollector.collect({message:`Invalid location format: ${t}; unable to parse message type and parameter key`,path:this.breadcrumbs});return}if(!r.startsWith(RKs)){this.context.errorCollector.collect({message:`Invalid location format: ${t}; expected ${RKs} prefix`,path:this.breadcrumbs});return}let n=r.substring(RKs.length);if(n!=="header"&&n!=="path"&&n!=="payload"){this.context.errorCollector.collect({message:`Invalid message type: ${n}. Must be one of: header, path, payload`,path:this.breadcrumbs});return}return n==="payload"?{type:"query",parameterKey:i}:{type:n,parameterKey:i}}catch{this.context.errorCollector.collect({message:`Invalid location format: ${t}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`,path:this.breadcrumbs});return}}resolveChannelServersFromReference(t){if(t==null||t.length===0||t[0]==null)return;let r=t[0];if(!r.$ref.startsWith(OGp)){this.context.errorCollector.collect({message:`Failed to resolve server name from server ref ${r.$ref}`,path:this.breadcrumbs});return}let i=r.$ref.substring(OGp.length);if(i==null){this.context.errorCollector.collect({message:`Failed to find server with name ${i}`,path:this.breadcrumbs});return}return i}getChannelPathFromOperation(t){if(!t.channel.$ref.startsWith(gGp))throw new Error(`Failed to resolve channel path from operation ${t.channel.$ref}`);return t.channel.$ref.substring(gGp.length)}};var nNo=class extends GEn{constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r,servers:i})}buildSingleBaseUrlEnvironment(t,r,i){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(i.protocol,i.host),docs:void 0}}};var kva=class extends w0{constructor({context:t,breadcrumbs:r}){super({context:t,breadcrumbs:r})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec,context:this.context}),this.context.spec=await this.resolveExternalRefs({spec:this.context.spec,context:this.context}),this.isAsyncAPIV3(this.context)?await this.convertChannelMessages():await this.convertComponentMessages(),await this.convertSchemas(),await this.convertServers(),await this.convertChannels();let t={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}};return t={...t,...bYr({ir:t,exampleGeneration:this.context.exampleGenerationArgs}),...SFi({ir:t,exampleGeneration:this.context.exampleGenerationArgs})},t}isAsyncAPIV3(t){return parseFloat(t.spec.asyncapi)>=3}async convertChannelMessages(){let t=this.context.spec;for(let[r,i]of Object.entries(t.channels??{}))for(let[n,a]of Object.entries(i.messages??{})){if(!this.context.isMessageWithPayload(a)&&!this.context.isReferenceObject(a))continue;let u=["channels",r,"messages",n],l=await this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:u});if(!this.context.isMessageWithPayload(l))continue;let f=await this.context.resolveMaybeReference({schemaOrReference:l.payload,breadcrumbs:u});if(f==null)continue;let s=`${r}_${n}`;await this.convertSchema({id:s,breadcrumbs:u,schema:f})}}async convertComponentMessages(){for(let[t,r]of Object.entries(this.context.spec.components?.messages??{})){if(r.payload==null)continue;let i=["components","messages",t],n=await this.context.resolveMaybeReference({schemaOrReference:r.payload,breadcrumbs:i});n!=null&&await this.convertSchema({id:t,breadcrumbs:i,schema:n})}}async convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{}))await this.convertSchema({id:t,breadcrumbs:["components","schemas",t],schema:r})}async convertSchema({id:t,breadcrumbs:r,schema:i}){let a=await new hA.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:r,schema:i}).convert();a!=null&&(this.ir.rootPackage.types.push(t),this.ir.types={...this.ir.types,...a.inlinedTypes,[t]:a.typeDeclaration})}async convertServers(){if(this.isAsyncAPIV3(this.context)){let t=this.context.spec.servers,i=new nNo({context:this.context,breadcrumbs:["servers"],servers:t}).convert();i!=null&&(this.ir.environments=i)}else{let t=this.context.spec.servers,i=new rNo({context:this.context,breadcrumbs:["servers"],servers:t}).convert();i!=null&&(this.ir.environments=i)}}async convertChannels(){for(let[t,r]of Object.entries(this.context.spec.channels??{})){let n=new hne.SdkGroupNameExtension({breadcrumbs:["channels",t],operation:r,context:this.context}).convert()?.groups,a;if(this.isAsyncAPIV3(this.context)){let l=this.context.spec.operations??{};a=await new iNo({context:this.context,breadcrumbs:["channels",t],channel:r,channelPath:t,operations:l,group:n}).convert()}else a=await new tNo({context:this.context,breadcrumbs:["channels",t],channel:r,channelPath:t,group:n}).convert();if(a!=null){let u=`channel_${$y(t)}`;this.ir.websocketChannels={...this.ir.websocketChannels,[n?n.join("."):u]:a.channel},this.ir.types={...this.ir.types,...a.inlinedTypes}}}this.addWebsocketsToIr({websocketChannels:this.ir.websocketChannels})}addWebsocketsToIr({websocketChannels:t}){if(t!=null)for(let[r,i]of Object.entries(t))if(r!==""){let n=r.replace("channel_",""),a=r.replace("channel_","subpackage_");this.ir.subpackages[a]==null&&(this.ir.subpackages[a]={name:this.context.casingsGenerator.generateName(n),...this.context.createPackage({name:n})}),this.ir.subpackages[a].websocket=r,this.ir.rootPackage.subpackages.push(a)}else this.ir.rootPackage.websocket=""}};var eba=class extends k2{isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}getTypeIdFromMessageReference(t){let r=t.$ref.match(/\/messages\/(.+)$/);if(!(!r||!r[1]))return r[1]}async convertReferenceToTypeReference(t){let r,i=t.$ref.match(/^.*\/schemas\/(.+)$/),n=t.$ref.match(/^.*\/channels\/([^/]+)\/messages\/(.+)$/),a=t.$ref.match(/^.*\/messages\/(.+)$/);if(i&&i[1])r=i[1];else if(n&&n[2]){let l=n[1],f=n[2];r=`${l}_${f}`}else a&&a[1]&&(r=a[1]);return r==null?{ok:!1}:(await this.resolveReference(t)).resolved?{ok:!0,reference:Bf.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(r),typeId:r,default:void 0,inline:!1})}:{ok:!1}}};var jGp=li(NKs(),1);var UKs=li(NKs(),1);var mGp=["get","post","put","delete","patch"];var aNo=class extends dS{operation;key="x-fern-idempotent";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-idempotent",path:this.breadcrumbs});return}return t}}};var TUD=pu.object({cursor:pu.string(),next_cursor:pu.string(),results:pu.string()}),CUD=pu.object({offset:pu.string(),results:pu.string(),step:pu.string().optional(),"has-next-page":pu.string().optional()}),FKs=pu.union([pu.boolean(),TUD,CUD]);var LKs="$request.",oNo="$response.",uNo=class extends dS{operation;document;key="x-fern-pagination";constructor({breadcrumbs:t,operation:r,document:i,context:n}){super({breadcrumbs:t,context:n}),this.operation=r,this.document=i}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=FKs.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean"){let i=this.getExtensionValue(this.document);if(i==null)return;if(typeof i=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.",path:this.breadcrumbs});return}let n=FKs.safeParse(i);if(!n.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${n.error.message}`,path:this.breadcrumbs});return}if(typeof n.data=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:n.data})}if(typeof r.data=="boolean"){this.context.errorCollector.collect({message:"Pagination extension is a boolean with no global configuration.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:r.data})}convertPaginationConfig({config:t}){let r=t;if("cursor"in r)return{type:"cursor",cursor:k2.maybeTrimPrefix(r.cursor,LKs),nextCursor:k2.maybeTrimPrefix(r.next_cursor,oNo),results:k2.maybeTrimPrefix(r.results,oNo)};let i=t;return{type:"offset",offset:k2.maybeTrimPrefix(i.offset,LKs),results:k2.maybeTrimPrefix(i.results,oNo),step:i.step!=null?k2.maybeTrimPrefix(i.step,LKs):void 0,hasNextPage:i["has-next-page"]!=null?k2.maybeTrimPrefix(i["has-next-page"],oNo):void 0}}};var BUD="$request.",xUD=pu.object({"stream-condition":pu.string().optional(),format:pu.enum(["sse","json"]).optional(),"stream-description":pu.string().optional(),"response-stream":pu.any(),response:pu.any()}),IUD=pu.union([pu.boolean(),xUD]),QEn=class extends dS{operation;key="x-fern-streaming";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=IUD.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-streaming extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean")return r.data?{type:"stream",format:"json"}:void 0;if(r.data["stream-condition"]==null&&r.data.format!=null)return{type:"stream",format:r.data.format};if(r.data["stream-condition"]==null){this.context.errorCollector.collect({message:"Missing required stream-condition property",path:this.breadcrumbs});return}return{type:"streamCondition",format:r.data.format??"json",streamDescription:r.data["stream-description"],streamConditionProperty:k2.maybeTrimPrefix(r.data["stream-condition"],BUD),responseStream:r.data["response-stream"],response:r.data.response}}};var sNo=class extends dS{operation;key="x-fern-webhook";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-webhook",path:this.breadcrumbs});return}return t}}};var cNo=class extends dS{operation;key="x-fern-examples";constructor({context:t,breadcrumbs:r,operation:i}){super({breadcrumbs:r,context:t}),this.operation=i}convert(){let t=this.getExtensionValue(this.operation);return t==null?void 0:(Array.isArray(t)?t:[]).filter(n=>{let a=cF.serialization.ExampleEndpointCallSchema.parse(n);return a.ok||this.context.errorCollector.collect({message:`Failed to parse x-fern-example in ${this.breadcrumbs.join(".")}`,path:this.breadcrumbs}),a.ok})}};var tba=class extends hA.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r,parameter:i})}async convert(){let t,r={};if(this.parameter.schema!=null){let n=await new hA.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required}).convert();n!=null&&(t=n.type,r=n.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}};var lNo=class extends hA.AbstractConverters.AbstractMediaTypeObjectConverter{requestBody;constructor({context:t,breadcrumbs:r,requestBody:i,group:n,method:a}){super({context:t,breadcrumbs:r,group:n,method:a}),this.requestBody=i}async convert(){if(!this.requestBody.content)return;let t=Object.keys(this.requestBody.content).filter(n=>n.includes("json"));for(let n of t){let a=this.handleJsonOrFormContent({contentType:n});if(a!=null)return a}let r=Object.keys(this.requestBody.content).filter(n=>n.includes("multipart"));for(let n of r){let a=this.requestBody.content[n],u=[...this.group,this.method,"Request"].join("_"),l=await this.parseMediaTypeObject({mediaTypeObject:a,schemaId:u});if(l!=null&&l.schema?.shape.type==="object")return{requestBody:FC.fileUpload({contentType:n,docs:this.requestBody.description,name:this.context.casingsGenerator.generateName(u),properties:l.schema?.shape.properties.map(s=>this.convertRequestBodyProperty({property:s,contentType:n})),v2Examples:await this.convertMediaTypeObjectExamples({mediaTypeObject:a,exampleGenerationStrategy:"request"})}),inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:u,inlinedTypes:l.inlinedTypes}),examples:l.examples}}let i=Object.keys(this.requestBody.content).filter(n=>n.includes("urlencoded"));for(let n of i){let a=this.handleJsonOrFormContent({contentType:n});if(a!=null)return a}}async handleJsonOrFormContent({contentType:t}){let r=[...this.group,this.method,"Request"].join("_"),i=this.requestBody.content[t],n=await this.parseMediaTypeObject({mediaTypeObject:i,schemaId:r});if(n!=null)return n.schema?.shape.type==="object"?{requestBody:FC.inlinedRequestBody({contentType:t,docs:this.requestBody.description,name:this.context.casingsGenerator.generateName(r),extendedProperties:n.schema?.shape.extendedProperties,extends:n.schema?.shape.extends,properties:n.schema?.shape.properties,extraProperties:n.schema?.shape.extraProperties,v2Examples:await this.convertMediaTypeObjectExamples({mediaTypeObject:i,exampleGenerationStrategy:"request"})}),inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:r,inlinedTypes:n.inlinedTypes})}:{requestBody:FC.reference({contentType:t,docs:this.requestBody.description,requestBodyType:n.type,v2Examples:await this.convertMediaTypeObjectExamples({mediaTypeObject:i,exampleGenerationStrategy:"request"})}),inlinedTypes:n.inlinedTypes??{}}}convertRequestBodyProperty({property:t,contentType:r}){let{isFile:i,isOptional:n,isArray:a}=this.recursivelyCheckTypeReferenceIsFile({typeReference:t.valueType});return i?a?O5.file(Zre.fileArray({key:t.name,isOptional:n,contentType:r,docs:t.docs})):O5.file(Zre.file({key:t.name,isOptional:n,contentType:r,docs:t.docs})):O5.bodyProperty({...t,contentType:r,style:void 0,name:t.name})}recursivelyCheckTypeReferenceIsFile({typeReference:t,isOptional:r,isArray:i}){return this.context.isList(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.list,isOptional:r,isArray:!0}):this.context.isOptional(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.optional,isOptional:!0,isArray:i}):this.context.isNullable(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.nullable,isOptional:r,isArray:i}):this.context.isFile(t)?{isFile:!0,isOptional:r??!1,isArray:i??!1}:{isFile:!1,isOptional:r??!1,isArray:i??!1}}};var fNo=class extends hA.AbstractConverters.AbstractMediaTypeObjectConverter{responseBody;statusCode;streamingExtension;constructor({context:t,breadcrumbs:r,responseBody:i,group:n,method:a,statusCode:u,streamingExtension:l}){super({context:t,breadcrumbs:r,group:n,method:a}),this.responseBody=i,this.statusCode=u,this.streamingExtension=l}async convert(){let t=Object.keys(this.responseBody.content??{}).filter(n=>n.includes("json")),r=[...this.group,this.method,"Response",this.statusCode].join("_");for(let n of[...t]){let a=this.responseBody.content?.[n],u=await this.parseMediaTypeObject({mediaTypeObject:a,schemaId:r});if(u!=null&&n.includes("json"))return{responseBody:SM.json(GY.response({responseBodyType:u.type,docs:this.responseBody.description,v2Examples:await this.convertMediaTypeObjectExamples({mediaTypeObject:a,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),inlinedTypes:u.inlinedTypes,examples:u.examples}}let i=Object.keys(this.responseBody.content??{}).filter(n=>!n.includes("json"));for(let n of i){let a=this.responseBody.content?.[n],u=await this.parseMediaTypeObject({mediaTypeObject:a,schemaId:r});if(u!=null&&this.isBinarySchema(u))return this.context.settings?.useBytesForBinaryResponse&&this.streamingExtension==null?{responseBody:SM.bytes({docs:this.responseBody.description,v2Examples:await this.convertMediaTypeObjectExamples({mediaTypeObject:a,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),inlinedTypes:{}}:{responseBody:SM.fileDownload({docs:this.responseBody.description,v2Examples:await this.convertMediaTypeObjectExamples({mediaTypeObject:a,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),inlinedTypes:{}}}}isBinarySchema(t){let r=t.type;switch(r.type){case"container":case"named":case"unknown":return!1;case"primitive":return r.primitive.v2==null?!1:r.primitive.v2.type==="string"&&r.primitive.v2.validation?.format==="binary";default:return!1}}};var dNo=class extends hA.AbstractConverters.AbstractMediaTypeObjectConverter{responseError;statusCode;constructor({context:t,breadcrumbs:r,responseError:i,group:n,method:a,statusCode:u}){super({context:t,breadcrumbs:r,group:n,method:a}),this.responseError=i,this.statusCode=u}async convert(){if(!this.responseError.content)return;let t=Object.keys(this.responseError.content).filter(i=>i.includes("json")),r=[...this.group,this.method,"Response",this.statusCode].join("_");for(let i of[...t]){let n=this.responseError.content?.[i],a=await this.parseMediaTypeObject({mediaTypeObject:n,schemaId:r});if(a!=null){if(a.schema!=null)return{error:{error:{...a.schema?.name,errorId:a.schema?.name.typeId},docs:this.responseError.description},inlinedTypes:a.inlinedTypes,examples:a.examples};if(a.type.type==="named")return{error:{error:{name:a.type.name,errorId:a.type.typeId,fernFilepath:a.type.fernFilepath},docs:this.responseError.description},inlinedTypes:a.inlinedTypes,examples:a.examples}}}}};var zUD=/{([^}]+)}/g,JEn=class extends w0{operation;method;path;inlinedTypes={};constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a}){super({context:t,breadcrumbs:r}),this.operation=i,this.method=n,this.path=a}convertHttpMethod(){switch(this.method){case"get":return S7.Get;case"post":return S7.Post;case"put":return S7.Put;case"delete":return S7.Delete;case"patch":return S7.Patch;default:return}}async convertParameters({breadcrumbs:t}){let r=[],i=[],n=[];if(!this.operation.parameters)return{pathParameters:r,queryParameters:i,headers:n};for(let l of this.operation.parameters){let f=await this.context.resolveMaybeReference({schemaOrReference:l,breadcrumbs:t});if(f==null)continue;let o=await new tba({context:this.context,breadcrumbs:t,parameter:f}).convert();if(o!=null)switch(this.inlinedTypes={...this.inlinedTypes,...o.inlinedTypes},o.type){case"path":r.push(o.parameter);break;case"query":i.push(o.parameter);break;case"header":n.push(o.parameter);break}}let u=[...this.path.matchAll(zUD)].map(l=>l[1]).filter(l=>!r.some(f=>f.name.originalName===l));for(let l of u){if(l==null)continue;let f=`${l}_example`;r.push({name:this.context.casingsGenerator.generateName(l),valueType:tba.STRING,docs:void 0,location:"ENDPOINT",variable:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{[f]:await this.generateStringParameterExample({example:void 0})}}})}return{pathParameters:r,queryParameters:i,headers:n}}async convertRequestBody({breadcrumbs:t,group:r,method:i}){if(this.operation.requestBody==null)return;let n=await this.context.resolveMaybeReference({schemaOrReference:this.operation.requestBody,breadcrumbs:t});if(n==null)return null;let u=await new lNo({context:this.context,breadcrumbs:t,requestBody:n,group:r??[],method:i}).convert();if(u!=null)return this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes},{value:u.requestBody,examples:u.examples}}async convertResponseBody({breadcrumbs:t,group:r,method:i,streamingExtension:n}){if(this.operation.responses==null)return;let a,u=!1;for(let[l,f]of Object.entries(this.operation.responses)){let s=parseInt(l);if(!(isNaN(s)||s<200||s>=300&&s<400)){if(a==null&&(a={value:void 0,errors:[],examples:{}}),s>=200&&s<300&&!u){let o=await this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:[...t,l]});if(o==null)continue;let b=await new fNo({context:this.context,breadcrumbs:[...t,l],responseBody:o,group:r??[],method:i,statusCode:l,streamingExtension:n}).convert();b!=null&&(u=!0,this.inlinedTypes={...this.inlinedTypes,...b.inlinedTypes},a.value={statusCode:s,body:b.responseBody})}if(s>=400&&s<500){let o=await this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:[...t,l]});if(o==null)continue;let b=await new dNo({context:this.context,breadcrumbs:[...t,l],responseError:o,group:r??[],method:i,statusCode:l}).convert();b!=null&&(this.inlinedTypes={...this.inlinedTypes,...b.inlinedTypes},a.errors.push(b.error))}}}return a}computeGroupNameAndLocationFromExtensions(){let r=new hne.SdkMethodNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.methodName,n=new hne.SdkGroupNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.groups??[];if(r!=null)return{group:n,method:r}}computeGroupNameFromTagAndOperationId(){let t=this.operation.tags?.[0],r=this.operation.operationId;if(r==null){let a=this.operation.summary!=null?$y(this.operation.summary):$y(`${this.method}_${this.path.split("/").join("_")}`);return t!=null?{group:[t],method:a}:{method:a}}if(t==null)return{method:r};let i=PGp(t),n=PGp(r);return hSe(i,n)?{method:t}:this.computeGroupAndMethodFromTokens({tag:t,tagTokens:i,operationId:r,operationIdTokens:n})}computeGroupAndMethodFromTokens({tag:t,tagTokens:r,operationId:i,operationIdTokens:n}){if(r.some((l,f)=>l!==n[f]))return{group:[t],method:i};let u=n.slice(r.length);return{group:[t],method:$y(u.join("_"))}}async generateStringParameterExample({example:t}){let r=new hA.ExampleConverter({breadcrumbs:this.breadcrumbs,context:this.context,schema:{type:"string"},example:t}),{validExample:i}=await r.convert();return i}};function PGp(e){let t=RUD(e)?NUD(e):FUD(e);return t=t.map(r=>r.toLowerCase()),t=exe(t),t}function RUD(e){return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)}function NUD(e){return e.split(/(?=[A-Z])/)}function FUD(e){return e.split(/[^a-zA-Z0-9]+/)}var pNo=class e extends JEn{idempotent;servers;streamingExtensionConverter;idToAuthScheme;static AUTHORIZATION_HEADER="Authorization";constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a,idempotent:u,servers:l,idToAuthScheme:f}){super({context:t,breadcrumbs:r,operation:i,method:n,path:a}),this.idempotent=u,this.servers=l,this.idToAuthScheme=f,this.streamingExtensionConverter=new QEn({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context})}async convert(){let t=this.convertHttpMethod();if(t==null)return;let{group:r,method:i}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),n=this.streamingExtensionConverter.convert(),{headers:a,pathParameters:u,queryParameters:l}=await this.convertParameters({breadcrumbs:[...this.breadcrumbs,"parameters"]}),f=await this.convertRequestBody({breadcrumbs:[...this.breadcrumbs,"requestBody"],group:r,method:i}),s=f?.value,o=await this.convertResponseBody({breadcrumbs:[...this.breadcrumbs,"responses"],group:r,method:i,streamingExtension:n}),c=o?.value,b=o!=null?o.errors:[],g=this.operation.servers?.[0]??this.servers?.[0]??this.context.spec.servers?.[0],O=[];this.context.namespace!=null&&O.push(this.context.namespace),O.push(...r??[]),O.push(i);let m=k7(this.path),P=g!=null?mZt.getServerName({server:g,context:this.context}):void 0,E=this.convertExamples({pathHead:m.head,httpMethod:t,baseUrl:P}),q=new Set(this.operation.security?.flatMap(D=>Object.keys(D))??[]),A=this.authSchemeToHeaders(Array.from(q));return A.length>0&&a.push(...A),{group:r,errors:{},endpoint:{id:O.join("."),displayName:this.operation.summary,method:t,name:this.context.casingsGenerator.generateName(i),baseUrl:P,path:m,pathParameters:u,queryParameters:l,headers:a.filter((D,C,z)=>C===z.findIndex($=>$.name.wireValue===D.name.wireValue)),requestBody:s,sdkRequest:void 0,response:c,errors:b,auth:this.operation.security!=null||this.context.spec.security!=null,availability:await this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),docs:this.operation.description,userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:this.idempotent??!1,basePath:void 0,fullPath:m,allPathParameters:u,pagination:void 0,transport:void 0,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:E},source:Xre.openapi()},inlinedTypes:this.inlinedTypes,servers:this.operation.servers?.filter(D=>!this.context.spec.servers?.some(C=>C.url===D.url))}}authSchemeToHeaders(t){let r=[];for(let i of t){let n=this.idToAuthScheme?.[i];if(n!=null)switch(n.type){case"bearer":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},valueType:w0.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0});break;case"basic":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},valueType:w0.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0});break;case"header":r.push({name:n.name,valueType:w0.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0});break}}return r}convertExamples({pathHead:t,httpMethod:r,baseUrl:i}){let a=new cNo({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation}).convert();return a==null?{}:Object.fromEntries(a.map((u,l)=>[u.id??l.toString(),{request:{docs:void 0,endpoint:{method:r,path:t},baseUrl:void 0,environment:i,auth:void 0,pathParameters:u["path-parameters"]??{},queryParameters:u["query-parameters"]??{},headers:u.headers??{},requestBody:u.request},response:{docs:void 0,statusCode:void 0,body:Ks.V2HttpEndpointResponseBody.json(u.response)},codeSamples:u["code-samples"]?.map(f=>({docs:void 0,language:("language"in f?f.language:f.sdk)??void 0,code:f.code}))}]))}};var KEn=class extends JEn{constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a}){super({context:t,breadcrumbs:r,operation:i,method:n,path:a})}async convert(){if(this.operation.requestBody==null){this.context.errorCollector.collect({message:"Skipping webhook because no request body present",path:this.breadcrumbs});return}let t=this.convertHttpMethod();if(t==null)return;if(t!=="POST"&&t!=="GET"){this.context.errorCollector.collect({message:"Skipping webhook because non-POST or GET method",path:this.breadcrumbs});return}let{group:r,method:i}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),n=[...this.breadcrumbs,"Payload"],{headers:a,pathParameters:u,queryParameters:l}=await this.convertParameters({breadcrumbs:n}),f=await this.convertRequestBody({breadcrumbs:n,group:r,method:i}),s;if(f?.value.type==="inlinedRequestBody")s=aV.inlinedPayload({name:f.value.name,extends:f.value.extends,properties:f.value.properties});else if(f?.value.type==="reference")s=aV.reference({payloadType:f.value.requestBodyType,docs:f.value.docs});else return;return{group:r,webhook:{id:`${r?.join(".")??""}.${i}`,name:this.context.casingsGenerator.generateName(i),displayName:this.operation.summary,method:t,headers:a,payload:s,examples:[],availability:await this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),docs:this.operation.description,v2Examples:void 0},inlinedTypes:this.inlinedTypes}}};var _No=class extends w0{pathItem;path;servers;idToAuthScheme;constructor({context:t,breadcrumbs:r,pathItem:i,path:n,servers:a,idToAuthScheme:u}){super({context:t,breadcrumbs:r}),this.pathItem=i,this.path=n,this.servers=a,this.idToAuthScheme=u}async convert(){let t=[],r=[],i={};for(let n of mGp){let a=this.pathItem[n];if(a==null)continue;let u=[...this.breadcrumbs,n],l=await this.tryParseAsWebhook({operationBreadcrumbs:u,operation:a,method:n,context:this.context});if(l!=null){r.push(l),Object.assign(i,l.inlinedTypes);continue}new QEn({breadcrumbs:u,operation:a,context:this.context}).convert()!=null;let o=await this.tryParseAsHttpEndpoint({operationBreadcrumbs:u,operation:a,method:n});o!=null&&(t.push(o),Object.assign(i,o.inlinedTypes))}return{endpoints:t,webhooks:r,inlinedTypes:i}}async tryParseAsWebhook({operation:t,method:r,operationBreadcrumbs:i,context:n}){return new sNo({breadcrumbs:i,operation:t,context:n}).convert()?await new KEn({context:this.context,breadcrumbs:i,operation:t,method:UKs.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path}).convert():void 0}async tryParseAsHttpEndpoint({operation:t,method:r,operationBreadcrumbs:i}){new uNo({breadcrumbs:i,operation:t,document:this.context.spec,context:this.context}).convert()!=null;let l=new aNo({breadcrumbs:i,operation:t,context:this.context}).convert();return await new pNo({context:this.context,breadcrumbs:i,operation:t,method:UKs.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,idempotent:l,idToAuthScheme:this.idToAuthScheme}).convert()}};var hNo=class extends w0{securityScheme;constructor({context:t,breadcrumbs:r,securityScheme:i}){super({context:t,breadcrumbs:r}),this.securityScheme=i}convert(){switch(this.securityScheme.type){case"http":{if(this.securityScheme.scheme==="bearer")return NC.bearer({token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:this.securityScheme.description});if(this.securityScheme.scheme==="basic")return NC.basic({username:this.context.casingsGenerator.generateName("username"),password:this.context.casingsGenerator.generateName("password"),usernameEnvVar:void 0,passwordEnvVar:void 0,docs:this.securityScheme.description});break}case"apiKey":{if(this.securityScheme.in==="header")return NC.header({name:{name:this.context.casingsGenerator.generateName(this.securityScheme.name),wireValue:this.securityScheme.name},valueType:Bf.container(Tv.optional(Bf.primitive({v1:"STRING",v2:wp.string({default:void 0,validation:void 0})}))),prefix:void 0,headerEnvVar:void 0,docs:this.securityScheme.description});break}case"oauth2":return NC.bearer({token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:this.securityScheme.description})}}};var rba=class extends w0{constructor({breadcrumbs:t,context:r}){super({breadcrumbs:t,context:r})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec,context:this.context}),this.context.spec=await this.resolveExternalRefs({spec:this.context.spec,context:this.context});let t=await this.convertSecuritySchemes();await this.convertSchemas(),await this.convertWebhooks();let{endpointLevelServers:r,errors:i}=await this.convertPaths({idToAuthScheme:t});this.convertServers({endpointLevelServers:r});let n={...this.ir,errors:i,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}};return n={...n,...bYr({ir:n,exampleGeneration:this.context.exampleGenerationArgs}),...SFi({ir:n,exampleGeneration:this.context.exampleGenerationArgs})},n}async convertSecuritySchemes(){if(this.context.authOverrides)return this.ir.auth=BKs({rawApiFileSchema:this.context.authOverrides,casingsGenerator:this.context.casingsGenerator}),{};let t=new Set(this.context.spec.security?.flatMap(n=>Object.keys(n))??[]),r={},i=[];for(let[n,a]of Object.entries(this.context.spec.components?.securitySchemes??{})){let u=await this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:["components","securitySchemes",n]});if(u==null)continue;let f=new hNo({context:this.context,breadcrumbs:["components","securitySchemes",n],securityScheme:u}).convert();f!=null&&(t.size===0||t.has(n))?i.push(f):f!=null&&(r[n]=f)}return i.length>0&&(this.ir.auth={requirement:"ANY",schemes:i,docs:void 0}),r}convertServers({endpointLevelServers:t}){if(this.context.environmentOverrides){this.ir.environments=zEn({rawApiFileSchema:this.context.environmentOverrides,casingsGenerator:this.context.casingsGenerator});return}let i=new mZt({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();i!=null&&(this.ir.environments=i.value)}async convertSchemas(){let t=this.context.getGroup({groupParts:[],namespace:this.context.namespace}),r=this.getOrCreatePackage({group:t});for(let[i,n]of Object.entries(this.context.spec.components?.schemas??{})){let u=await new hA.SchemaConverters.SchemaConverter({context:this.context,id:i,breadcrumbs:["components","schemas",i],schema:n}).convert();u!=null&&(r.types.push(i),this.ir.types={...this.ir.types,...u.inlinedTypes,[i]:u.typeDeclaration})}}async convertWebhooks(){let t={};for(let[,r]of Object.entries(this.context.spec.webhooks??{})){if(r==null){this.context.errorCollector.collect({message:"Skipping empty webhook",path:this.breadcrumbs});return}if(!("post"in r)){this.context.errorCollector.collect({message:"Skipping webhook because non-POST method",path:this.breadcrumbs});return}if(r.post?.operationId==null){this.context.errorCollector.collect({message:"Skipping webhook because no operation id present",path:this.breadcrumbs});return}let i=r.post.operationId,a=await new KEn({context:this.context,breadcrumbs:["webhooks",i],operation:r.post,method:jGp.OpenAPIV3.HttpMethods.POST,path:i}).convert();if(a!=null){let u=a.group?.join(".")??i;t[u]==null&&(t[u]=[]),t[u].push(i);let l=this.getOrCreatePackage({group:a.group});this.ir.webhookGroups[u]==null&&(this.ir.webhookGroups[u]=[]),this.ir.webhookGroups[u].push(a.webhook),l.webhooks=u,this.ir.types={...this.ir.types,...a.inlinedTypes}}}}async convertPaths({idToAuthScheme:t}){let r=[],i={};for(let[n,a]of Object.entries(this.context.spec.paths??{})){if(a==null)continue;let l=await new _No({context:this.context,breadcrumbs:["paths",n],pathItem:a,path:n}).convert();if(l!=null){for(let f of l.endpoints){let s=this.context.getGroup({groupParts:f.group,namespace:this.context.namespace}),o=this.getOrCreatePackage({group:f.group}),c=[...s].map(O=>this.context.casingsGenerator.generateName(O)),b=c[c.length-1],g=s.join(".");if(o.service=o.service??`service_${g}`,this.ir.services[o.service]==null&&(this.ir.services[o.service]=this.createNewService({allParts:c,finalpart:b})),this.ir.services[o.service]?.endpoints.push(f.endpoint),f.servers&&f.servers[0]!=null&&r.push(f.servers[0]),f.errors)for(let[O,m]of Object.entries(f.errors))i[O]=m}for(let f of l.webhooks){let s=this.context.getGroup({groupParts:f.group,namespace:this.context.namespace}),o=this.getOrCreatePackage({group:f.group}),c=s.join(".");this.ir.webhookGroups[c]??=[],this.ir.webhookGroups[c].push(f.webhook),o.webhooks=c}this.ir.types={...this.ir.types,...l.inlinedTypes}}}return{endpointLevelServers:r,errors:i}}createNewService({allParts:t,finalpart:r}){return{name:{fernFilepath:{allParts:t,packagePath:t.slice(0,-1),file:r}},displayName:void 0,basePath:k7(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0}}};var iba=class extends k2{isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}async convertReferenceToTypeReference(t){let r=this.getTypeIdFromSchemaReference(t);return r==null?{ok:!1}:(await this.resolveReference(t)).resolved?{ok:!0,reference:Bf.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(r),typeId:r,default:void 0,inline:!1})}:{ok:!1}}};var yNo=class extends hA.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r,parameter:i})}async convert(){let t,r={};if(this.parameter.schema!=null){let n=await new hA.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required}).convert();n!=null&&(t=n.type,r=n.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}};var LUD=pu.object({description:pu.string().optional(),required:pu.boolean().optional(),deprecated:pu.boolean().optional(),allowEmptyValue:pu.boolean().optional(),style:pu.string().optional(),explode:pu.boolean().optional(),allowReserved:pu.boolean().optional(),schema:pu.any().optional(),example:pu.any().optional(),examples:pu.record(pu.string(),pu.any()).optional(),content:pu.record(pu.string(),pu.any()).optional()}),UUD=LUD.extend({name:pu.string(),in:pu.string()}),VUD=pu.array(UUD),vNo=class extends dS{operation;key="x-fern-parameters";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null)try{return VUD.parse(t)}catch(r){this.context.errorCollector.collect({message:`Failed to parse x-fern-parameters extension: ${r instanceof Error?r.message:String(r)}`,path:this.breadcrumbs});return}}};var bNo=class extends w0{static STRING=Bf.primitive({v1:"STRING",v2:wp.string({default:void 0,validation:void 0})});method;pathParameters;queryParameters;headers;constructor({context:t,breadcrumbs:r,method:i,pathParameters:n=[],queryParameters:a=[],headers:u=[]}){super({context:t,breadcrumbs:r}),this.method=i,this.pathParameters=n,this.queryParameters=a,this.headers=u}async convert(){let t={},r="";for(let l of this.pathParameters)r+=`/{${l.name.originalName}}`;let i=k7(r),n=[];for(let[l,f]of this.method.params.entries()){let s;if(this.context.isReferenceObject(f)){let g=await this.context.resolveReference(f);if(g.resolved)s=g.value;else continue}else s=f;let o=[this.method.name,"Param",s.name].join("_"),b=await new hA.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[...this.breadcrumbs,`params[${l}]`],schemaIdOverride:o,context:this.context,schemaOrReference:s.schema}).convert();b!=null&&(n.push({docs:s.description,availability:await this.context.getAvailability({node:f,breadcrumbs:[...this.breadcrumbs,"parameters"]}),name:this.context.casingsGenerator.generateNameAndWireValue({name:s.name,wireValue:s.name}),valueType:b.type,v2Examples:b.schema?.v2Examples}),t={...b.inlinedTypes,...t,...b.schema!=null?{[o]:b.schema}:{}})}let a;if(this.method.result!=null){let l=await this.context.resolveMaybeReference({schemaOrReference:this.method.result,breadcrumbs:[...this.breadcrumbs,"result"]});if(l!=null){let f=new hA.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"result"],context:this.context,schemaOrReference:l.schema}),s=[...this.method.name,"Result"].join("_"),o=await f.convert();o!=null&&(a={docs:l.description,v2Examples:o?.schema?.v2Examples,responseBodyType:o.type},t={...o.inlinedTypes,...t,...o.schema!=null?{[s]:o.schema}:{}})}}return{endpoint:{baseUrl:void 0,basePath:void 0,auth:!1,method:"POST",id:this.method.name,docs:this.method.description,name:this.context.casingsGenerator.generateName(this.method.name),headers:this.headers,displayName:this.method.name,pathParameters:this.pathParameters,queryParameters:this.queryParameters,allPathParameters:this.pathParameters,path:i,fullPath:i,requestBody:n.length>0?FC.inlinedRequestBody({name:this.context.casingsGenerator.generateName([this.method.name,"Request"].join("_")),docs:void 0,properties:n,extends:[],extendedProperties:[],contentType:"application/json",extraProperties:!1,v2Examples:void 0}):void 0,sdkRequest:void 0,response:a!=null?{body:SM.json(GY.response(a)),statusCode:void 0}:void 0,errors:[],idempotent:!1,pagination:void 0,userSpecifiedExamples:[],autogeneratedExamples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:await this.convertExamples()},transport:void 0,availability:void 0,source:Xre.openrpc()},inlinedTypes:t}}async convertExamples(){let t={},r=0;if(this.method.examples&&this.method.examples.length>0){for(let i of this.method.examples??[]){let n;if(this.context.isReferenceObject(i)){let f=await this.context.resolveReference(i);if(f.resolved)n=f.value;else continue}else n=i;let a;if(n.result)if(this.context.isReferenceObject(n.result)){let f=await this.context.resolveReference(n.result);f.resolved&&(a=f.value)}else a=n.result;let u=n.name??`Example ${r+1}`,l=[];if(n.params&&Array.isArray(n.params)){l=[];for(let f of n.params)if(this.context.isReferenceObject(f)){let s=await this.context.resolveReference(f);if(s.resolved)l.push(s.value);else continue}else l.push(f)}t[u]={request:{docs:void 0,endpoint:{method:"POST",path:"/{apiKey}"},baseUrl:void 0,environment:void 0,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:l.map(f=>f.value)??void 0},response:{docs:void 0,statusCode:void 0,body:a?.value?Ks.V2HttpEndpointResponseBody.json({jsonrpc:"2.0",id:n.examplePairedRequest?.id||"1",result:a.value}):void 0},codeSamples:[]}}++r}return t}};var nba=class extends w0{constructor({context:t,breadcrumbs:r}){super({context:t,breadcrumbs:r})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec,context:this.context}),this.convertServers({}),await this.convertSchemas(),await this.convertMethods();let t={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}};return t={...t,...bYr({ir:t,exampleGeneration:this.context.exampleGenerationArgs}),...SFi({ir:t,exampleGeneration:this.context.exampleGenerationArgs})},t}convertServers({endpointLevelServers:t}){let i=new mZt({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();i!=null&&(this.ir.environments=i.value)}async convertSchemas(){let t=this.context.getGroup({groupParts:[],namespace:this.context.namespace}),r=this.getOrCreatePackage({group:t});for(let[i,n]of Object.entries(this.context.spec.components?.schemas??{})){let u=await new hA.SchemaConverters.SchemaConverter({context:this.context,id:i,breadcrumbs:["components","schemas",i],schema:n}).convert();u!=null&&(r.types.push(i),this.ir.types={...this.ir.types,...u.inlinedTypes,[i]:u.typeDeclaration})}}async convertMethods(){let r=new vNo({context:this.context,breadcrumbs:["methods"],operation:this.context.spec}).convert(),i=[],n=[],a=[];if(r&&r.length>0)for(let[f,s]of r.entries()){let c=await new yNo({context:this.context,breadcrumbs:[...this.breadcrumbs,`x-fern-parameters[${f}]`],parameter:s}).convert();if(c!=null)switch(c.type){case"path":{i.push(c.parameter);break}case"query":{n.push(c.parameter);break}case"header":{a.push(c.parameter);break}}}let u=this.context.getGroup({groupParts:[],namespace:this.context.namespace}),l=this.getOrCreatePackage({group:u});for(let f of this.context.spec.methods??[]){let s=await this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:["methods"]});if(s==null)continue;let c=await new bNo({context:this.context,breadcrumbs:["methods"],method:s,pathParameters:i,queryParameters:n,headers:a}).convert();if(c!=null){l.service==null&&(l.service="service_root");let b=[...u].map(O=>this.context.casingsGenerator.generateName(O)),g=b[b.length-1];this.ir.services[l.service]==null&&(this.ir.services[l.service]={name:{fernFilepath:{allParts:b,packagePath:b.slice(0,-1),file:g}},displayName:void 0,basePath:k7(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0}),this.ir.services[l.service]?.endpoints.push(c.endpoint),this.ir.types={...this.ir.types,...c.inlinedTypes}}}}};var aba=class extends k2{isReferenceObject(t){return t!=null&&"$ref"in t}async convertReferenceToTypeReference(t){let r=this.getTypeIdFromSchemaReference(t);return r==null?{ok:!1}:(await this.resolveReference(t)).resolved?{ok:!0,reference:Bf.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(r),typeId:r,default:void 0,inline:!1})}:{ok:!1}}};var wGp={[Yh.GenerationLanguage.PHP]:new Set(["abstract","and","as","break","callable","case","catch","class","clone","const","continue","declare","default","do","echo","else","elseif","enddeclare","endfor","endforeach","endif","endswitch","endwhile","extends","final","finally","fn","for","foreach","function","global","goto","list","if","implements","include","include_once","instanceof","insteadof","interface","match","namespace","new","or","parent","Parent","print","private","protected","public","readonly","require","require_once","return","static","switch","throw","trait","try","use","var","while","xor","yield"].flatMap(e=>[e,dx(e)])),[Yh.GenerationLanguage.TYPESCRIPT]:new Set(["any","as","boolean","break","case","catch","class","const","constructor","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","let","module","new","null","number","of","package","private","protected","public","require","return","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","Date","Error","File","Object","Record"]),[Yh.GenerationLanguage.JAVA]:new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","false","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","true","try","void","volatile","while"]),[Yh.GenerationLanguage.PYTHON]:new Set(["False","None","True","and","as","assert","async","","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","float","int","complex","bool","uuid","list","set","map","long","self","all"]),[Yh.GenerationLanguage.GO]:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[Yh.GenerationLanguage.RUBY]:new Set(["__ENCODING__","__LINE__","__FILE__","alias","and","begin","break","case","class","def","defined","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield","Object","JSON","Date","DateTime"]),[Yh.GenerationLanguage.CSHARP]:new Set(["abstract","as","base","bool","break","byte","case","catch","char","checked","class","const","continue","decimal","default","delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","goto","if","implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","operator","out","override","params","private","protected","public","readonly","ref","return","sbyte","sealed","short","sizeof","stackalloc","static","string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","ushort","using","virtual","void","volatile","while","add","and","alias","ascending","args","async","","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","managed","nameof","nint","not","notnull","nuint","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value","var","when","where","with","yield"]),[Yh.GenerationLanguage.SWIFT]:new Set([])};var WUD=["go","ruby"];function VKs({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let u=c=>({unsafeName:c,safeName:HUD({name:c,keywords:$UD({generationLanguage:e,keywords:t})})}),l=$y(n),f=dx(l),s=qCi(n),o=DCi(l);return r&&(!JUD(o)&&(e==null||WUD.includes(e))&&(l=o.map((c,b)=>{if(b>0){let g=gNo(c);if(g!=null)return g;if(ONo(c))return c.toUpperCase()}return c}).join(""),f=o.map((c,b)=>{let g=gNo(c);return g??(ONo(c)?c.toUpperCase():b===0?dx(c):c)}).join("")),s=n.split(" ").map(c=>c.split(/(\d+)/).map(qCi).join("")).join("_")),{originalName:n,camelCase:u(a?.casingOverrides?.camel??l),snakeCase:u(a?.casingOverrides?.snake??s),screamingSnakeCase:u(a?.casingOverrides?.["screaming-snake"]??s.toUpperCase()),pascalCase:u(a?.casingOverrides?.pascal??f)}},generateNameAndWireValue:({name:n,wireValue:a,opts:u})=>({name:i.generateName(n,u),wireValue:a})};return i}function HUD({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":QUD(e)?"_"+e:e}function $UD({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return wGp[e]}var GUD=/^[0-9]/;function QUD(e){return GUD.test(e)}function JUD(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=gNo(i)!=null||ONo(i),a=gNo(t)!=null||ONo(t);return n&&a})}function gNo(e){return YUD.get(e.toUpperCase())}function ONo(e){return KUD.has(e.toUpperCase())}var KUD=new Set(["ACL","API","ASCII","CPU","CSS","DNS","EOF","GUID","HTML","HTTP","HTTPS","ID","IP","JSON","LHS","QPS","RAM","RHS","RPC","SAML","SCIM","SLA","SMTP","SQL","SSH","SSO","TCP","TLS","TTL","UDP","UI","UID","UUID","URI","URL","UTF8","VM","XML","XMPP","XSRF","XSS"]),YUD=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);var SGp=require("fs/promises");async function WKs({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let i=(await(0,SGp.readFile)(t)).toString(),n;try{n=JSON.parse(i)}catch{n=Gd.load(i)}return r!=null?await rEn({absoluteFilePathToOverrides:r,context:e,data:n}):n}var nN=class extends Oha{type="oss";allSpecs;specs;sources;loader;constructor({allSpecs:t,specs:r,...i}){super({...i,respectReadonlySchemas:r.every(n=>n.settings?.respectReadonlySchemas),respectNullableSchemas:r.every(n=>n.settings?.respectNullableSchemas),onlyIncludeReferencedSchemas:r.every(n=>n.settings?.onlyIncludeReferencedSchemas),inlinePathParameters:r.every(n=>n.settings?.inlinePathParameters),objectQueryParameters:r.every(n=>n.settings?.objectQueryParameters),useBytesForBinaryResponse:r.filter(n=>n.type==="openapi"&&n.source.type==="openapi").some(n=>n.settings?.useBytesForBinaryResponse),respectForwardCompatibleEnums:r.filter(n=>n.type==="openapi"&&n.source.type==="openapi").some(n=>n.settings?.respectForwardCompatibleEnums),exampleGeneration:r[0]?.settings?.exampleGeneration}),this.specs=r,this.allSpecs=t,this.sources=this.convertSpecsToIdentifiableSources(r),this.loader=new b9t(this.absoluteFilePath)}async getOpenAPIIr({context:t,relativePathToDependency:r},i){let n=await aRe({context:t,specs:this.specs,relativePathToDependency:r});return kNi({context:t,documents:await this.loader.loadDocuments({context:t,specs:n}),options:{...i,respectReadonlySchemas:i?.respectReadonlySchemas??this.respectReadonlySchemas,respectNullableSchemas:i?.respectNullableSchemas??this.respectNullableSchemas,onlyIncludeReferencedSchemas:i?.onlyIncludeReferencedSchemas??this.onlyIncludeReferencedSchemas,inlinePathParameters:i?.inlinePathParameters??this.inlinePathParameters,objectQueryParameters:i?.objectQueryParameters??this.objectQueryParameters,exampleGeneration:i?.exampleGeneration??this.exampleGeneration,useBytesForBinaryResponse:i?.useBytesForBinaryResponse??this.useBytesForBinaryResponse}})}async getIntermediateRepresentation({context:t,audiences:r}){let i=await aRe({context:t,specs:this.specs}),n=await this.loader.loadDocuments({context:t,specs:i}),a=new EFi(r),u=this.generatorsConfiguration?.api?.auth!=null?{...this.generatorsConfiguration?.api}:void 0;u&&t.logger.trace("Using auth overrides from generators configuration");let l=this.generatorsConfiguration?.api?.environments!=null?{...this.generatorsConfiguration?.api}:void 0;l&&t.logger.trace("Using environment overrides from generators configuration");let f=this.generatorsConfiguration?.api?.headers!=null?{...this.generatorsConfiguration?.api}:void 0;f&&t.logger.trace("Using global header overrides from generators configuration");let s;for(let o of n){let c=new WEn({logger:t.logger}),b;switch(o.type){case"openapi":{let O=new iba({namespace:o.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:o.value,exampleGenerationArgs:{disabled:!1},errorCollector:c,authOverrides:u,environmentOverrides:l,globalHeaderOverrides:f});b=await new rba({context:O}).convert();break}case"asyncapi":{let O=new eba({namespace:o.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:o.value,exampleGenerationArgs:{disabled:!1},errorCollector:c});b=await new kva({context:O}).convert();break}default:c.collect({message:`Unsupported document type: ${o}`,path:[]});break}c.hasErrors()&&(t.logger.info(`${o.type==="openapi"?"OpenAPI":"AsyncAPI"} Importer encountered errors:`),c.logErrors());let g=VKs({generationLanguage:"typescript",keywords:void 0,smartCasing:!1});b!=null&&(s=s===void 0?b:NRo(s,b,g))}for(let o of this.allSpecs)if(o.type==="openrpc"){let c=new WEn({logger:t.logger}),b=new aba({namespace:o.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:await WKs({context:t,absoluteFilePath:o.absoluteFilepath,absoluteFilePathToOverrides:o.absoluteFilepathToOverrides}),exampleGenerationArgs:{disabled:!1},errorCollector:c}),O=await new nba({context:b}).convert();c.hasErrors()&&(t.logger.info("OpenRPC Importer encountered errors:"),c.logErrors());let m=VKs({generationLanguage:"typescript",keywords:void 0,smartCasing:!1});O!=null&&(s=s===void 0?O:NRo(s,O,m))}if(s===void 0)throw new Error("Failed to generate intermediate representation");return s}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new mDe({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:i,cliVersion:this.cliVersion,sources:this.sources})}getAbsoluteFilePaths(){return[this.absoluteFilePath,...this.specs.flatMap(t=>[t.type==="protobuf"?t.absoluteFilepathToProtobufTarget:t.absoluteFilepath,t.absoluteFilepathToOverrides]).filter(g0)]}getSources(){return this.sources}convertSpecsToIdentifiableSources(t){let r=new Set,i=[];return t.reduce((n,a)=>{let u=a.type==="protobuf"?a.absoluteFilepathToProtobufRoot:a.absoluteFilepath;return r.has(u)||(r.add(u),n.push({type:a.type,id:Uie(),absoluteFilePath:u})),n},i)}};var DGp={None:"none",Header:"header"};var WNo={};jo(WNo,{ConjureAliasDeclaration:()=>ENo,ConjureArgument:()=>LNo,ConjureArgumentWithParamType:()=>FNo,ConjureAuthDefinition:()=>kEn,ConjureAuthDefinitionType:()=>RNo,ConjureDefinitions:()=>INo,ConjureEndpointDefinition:()=>UNo,ConjureEnumDeclaration:()=>BNo,ConjureEnumVariant:()=>CNo,ConjureEnumWithDocs:()=>TNo,ConjureObjectDeclaration:()=>qNo,ConjureParamType:()=>NNo,ConjurePrimitive:()=>DNo,ConjureService:()=>VNo,ConjureServiceName:()=>SNo,ConjureType:()=>b_i,ConjureTypeDeclaration:()=>xNo,ConjureTypeReference:()=>g_i,ConjureTypeWithDocs:()=>MNo,ConjureTypes:()=>zNo,ConjureUnionDeclaration:()=>ANo,DefinitionFile:()=>eQp,WithDocs:()=>PZt,commons:()=>JKs,conjure:()=>KKs,services:()=>YKs,types:()=>XKs});var JKs={};jo(JKs,{WithDocs:()=>PZt});var kd={};jo(kd,{JsonError:()=>YEn,ParseError:()=>XEn,any:()=>UGp,bigint:()=>MGp,boolean:()=>VGp,booleanLiteral:()=>LGp,date:()=>AGp,discriminant:()=>XGp,enum_:()=>PNo,getObjectLikeUtils:()=>m9t,getObjectUtils:()=>AFi,getSchemaUtils:()=>oq,isProperty:()=>v_i,lazy:()=>qGp,lazyObject:()=>RGp,list:()=>wNo,number:()=>WGp,object:()=>jNo,objectWithoutOptionalProperties:()=>zGp,optional:()=>HKs,property:()=>CGp,record:()=>QGp,set:()=>JGp,string:()=>HGp,stringLiteral:()=>FGp,transform:()=>$Ks,undiscriminatedUnion:()=>YGp,union:()=>kGp,unknown:()=>$Gp,withParsedProperties:()=>QKs});var ij={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 RM(e,t){return`Expected ${t}. Received ${XUD(e)}.`}function XUD(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 k5(e){return{...e,json:EGp(e.json),parse:EGp(e.parse)}}function EGp(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(`
|
|
1958
1958
|
`)),{ok:!0,value:t}):i}}function mNo(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var YEn=class e extends Error{errors;constructor(t){super(t.map(mNo).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var XEn=class e extends Error{errors;constructor(t){super(t.map(mNo).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function oq(e){return{optional:()=>HKs(e),transform:t=>$Ks(e,t),parseOrThrow:(t,r)=>{let i=e.parse(t,r);if(i.ok)return i.value;throw new XEn(i.errors)},jsonOrThrow:(t,r)=>{let i=e.json(t,r);if(i.ok)return i.value;throw new YEn(i.errors)}}}function HKs(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:()=>ij.OPTIONAL};return{...t,...oq(t)}}function $Ks(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,...oq(r)}}function MGp(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:RM(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:RM(t,"bigint")}]},getType:()=>ij.BIGINT};return{...k5(e),...oq(e)}}var ZUD=/^([+-]?\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 AGp(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:RM(t,"string")}]}:ZUD.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:RM(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:RM(t,"Date object")}]},getType:()=>ij.DATE};return{...k5(e),...oq(e)}}function YG(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...k5(r),...oq(r)}}}function PNo(e){let t=new Set(e);return YG(ij.ENUM,(i,{allowUnrecognizedEnumValues:n,breadcrumbsPrefix:a=[]}={})=>typeof i!="string"?{ok:!1,errors:[{path:a,message:RM(i,"string")}]}:!t.has(i)&&!n?{ok:!1,errors:[{path:a,message:RM(i,"enum")}]}:{ok:!0,value:i})()}function qGp(e){let t=GKs(e);return{...t,...oq(t)}}function GKs(e){return{parse:(t,r)=>ZEn(e).parse(t,r),json:(t,r)=>ZEn(e).json(t,r),getType:()=>ZEn(e).getType()}}function ZEn(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function oba(e){return Object.entries(e)}function uba(e,t){let r=new Set(t);return Object.entries(e).reduce((i,[n,a])=>(r.has(n)&&(i[n]=a),i),{})}function y_i(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 sba(e){return Object.keys(e)}function TGp(e,t){let r=[],i=[];for(let n of e)t(n)?r.push(n):i.push(n);return[r,i]}function m9t(e){return{withParsedProperties:t=>QKs(e,t)}}function QKs(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,[f,s])=>({...l,[f]:typeof s=="function"?s(a.value):s}),{});return{ok:!0,value:{...a.value,...u}}},json:(i,n)=>{if(!y_i(i))return{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:RM(i,"object")}]};let a=new Set(Object.keys(t)),u=uba(i,Object.keys(i).filter(l=>!a.has(l)));return e.json(u,n)},getType:()=>e.getType()};return{...r,...oq(r),...m9t(r)}}function CGp(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function v_i(e){return e.isProperty}function jNo(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,i])=>v_i(i)?i.rawKey:r),_getParsedProperties:()=>sba(e),parse:(r,i)=>{let n={},a=[];for(let[u,l]of oba(e)){let f=v_i(l)?l.rawKey:u,s=v_i(l)?l.valueSchema:l,o={rawKey:f,parsedKey:u,valueSchema:s};n[f]=o,IGp(s)&&a.push(f)}return BGp({value:r,requiredKeys:a,getProperty:u=>{let l=n[u];if(l!=null)return{transformedKey:l.parsedKey,transform:f=>l.valueSchema.parse(f,{...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 oba(e)){let l=v_i(u)?u.valueSchema:u;IGp(l)&&n.push(a)}return BGp({value:r,requiredKeys:n,getProperty:a=>{let u=e[a];if(u!=null)return v_i(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:()=>ij.OBJECT};return{...k5(t),...oq(t),...m9t(t),...AFi(t)}}function BGp({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:i="fail",skipValidation:n=!1,breadcrumbsPrefix:a=[]}){if(!y_i(e))return{ok:!1,errors:[{path:a,message:RM(e,"object")}]};let u=new Set(t),l=[],f={};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?f[c.transformedKey]=b.value:(f[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":f[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:f}:{ok:!1,errors:l}}function AFi(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(i,n)=>xGp({extensionKeys:t._getRawProperties(),value:i,transformBase:a=>e.parse(a,n),transformExtension:a=>t.parse(a,n)}),json:(i,n)=>xGp({extensionKeys:t._getParsedProperties(),value:i,transformBase:a=>e.json(a,n),transformExtension:a=>t.json(a,n)}),getType:()=>ij.OBJECT};return{...r,...oq(r),...m9t(r),...AFi(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:()=>ij.OBJECT};return{...t,...oq(t),...m9t(t),...AFi(t)}}}}function xGp({extensionKeys:e,value:t,transformBase:r,transformExtension:i}){let n=new Set(e),[a,u]=TGp(sba(t),s=>n.has(s)),l=r(uba(t,u)),f=i(uba(t,a));return l.ok&&f.ok?{ok:!0,value:{...l.value,...f.value}}:{ok:!1,errors:[...l.ok?[]:l.errors,...f.ok?[]:f.errors]}}function IGp(e){return!kUD(e)}function kUD(e){switch(e.getType()){case ij.ANY:case ij.UNKNOWN:case ij.OPTIONAL:return!0;default:return!1}}function zGp(e){return jNo(e)}function RGp(e){let t={...GKs(e),_getRawProperties:()=>ZEn(e)._getRawProperties(),_getParsedProperties:()=>ZEn(e)._getParsedProperties()};return{...t,...oq(t),...m9t(t),...AFi(t)}}function wNo(e){let t={parse:(r,i)=>NGp(r,(n,a)=>e.parse(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,i)=>NGp(r,(n,a)=>e.json(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>ij.LIST};return{...k5(t),...oq(t)}}function NGp(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:RM(e,"list"),path:[]}]}}function FGp(e){return YG(ij.STRING_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:RM(r,`"${e}"`)}]})()}function LGp(e){return YG(ij.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:RM(r,`${e.toString()}`)}]})()}var UGp=YG(ij.ANY,e=>({ok:!0,value:e}));var VGp=YG(ij.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:RM(e,"boolean")}]});var WGp=YG(ij.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:RM(e,"number")}]});var HGp=YG(ij.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:RM(e,"string")}]});var $Gp=YG(ij.UNKNOWN,e=>({ok:!0,value:e}));function QGp(e,t){let r={parse:(i,n)=>GGp({value:i,isKeyNumeric:e.getType()===ij.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)=>GGp({value:i,isKeyNumeric:e.getType()===ij.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:()=>ij.RECORD};return{...k5(r),...oq(r)}}function GGp({value:e,isKeyNumeric:t,transformKey:r,transformValue:i,breadcrumbsPrefix:n=[]}){return y_i(e)?oba(e).reduce((a,[u,l])=>{if(l==null)return a;let f=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(f.ok&&o.ok&&c.ok)return{ok:!0,value:{...f.value,[o.value]:c.value}};let b=[];return f.ok||b.push(...f.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:RM(e,"object")}]}}function JGp(e){let t=wNo(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:RM(i,"Set")}]},getType:()=>ij.SET};return{...k5(r),...oq(r)}}function YGp(e){let t={parse:(r,i)=>KGp((n,a)=>n.parse(r,a),e,i),json:(r,i)=>KGp((n,a)=>n.json(r,a),e,i),getType:()=>ij.UNDISCRIMINATED_UNION};return{...k5(t),...oq(t)}}function KGp(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 XGp(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function kGp(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,i=typeof e=="string"?e:e.parsedDiscriminant,n=PNo(sba(t)),a={parse:(u,l)=>ZGp({value:u,discriminant:r,transformedDiscriminant:i,transformDiscriminantValue:f=>n.parse(f,{allowUnrecognizedEnumValues:l?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...l?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:f=>t[f],allowUnrecognizedUnionMembers:l?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(f,s)=>s.parse(f,l),breadcrumbsPrefix:l?.breadcrumbsPrefix}),json:(u,l)=>ZGp({value:u,discriminant:i,transformedDiscriminant:r,transformDiscriminantValue:f=>n.json(f,{allowUnrecognizedEnumValues:l?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...l?.breadcrumbsPrefix??[],i]}),getAdditionalPropertiesSchema:f=>t[f],allowUnrecognizedUnionMembers:l?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(f,s)=>s.json(f,l),breadcrumbsPrefix:l?.breadcrumbsPrefix}),getType:()=>ij.UNION};return{...k5(a),...oq(a),...m9t(a)}}function ZGp({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:i,getAdditionalPropertiesSchema:n,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:u,breadcrumbsPrefix:l=[]}){if(!y_i(e))return{ok:!1,errors:[{path:l,message:RM(e,"object")}]};let{[t]:f,...s}=e;if(f==null)return{ok:!1,errors:[{path:l,message:`Missing discriminant ("${t}")`}]};let o=i(f);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]:f,...b.value}}:b}var PZt=kd.objectWithoutOptionalProperties({docs:kd.string().optional()});var KKs={};jo(KKs,{ConjureServiceName:()=>SNo,DefinitionFile:()=>eQp});var SNo=kd.string();var DNo=kd.enum_(["rid","string","safelong","integer","double","boolean"]);var b_i=kd.undiscriminatedUnion([DNo,kd.string()]);var ENo=kd.objectWithoutOptionalProperties({alias:b_i,docs:kd.string().optional()});var MNo=kd.objectWithoutOptionalProperties({type:b_i,docs:kd.string().optional()});var g_i=kd.undiscriminatedUnion([b_i,MNo]);var ANo=kd.objectWithoutOptionalProperties({union:kd.record(kd.string(),g_i)});var qNo=kd.objectWithoutOptionalProperties({fields:kd.record(kd.string(),g_i)});var TNo=kd.objectWithoutOptionalProperties({value:kd.string()}).extend(PZt);var CNo=kd.undiscriminatedUnion([kd.string(),TNo]);var BNo=kd.objectWithoutOptionalProperties({values:kd.list(CNo)});var xNo=kd.undiscriminatedUnion([ENo,ANo,qNo,BNo]);var INo=kd.objectWithoutOptionalProperties({objects:kd.record(kd.string(),xNo).optional()});var zNo=kd.objectWithoutOptionalProperties({conjureImports:kd.property("conjure-imports",kd.record(kd.string(),kd.string()).optional()),definitions:INo.optional()});var RNo=kd.enum_(["none","header"]);var kEn=kd.undiscriminatedUnion([RNo,kd.string()]);var NNo=kd.enum_(["path","query","body"]);var FNo=kd.objectWithoutOptionalProperties({paramType:kd.property("param-type",NNo),type:kd.string()}).extend(PZt);var LNo=kd.undiscriminatedUnion([kd.string(),FNo]);var UNo=kd.objectWithoutOptionalProperties({http:kd.string(),auth:kEn.optional(),args:kd.record(kd.string(),LNo).optional(),returns:g_i.optional()}).extend(PZt);var VNo=kd.objectWithoutOptionalProperties({name:kd.string().optional(),package:kd.string().optional(),basePath:kd.property("base-path",kd.string().optional()),defaultAuth:kd.property("default-auth",kEn.optional()),endpoints:kd.record(kd.string(),UNo).optional()}).extend(PZt);var eQp=kd.objectWithoutOptionalProperties({types:zNo.optional(),services:kd.record(SNo,VNo).optional()});var YKs={};jo(YKs,{ConjureArgument:()=>LNo,ConjureArgumentWithParamType:()=>FNo,ConjureAuthDefinition:()=>kEn,ConjureAuthDefinitionType:()=>RNo,ConjureEndpointDefinition:()=>UNo,ConjureParamType:()=>NNo,ConjureService:()=>VNo});var XKs={};jo(XKs,{ConjureAliasDeclaration:()=>ENo,ConjureDefinitions:()=>INo,ConjureEnumDeclaration:()=>BNo,ConjureEnumVariant:()=>CNo,ConjureEnumWithDocs:()=>TNo,ConjureObjectDeclaration:()=>qNo,ConjurePrimitive:()=>DNo,ConjureType:()=>b_i,ConjureTypeDeclaration:()=>xNo,ConjureTypeReference:()=>g_i,ConjureTypeWithDocs:()=>MNo,ConjureTypes:()=>zNo,ConjureUnionDeclaration:()=>ANo});var tQp=require("fs/promises");async function rQp(e,t){let r=[];for(let i of await pxe(e,t))r.push(await eVD({relativeFilepath:KA(e,i),absoluteFilepath:i}));return r}async function eVD({relativeFilepath:e,absoluteFilepath:t}){let r=(await(0,tQp.readFile)(t)).toString().replaceAll(/: rid(?:$|\s)/g,`: string
|
|
1959
1959
|
`).replaceAll("<rid>","<string>").replaceAll("rid>","string>").replaceAll(": safelong",": long").replaceAll("<safelong>","<long>").replaceAll("safelong>","long>").replaceAll(": any",": unknown").replaceAll("<any>","<unknown>").replaceAll("any>","unknown>");return{relativeFilepath:e,absoluteFilepath:t,fileContents:WNo.DefinitionFile.parseOrThrow(Gd.load(r),{unrecognizedObjectKeys:"passthrough",allowUnrecognizedEnumValues:!0,allowUnrecognizedUnionMembers:!0})}}function iQp(e,t){if(tVD(e))return t.alias(e);if(rVD(e))return t.enum(e);if(iVD(e))return t.object(e);if(nVD(e))return t.union(e);Mo(e)}function tVD(e){return e?.alias!=null}function rVD(e){return e?.values!=null}function iVD(e){return e?.fields!=null}function nVD(e){return e?.union!=null}var cba=class extends lha{fernDefinitionBuilder=new gNi(!1);conjureFilepathToFernFilepath={};async import({absolutePathToConjureFolder:t,authOverrides:r,environmentOverrides:i,globalHeaderOverrides:n}){if(r!=null){for(let[a,u]of Object.entries(r["auth-schemes"]??{}))this.fernDefinitionBuilder.addAuthScheme({name:a,schema:u});r.auth!=null&&this.fernDefinitionBuilder.setAuth(r.auth)}if(i!=null){for(let[a,u]of Object.entries(i.environments??{}))this.fernDefinitionBuilder.addEnvironment({name:a,schema:u});i["default-environment"]!=null&&this.fernDefinitionBuilder.setDefaultEnvironment(i["default-environment"]),i["default-url"]!=null&&this.fernDefinitionBuilder.setDefaultUrl(i["default-url"])}return await nQp(t,(a,u,l)=>{for(let[o,c]of Object.entries(l.services??{})){let b=GXa({value:o,suffix:"Service"});this.conjureFilepathToFernFilepath[u]=Xa.of(`${b}/__package__.yml`);return}let s=ubs(u)?.split(".")[0];s!=null&&(this.conjureFilepathToFernFilepath[u]=Xa.of(`${s}/__package__.yml`))}),await nQp(t,(a,u,l)=>{if(l.services==null||Object.keys(l.services??{}).length===0){let f=this.conjureFilepathToFernFilepath[u];if(f==null)throw new Error(`Failed to find corresponding fern filepath for conjure file ${u}`);for(let[s,o]of Object.entries(l.types?.conjureImports??{})){let c=this.getFernFileToImport({absoluteFilePathToConjureFile:a,absoluteFilePathToConjureFolder:t,importFilePath:Xa.of(o)});this.fernDefinitionBuilder.addImport({file:f,fileToImport:Xa.of(c),alias:s})}this.importAllTypes({conjureFile:l,fernFilePath:f});return}for(let[f,s]of Object.entries(l.services)){let o=GXa({value:f,suffix:"Service"}),c=Xa.of(`${o}/__package__.yml`),b={};s.basePath!=null&&(b["base-path"]=s.basePath),s.docs!=null&&(b.docs=s.docs),this.fernDefinitionBuilder.setServiceInfo(c,b),this.importAllTypes({conjureFile:l,fernFilePath:c});for(let[g,O]of Object.entries(l.types?.conjureImports??{})){let m=this.getFernFileToImport({absoluteFilePathToConjureFile:a,absoluteFilePathToConjureFolder:t,importFilePath:Xa.of(O)});this.fernDefinitionBuilder.addImport({file:c,fileToImport:Xa.of(m),alias:g})}for(let[g,O]of Object.entries(s.endpoints??{})){let m=y_s(O.http);if(m.type==="failure"){this.context?.logger.error(`Failed to parse ${O.http}. Skipping.`);continue}let E={auth:(O.auth??s.defaultAuth)!==DGp.None,path:m.path,method:m.method,response:O.returns==="binary"?"file":O.returns};O.docs!=null&&(E.docs=O.docs);let q={};if(O.args!=null)for(let A of m.pathParameters){let D=O.args[A];if(D==null)throw new Error(`Failed to find path parameter ${A} in ${O.http}`);q[A]=typeof D=="string"?D:{type:D.type}}Object.entries(q).length>0&&(E["path-parameters"]=q);for(let[A,D]of Object.entries(O.args??{}))if(q[A]==null)if(typeof D=="string")E.request?typeof E.request=="string"&&(E.request={body:E.request}):E.request={},E.request.body=D==="binary"?"bytes":D;else switch(D.paramType){case"body":E.request={body:D.type==="binary"?"bytes":D.type};break;case"query":E.request==null?E.request={"query-parameters":{[A]:D.type}}:typeof E.request!="string"&&E.request?.["query-parameters"]==null?E.request["query-parameters"]={[A]:D.type}:typeof E.request!="string"&&E.request?.["query-parameters"]!=null&&(E.request["query-parameters"][A]=D.type)}E.request!=null&&typeof E.request!="string"&&E.request?.["query-parameters"]!=null&&(E.request.name=`${g}Request`),this.fernDefinitionBuilder.addEndpoint(c,{name:g,schema:E,source:void 0})}}}),this.fernDefinitionBuilder.build()}importAllTypes({conjureFile:t,fernFilePath:r}){for(let[i,n]of Object.entries(t.types?.definitions?.objects??{}))iQp(n,{alias:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{type:a.alias,docs:a.docs}})},object:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{properties:a.fields}})},enum:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{enum:a.values}})},union:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{union:Object.fromEntries(Object.entries(a.union).map(([u,l])=>[u,{type:typeof l=="string"?l:l.type,docs:typeof l=="string"?void 0:l.docs,key:u}]))}})}})}getFernFileToImport({absoluteFilePathToConjureFile:t,importFilePath:r,absoluteFilePathToConjureFolder:i}){let n=Lu(Zd(t),Xa.of(r)),a=y8t(i,n),u=this.conjureFilepathToFernFilepath[a];if(u==null)throw new Error(`Failed to find corresponding fern filepath for conjure file ${a}`);return u}};async function nQp(e,t){for(let r of await rQp(e,"{yml,yaml}"))await t(r.absoluteFilepath,r.relativeFilepath,r.fileContents)}function aQp(e,t){return nd(e,t)}var HNo=class extends r9t{type="conjure";absolutePathToConjureFolder;constructor({relativePathToConjureDirectory:t,...r}){super(r),this.absolutePathToConjureFolder=Lu(r.absoluteFilePath,t)}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new mDe({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:i,cliVersion:this.cliVersion,sources:void 0})}async getDefinition({context:t},r){let n=await new cba(t).import({absolutePathToConjureFolder:this.absolutePathToConjureFolder,authOverrides:this.generatorsConfiguration?.api?.auth!=null?{...this.generatorsConfiguration?.api}:void 0,environmentOverrides:this.generatorsConfiguration?.api?.environments!=null?{...this.generatorsConfiguration?.api}:void 0,globalHeaderOverrides:this.generatorsConfiguration?.api?.headers!=null?{...this.generatorsConfiguration?.api}:void 0});return{absoluteFilePath:Hl.of("/DUMMY_PATH"),rootApiFile:{defaultUrl:n.rootApiFile["default-url"],contents:n.rootApiFile,rawContents:Gd.dump(n.rootApiFile)},namedDefinitionFiles:{...aQp(n.definitionFiles,a=>({absoluteFilepath:Hl.of("/DUMMY_PATH"),rawContents:Gd.dump(a),contents:a})),[Xa.of(nS)]:{absoluteFilepath:Hl.of("/DUMMY_PATH"),rawContents:Gd.dump(n.packageMarkerFile),contents:n.packageMarkerFile}},packageMarkers:{},importedDefinitions:{}}}getAbsoluteFilePaths(){return[this.absolutePathToConjureFolder]}};function ZKs(e,t){for(let[r,i]of KN(e.failures))aVD({relativeFilepath:r,failure:i,logger:t})}function aVD({relativeFilepath:e,failure:t,logger:r}){switch(t.type){case pP.MISCONFIGURED_DIRECTORY:r.error("Misconfigured fern directory: please see the docs at https://buildwithfern.com/learn/api-definition/introduction/what-is-the-fern-folder");break;case pP.FILE_READ:r.error("Failed to open file: "+e);break;case pP.FILE_MISSING:r.error("Missing file: "+e);break;case pP.FILE_PARSE:t.error instanceof Waa?r.error(kie({title:`Failed to parse ${e}: ${t.error.reason}`,subtitle:t.error.mark.snippet})):r.error("Failed to parse file: "+e);break;case pP.STRUCTURE_VALIDATION:for(let i of t.error.issues)for(let{title:n,subtitle:a}of oVD(i))r.error(kie({title:n,subtitle:a,breadcrumbs:[e,...i.path]}));break;case pP.FAILED_TO_LOAD_DEPENDENCY:r.error("Failed to load dependency: "+t.dependencyName);break;case pP.DEPENDENCY_NOT_LISTED:r.error(`Dependency is not listed in ${CZa}: `+t.dependencyName);break;case pP.EXPORT_PACKAGE_HAS_DEFINITIONS:r.error("Exported package contains API definitions: "+t.pathToPackage);break;case pP.EXPORTING_PACKAGE_MARKER_OTHER_KEYS:r.error(`${t.pathOfPackageMarker} has an export so it cannot define other keys.`);break;case pP.JSONSCHEMA_VALIDATION:t.error.error!=null&&r.error(kie({title:t.error.error.message??"Unknown error",breadcrumbs:[e,...t.error.error.instancePath.split("/").filter(i=>i!=="")]}));break;default:Mo(t)}}function oVD(e){switch(e.code){case Wl.invalid_type:return[{title:"Incorrect type",subtitle:`Expected ${Ws.underline(e.expected)} but received ${Ws.underline(e.received)}`}];case Wl.unrecognized_keys:return e.keys.map(t=>({title:"Unexpected key",subtitle:`Encountered unexpected key ${Ws.underline(t)}`}));case Wl.invalid_enum_value:return[{title:"Unrecognized value",subtitle:`Allowed values: ${e.options.map(t=>Ws.underline(t)).join(", ")}`}];case Wl.invalid_union:case Wl.invalid_arguments:case Wl.invalid_return_type:case Wl.invalid_date:case Wl.invalid_string:case Wl.too_small:case Wl.too_big:case Wl.invalid_intersection_types:case Wl.not_multiple_of:case Wl.custom:default:return[{title:e.message}]}}var oQp=require("fs/promises");async function uQp(e,t){let r=[];for(let i of await pxe(e,t))r.push(await uVD({relativeFilepath:KA(e,i),absoluteFilepath:i}));return r}async function uVD({relativeFilepath:e,absoluteFilepath:t}){return{relativeFilepath:e,absoluteFilepath:t,fileContents:(await(0,oQp.readFile)(t)).toString()}}async function sQp({absolutePathToWorkspace:e}){let t=Lu(e,Xa.of(DWf));if(!await Cf(t))return;let i=await uQp(t,"{md,mdx}");return{files:await Promise.all(i.map(n=>({absoluteFilepath:n.absoluteFilepath,contents:n.fileContents})))}}async function kKs({absolutePathToWorkspace:e,namespace:t,definitions:r}){let i=[];for(let n of r){let a=n.overrides!=null?Lu(e,Xa.of(n.overrides)):void 0;if(n.schema.type==="protobuf"){let l=Xa.of(n.schema.root),f=Lu(e,l);if(!await Cf(f))return{didSucceed:!1,failures:{[Xa.of(n.schema.root)]:{type:pP.FILE_MISSING}}};let s=Lu(e,Xa.of(n.schema.target));if(!await Cf(s))return{didSucceed:!1,failures:{[Xa.of(n.schema.target)]:{type:pP.FILE_MISSING}}};i.push({type:"protobuf",absoluteFilepathToProtobufRoot:f,absoluteFilepathToProtobufTarget:s,absoluteFilepathToOverrides:a,relativeFilepathToProtobufRoot:l,generateLocally:n.schema.localGeneration,settings:{audiences:n.audiences??[],useTitlesAsName:n.settings?.shouldUseTitleAsName??!0,shouldUseUndiscriminatedUnionsWithLiterals:n.settings?.shouldUseUndiscriminatedUnionsWithLiterals??!1,shouldUseIdiomaticRequestNames:n.settings?.shouldUseIdiomaticRequestNames??!1,optionalAdditionalProperties:n.settings?.shouldUseOptionalAdditionalProperties??!0,coerceEnumsToLiterals:n.settings?.coerceEnumsToLiterals??!0,objectQueryParameters:n.settings?.objectQueryParameters??!1,respectReadonlySchemas:n.settings?.respectReadonlySchemas??!1,respectNullableSchemas:n.settings?.respectNullableSchemas??!1,onlyIncludeReferencedSchemas:n.settings?.onlyIncludeReferencedSchemas??!1,inlinePathParameters:n.settings?.inlinePathParameters??!1,disableExamples:!1,discriminatedUnionV2:n.settings?.shouldUseUndiscriminatedUnionsWithLiterals??!1,preserveSchemaIds:!1,asyncApiNaming:n.settings?.asyncApiMessageNaming??"v1",filter:n.settings?.filter,exampleGeneration:void 0,defaultFormParameterEncoding:n.settings?.defaultFormParameterEncoding,useBytesForBinaryResponse:n.settings?.useBytesForBinaryResponse??!1,respectForwardCompatibleEnums:n.settings?.respectForwardCompatibleEnums??!1,additionalPropertiesDefaultsTo:n.settings?.additionalPropertiesDefaultsTo??!1}});continue}if(n.schema.type==="openrpc"){let l=Xa.of(n.schema.path),f=Lu(e,l);i.push({type:"openrpc",absoluteFilepath:f,absoluteFilepathToOverrides:a,namespace:t});continue}let u=Lu(e,Xa.of(n.schema.path));if(!await Cf(u))return{didSucceed:!1,failures:{[Xa.of(n.schema.path)]:{type:pP.FILE_MISSING}}};if(n.overrides!=null&&a!=null&&!await Cf(a))return{didSucceed:!1,failures:{[Xa.of(n.overrides)]:{type:pP.FILE_MISSING}}};i.push({type:"openapi",absoluteFilepath:u,absoluteFilepathToOverrides:a,settings:{audiences:n.audiences??[],useTitlesAsName:n.settings?.shouldUseTitleAsName??!0,shouldUseUndiscriminatedUnionsWithLiterals:n.settings?.shouldUseUndiscriminatedUnionsWithLiterals??!1,shouldUseIdiomaticRequestNames:n.settings?.shouldUseIdiomaticRequestNames??!1,optionalAdditionalProperties:n.settings?.shouldUseOptionalAdditionalProperties??!0,coerceEnumsToLiterals:n.settings?.coerceEnumsToLiterals??!0,objectQueryParameters:n.settings?.objectQueryParameters??!1,respectReadonlySchemas:n.settings?.respectReadonlySchemas??!1,respectNullableSchemas:n.settings?.respectNullableSchemas??!1,onlyIncludeReferencedSchemas:n.settings?.onlyIncludeReferencedSchemas??!1,inlinePathParameters:n.settings?.inlinePathParameters??!1,disableExamples:!1,discriminatedUnionV2:n.settings?.shouldUseUndiscriminatedUnionsWithLiterals??!1,preserveSchemaIds:!1,asyncApiNaming:n.settings?.asyncApiMessageNaming??"v1",filter:n.settings?.filter,exampleGeneration:n.settings?.exampleGeneration,defaultFormParameterEncoding:n.settings?.defaultFormParameterEncoding,useBytesForBinaryResponse:n.settings?.useBytesForBinaryResponse??!1,respectForwardCompatibleEnums:n.settings?.respectForwardCompatibleEnums??!1,additionalPropertiesDefaultsTo:n.settings?.additionalPropertiesDefaultsTo??!1},source:{type:"openapi",file:u},namespace:t})}return i}async function lba({absolutePathToWorkspace:e,context:t,cliVersion:r,workspaceName:i}){let n=await Q8t({absolutePathToWorkspace:e,context:t}),a;try{a=await sQp({absolutePathToWorkspace:e})}catch{}if(n?.api!=null&&n?.api.type==="conjure")return{didSucceed:!0,workspace:new HNo({workspaceName:i,absoluteFilePath:e,generatorsConfiguration:n,changelog:a,cliVersion:r,context:t,relativePathToConjureDirectory:Xa.of(n.api.pathToConjureDefinition)})};if(n?.api!=null&&(n.api.type==="singleNamespace"&&n.api.definitions.length>0||n.api.type==="multiNamespace")){let u=[];if(n.api.type==="singleNamespace"){let l=await kKs({absolutePathToWorkspace:e,namespace:void 0,definitions:n.api.definitions});if(!Array.isArray(l))return l;u.push(...l)}else{for(let[l,f]of Object.entries(n.api.definitions)){let s=await kKs({absolutePathToWorkspace:e,namespace:l,definitions:f});if(!Array.isArray(s))return s;u.push(...s)}if(n.api.rootDefinitions!=null){let l=await kKs({absolutePathToWorkspace:e,namespace:void 0,definitions:n.api.rootDefinitions});if(!Array.isArray(l))return l;u.push(...l)}}return{didSucceed:!0,workspace:new nN({specs:u.filter(l=>l.type!=="openrpc"),allSpecs:u,workspaceName:i,absoluteFilePath:e,generatorsConfiguration:n,changelog:a,cliVersion:r})}}return await Cf(Lu(e,Xa.of(i5)))?{didSucceed:!0,workspace:new yZt({absoluteFilePath:e,generatorsConfiguration:n,workspaceName:i,changelog:a,context:t,cliVersion:r,loadAPIWorkspace:lba})}:{didSucceed:!1,failures:{[Xa.of(TZa)]:{type:pP.MISCONFIGURED_DIRECTORY}}}}var cQp=require("fs/promises");var eYs={};jo(eYs,{additionalProperties:()=>fVD,default:()=>pVD,definitions:()=>dVD,properties:()=>cVD,required:()=>lVD,type:()=>sVD});var sVD="object",cVD={instances:{type:"array",items:{$ref:"#/definitions/docs.DocsInstance"}},title:{oneOf:[{type:"string"},{type:"null"}]},analytics:{oneOf:[{$ref:"#/definitions/docs.AnalyticsConfig"},{type:"null"}]},announcement:{oneOf:[{$ref:"#/definitions/docs.AnnouncementConfig"},{type:"null"}]},roles:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.RoleId"}},{type:"null"}]},tabs:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/docs.TabConfig"}},{type:"null"}]},versions:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.VersionConfig"}},{type:"null"}]},"landing-page":{oneOf:[{$ref:"#/definitions/docs.PageConfiguration"},{type:"null"}]},navigation:{oneOf:[{$ref:"#/definitions/docs.NavigationConfig"},{type:"null"}]},"navbar-links":{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.NavbarLink"}},{type:"null"}]},"footer-links":{oneOf:[{$ref:"#/definitions/docs.FooterLinksConfig"},{type:"null"}]},experimental:{oneOf:[{$ref:"#/definitions/docs.ExperimentalConfig"},{type:"null"}]},"default-language":{oneOf:[{$ref:"#/definitions/docs.ProgrammingLanguage"},{type:"null"}]},"ai-chat":{oneOf:[{$ref:"#/definitions/docs.AIChatConfig"},{type:"null"}]},"ai-search":{oneOf:[{$ref:"#/definitions/docs.AIChatConfig"},{type:"null"}]},metadata:{oneOf:[{$ref:"#/definitions/docs.MetadataConfig"},{type:"null"}]},redirects:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.RedirectConfig"}},{type:"null"}]},logo:{oneOf:[{$ref:"#/definitions/docs.LogoConfiguration"},{type:"null"}]},favicon:{oneOf:[{type:"string"},{type:"null"}]},"background-image":{oneOf:[{$ref:"#/definitions/docs.BackgroundImageConfiguration"},{type:"null"}]},colors:{oneOf:[{$ref:"#/definitions/docs.ColorsConfiguration"},{type:"null"}]},typography:{oneOf:[{$ref:"#/definitions/docs.DocsTypographyConfig"},{type:"null"}]},layout:{oneOf:[{$ref:"#/definitions/docs.LayoutConfig"},{type:"null"}]},integrations:{oneOf:[{$ref:"#/definitions/docs.IntegrationsConfig"},{type:"null"}]},css:{oneOf:[{$ref:"#/definitions/docs.CssConfig"},{type:"null"}]},js:{oneOf:[{$ref:"#/definitions/docs.JsConfig"},{type:"null"}]}},lVD=["instances"],fVD=!1,dVD={"docs.CustomDomain":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"docs.GithubEditThisPageConfig":{type:"object",properties:{host:{oneOf:[{type:"string"},{type:"null"}]},owner:{type:"string"},repo:{type:"string"},branch:{oneOf:[{type:"string"},{type:"null"}]}},required:["owner","repo"],additionalProperties:!1},"docs.EditThisPageConfig":{type:"object",properties:{github:{oneOf:[{$ref:"#/definitions/docs.GithubEditThisPageConfig"},{type:"null"}]}},additionalProperties:!1},"docs.DocsInstance":{type:"object",properties:{url:{type:"string"},"custom-domain":{oneOf:[{$ref:"#/definitions/docs.CustomDomain"},{type:"null"}]},private:{oneOf:[{type:"boolean"},{type:"null"}]},"edit-this-page":{oneOf:[{$ref:"#/definitions/docs.EditThisPageConfig"},{type:"null"}]}},required:["url"],additionalProperties:!1},"docs.SegmentConfig":{type:"object",properties:{"write-key":{type:"string"}},required:["write-key"],additionalProperties:!1},"docs.FullStoryAnalyticsConfig":{type:"object",properties:{"org-id":{type:"string"}},required:["org-id"],additionalProperties:!1},"docs.IntercomConfig":{type:"object",properties:{"app-id":{type:"string"},"api-base":{oneOf:[{type:"string"},{type:"null"}]}},required:["app-id"],additionalProperties:!1},"docs.PostHogConfig":{type:"object",properties:{"api-key":{type:"string"},endpoint:{oneOf:[{type:"string"},{type:"null"}]}},required:["api-key"],additionalProperties:!1},"docs.GTMConfig":{type:"object",properties:{"container-id":{type:"string"}},required:["container-id"],additionalProperties:!1},"docs.GoogleAnalytics4Config":{type:"object",properties:{"measurement-id":{type:"string"}},required:["measurement-id"],additionalProperties:!1},"docs.AnalyticsConfig":{type:"object",properties:{segment:{oneOf:[{$ref:"#/definitions/docs.SegmentConfig"},{type:"null"}]},fullstory:{oneOf:[{$ref:"#/definitions/docs.FullStoryAnalyticsConfig"},{type:"null"}]},intercom:{oneOf:[{$ref:"#/definitions/docs.IntercomConfig"},{type:"null"}]},posthog:{oneOf:[{$ref:"#/definitions/docs.PostHogConfig"},{type:"null"}]},gtm:{oneOf:[{$ref:"#/definitions/docs.GTMConfig"},{type:"null"}]},ga4:{oneOf:[{$ref:"#/definitions/docs.GoogleAnalytics4Config"},{type:"null"}]}},additionalProperties:!1},"docs.AnnouncementConfig":{type:"object",properties:{message:{type:"string"}},required:["message"],additionalProperties:!1},"docs.RoleId":{type:"string"},"docs.Role":{anyOf:[{$ref:"#/definitions/docs.RoleId"},{type:"array",items:{$ref:"#/definitions/docs.RoleId"}}]},"docs.FeatureFlag":{type:"object",properties:{flag:{type:"string"},"fallback-value":{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},match:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]}},required:["flag"],additionalProperties:!1},"docs.FeatureFlagConfiguration":{anyOf:[{type:"string",description:"The name of the feature flag, We assume that it is a boolean feature flag that needs to be evaluated to true."},{$ref:"#/definitions/docs.FeatureFlag",description:"A single feature flag with a configurable name, fallback value, and match value. Especially useful for non boolean feature flags."},{type:"array",items:{$ref:"#/definitions/docs.FeatureFlag"},description:"A list of feature flags. If any of the feature flags are satisfied, we will show all content."}]},"docs.ChangelogFolderRelativePath":{type:"string"},"docs.TabConfig":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},"display-name":{type:"string"},icon:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},href:{oneOf:[{type:"string"},{type:"null"}]},changelog:{oneOf:[{$ref:"#/definitions/docs.ChangelogFolderRelativePath"},{type:"null"}]}},required:["display-name"],additionalProperties:!1},"docs.VersionAvailability":{type:"string",enum:["deprecated","ga","stable","beta"]},"docs.VersionConfig":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},"display-name":{type:"string"},path:{type:"string"},slug:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/docs.VersionAvailability"},{type:"null"}]}},required:["display-name","path"],additionalProperties:!1},"docs.PageConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},page:{type:"string"},path:{type:"string"},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},noindex:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["page","path"],additionalProperties:!1},"docs.SectionConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},section:{type:"string"},path:{oneOf:[{type:"string"},{type:"null"}]},contents:{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},collapsed:{oneOf:[{type:"boolean"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["section","contents"],additionalProperties:!1},"docs.AudienceId":{type:"string"},"docs.VersionedSnippetLanguageConfiguration":{type:"object",properties:{version:{type:"string"},package:{type:"string"}},required:["version","package"],additionalProperties:!1},"docs.SnippetLanguageConfiguration":{anyOf:[{type:"string"},{$ref:"#/definitions/docs.VersionedSnippetLanguageConfiguration"}]},"docs.SnippetsConfiguration":{type:"object",properties:{python:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},typescript:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},go:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},java:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},ruby:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},csharp:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]}},additionalProperties:!1},"docs.PlaygroundButtonSettings":{type:"object",properties:{href:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.PlaygroundSettings":{type:"object",properties:{environments:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},button:{oneOf:[{$ref:"#/definitions/docs.PlaygroundButtonSettings"},{type:"null"}]},oauth:{oneOf:[{type:"boolean"},{type:"null"}]},"limit-websocket-messages-per-connection":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"docs.ApiReferencePackageConfigurationWithOptions":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},title:{oneOf:[{type:"string"},{type:"null"}]},summary:{oneOf:[{type:"string"},{type:"null"}]},contents:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},additionalProperties:!1},"docs.ApiReferencePackageConfiguration":{anyOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{$ref:"#/definitions/docs.ApiReferencePackageConfigurationWithOptions"}]},"docs.ApiReferenceSectionConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},section:{type:"string"},"referenced-packages":{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},summary:{oneOf:[{type:"string"},{type:"null"}]},contents:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},required:["section"],additionalProperties:!1},"docs.ApiReferenceEndpointConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},endpoint:{type:"string"},title:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"docs.LinkConfiguration":{type:"object",properties:{link:{type:"string"},href:{type:"string"},icon:{oneOf:[{type:"string"},{type:"null"}]}},required:["link","href"],additionalProperties:!1},"docs.ApiReferenceLayoutItem":{anyOf:[{type:"string",description:"This should be either an endpoint, websocket, webhook, or subpackage ID"},{type:"object",additionalProperties:{$ref:"#/definitions/docs.ApiReferencePackageConfiguration"},description:"Keyed by subpackage name, this object allows you to group endpoints and pages together."},{$ref:"#/definitions/docs.ApiReferenceSectionConfiguration"},{$ref:"#/definitions/docs.ApiReferenceEndpointConfiguration"},{$ref:"#/definitions/docs.PageConfiguration"},{$ref:"#/definitions/docs.LinkConfiguration"}]},"docs.ApiReferenceConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},api:{type:"string"},"api-name":{oneOf:[{type:"string"},{type:"null"}]},openrpc:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.AudienceId"}},{type:"null"}]},"display-errors":{oneOf:[{type:"boolean"},{type:"null"}]},snippets:{oneOf:[{$ref:"#/definitions/docs.SnippetsConfiguration"},{type:"null"}]},summary:{oneOf:[{type:"string"},{type:"null"}]},layout:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},alphabetized:{oneOf:[{type:"boolean"},{type:"null"}]},flattened:{oneOf:[{type:"boolean"},{type:"null"}]},paginated:{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},required:["api"],additionalProperties:!1},"docs.ChangelogConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},changelog:{$ref:"#/definitions/docs.ChangelogFolderRelativePath"},title:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["changelog"],additionalProperties:!1},"docs.NavigationItem":{anyOf:[{$ref:"#/definitions/docs.PageConfiguration"},{$ref:"#/definitions/docs.SectionConfiguration"},{$ref:"#/definitions/docs.ApiReferenceConfiguration"},{$ref:"#/definitions/docs.LinkConfiguration"},{$ref:"#/definitions/docs.ChangelogConfiguration"}]},"docs.UntabbedNavigationConfig":{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},"docs.TabId":{type:"string"},"docs.TabbedNavigationItem":{type:"object",properties:{tab:{$ref:"#/definitions/docs.TabId"},layout:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},{type:"null"}]}},required:["tab"],additionalProperties:!1},"docs.TabbedNavigationConfig":{type:"array",items:{$ref:"#/definitions/docs.TabbedNavigationItem"}},"docs.NavigationConfig":{anyOf:[{$ref:"#/definitions/docs.UntabbedNavigationConfig"},{$ref:"#/definitions/docs.TabbedNavigationConfig"}]},"docs.NavbarGithubConfig":{type:"string"},"docs.NavbarLink":{type:"object",properties:{type:{type:"string",enum:["filled","outlined","minimal","github","primary","secondary"]}},required:["type"],oneOf:[{properties:{type:{const:"filled"},href:{oneOf:[{type:"string"},{type:"null"}]},url:{oneOf:[{type:"string"},{type:"null"}]},text:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},rightIcon:{oneOf:[{type:"string"},{type:"null"}]},rounded:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"]},{properties:{type:{const:"outlined"},href:{oneOf:[{type:"string"},{type:"null"}]},url:{oneOf:[{type:"string"},{type:"null"}]},text:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},rightIcon:{oneOf:[{type:"string"},{type:"null"}]},rounded:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"]},{properties:{type:{const:"minimal"},href:{oneOf:[{type:"string"},{type:"null"}]},url:{oneOf:[{type:"string"},{type:"null"}]},text:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},rightIcon:{oneOf:[{type:"string"},{type:"null"}]},rounded:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"]},{properties:{type:{const:"github"},value:{$ref:"#/definitions/docs.NavbarGithubConfig"}},required:["type"]},{properties:{type:{const:"primary"},href:{oneOf:[{type:"string"},{type:"null"}]},url:{oneOf:[{type:"string"},{type:"null"}]},text:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},rightIcon:{oneOf:[{type:"string"},{type:"null"}]},rounded:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"]},{properties:{type:{const:"secondary"},href:{oneOf:[{type:"string"},{type:"null"}]},url:{oneOf:[{type:"string"},{type:"null"}]},text:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},rightIcon:{oneOf:[{type:"string"},{type:"null"}]},rounded:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"]}]},"docs.FooterLinksConfig":{type:"object",properties:{github:{oneOf:[{type:"string"},{type:"null"}]},twitter:{oneOf:[{type:"string"},{type:"null"}]},x:{oneOf:[{type:"string"},{type:"null"}]},linkedin:{oneOf:[{type:"string"},{type:"null"}]},youtube:{oneOf:[{type:"string"},{type:"null"}]},instagram:{oneOf:[{type:"string"},{type:"null"}]},facebook:{oneOf:[{type:"string"},{type:"null"}]},discord:{oneOf:[{type:"string"},{type:"null"}]},slack:{oneOf:[{type:"string"},{type:"null"}]},hackernews:{oneOf:[{type:"string"},{type:"null"}]},medium:{oneOf:[{type:"string"},{type:"null"}]},website:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.ExperimentalConfig":{type:"object",properties:{"mdx-components":{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"disable-stream-toggle":{oneOf:[{type:"boolean"},{type:"null"}]},"openapi-parser-v2":{oneOf:[{type:"boolean"},{type:"null"}]},"openapi-parser-v3":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"docs.ProgrammingLanguage":{type:"string",enum:["typescript","javascript","python","java","go","ruby","csharp","nodets","nodejs","dotnet","curl","jvm","ts","js"]},"docs.AIChatModel":{type:"string",enum:["claude-3.5","claude-3.7","command-a"]},"docs.AIChatConfig":{type:"object",properties:{model:{oneOf:[{$ref:"#/definitions/docs.AIChatModel"},{type:"null"}]},"system-prompt":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.TwitterCardSetting":{type:"string",enum:["summary","summary_large_image","app","player"]},"docs.MetadataConfig":{type:"object",properties:{"og:site_name":{oneOf:[{type:"string"},{type:"null"}]},"og:title":{oneOf:[{type:"string"},{type:"null"}]},"og:description":{oneOf:[{type:"string"},{type:"null"}]},"og:url":{oneOf:[{type:"string"},{type:"null"}]},"og:image":{oneOf:[{type:"string"},{type:"null"}]},"og:image:width":{oneOf:[{type:"number"},{type:"null"}]},"og:image:height":{oneOf:[{type:"number"},{type:"null"}]},"og:locale":{oneOf:[{type:"string"},{type:"null"}]},"og:logo":{oneOf:[{type:"string"},{type:"null"}]},"twitter:title":{oneOf:[{type:"string"},{type:"null"}]},"twitter:description":{oneOf:[{type:"string"},{type:"null"}]},"twitter:handle":{oneOf:[{type:"string"},{type:"null"}]},"twitter:image":{oneOf:[{type:"string"},{type:"null"}]},"twitter:site":{oneOf:[{type:"string"},{type:"null"}]},"twitter:url":{oneOf:[{type:"string"},{type:"null"}]},"twitter:card":{oneOf:[{$ref:"#/definitions/docs.TwitterCardSetting"},{type:"null"}]}},additionalProperties:!1},"docs.RedirectConfig":{type:"object",properties:{source:{type:"string"},destination:{type:"string"},permanent:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["source","destination"],additionalProperties:!1},"docs.LogoConfiguration":{type:"object",properties:{dark:{oneOf:[{type:"string"},{type:"null"}]},light:{oneOf:[{type:"string"},{type:"null"}]},height:{oneOf:[{type:"number"},{type:"null"}]},href:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.BackgroundImageThemedConfig":{type:"object",properties:{dark:{oneOf:[{type:"string"},{type:"null"}]},light:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.BackgroundImageConfiguration":{anyOf:[{type:"string"},{$ref:"#/definitions/docs.BackgroundImageThemedConfig"}]},"docs.ColorThemedConfig":{type:"object",properties:{dark:{oneOf:[{type:"string"},{type:"null"}]},light:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.ColorConfig":{anyOf:[{type:"string"},{$ref:"#/definitions/docs.ColorThemedConfig"}]},"docs.ColorsConfiguration":{type:"object",properties:{"accent-primary":{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]},accentPrimary:{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]},background:{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]},border:{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]},"sidebar-background":{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]},"header-background":{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]},"card-background":{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]}},additionalProperties:!1},"docs.FontWeight":{anyOf:[{type:"string"},{type:"integer"}]},"docs.FontStyle":{type:"string",enum:["normal","italic"]},"docs.FontConfigVariant":{type:"object",properties:{path:{type:"string"},weight:{oneOf:[{$ref:"#/definitions/docs.FontWeight"},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/docs.FontStyle"},{type:"null"}]}},required:["path"],additionalProperties:!1},"docs.FontConfigPath":{anyOf:[{type:"string"},{$ref:"#/definitions/docs.FontConfigVariant"}]},"docs.FontDisplay":{type:"string",enum:["auto","block","swap","fallback","optional"]},"docs.FontConfig":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},path:{oneOf:[{type:"string"},{type:"null"}]},weight:{oneOf:[{$ref:"#/definitions/docs.FontWeight"},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/docs.FontStyle"},{type:"null"}]},paths:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.FontConfigPath"}},{type:"null"}]},display:{oneOf:[{$ref:"#/definitions/docs.FontDisplay"},{type:"null"}]},fallback:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"font-variation-settings":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.DocsTypographyConfig":{type:"object",properties:{headingsFont:{oneOf:[{$ref:"#/definitions/docs.FontConfig"},{type:"null"}]},bodyFont:{oneOf:[{$ref:"#/definitions/docs.FontConfig"},{type:"null"}]},codeFont:{oneOf:[{$ref:"#/definitions/docs.FontConfig"},{type:"null"}]}},additionalProperties:!1},"docs.SearchbarPlacement":{type:"string",enum:["header","header-tabs","sidebar"]},"docs.TabsPlacement":{type:"string",enum:["header","sidebar"]},"docs.ContentAlignment":{type:"string",enum:["center","left"]},"docs.HeaderPosition":{type:"string",enum:["fixed","static"]},"docs.LayoutConfig":{type:"object",properties:{"page-width":{oneOf:[{type:"string"},{type:"null"}]},"content-width":{oneOf:[{type:"string"},{type:"null"}]},"sidebar-width":{oneOf:[{type:"string"},{type:"null"}]},"header-height":{oneOf:[{type:"string"},{type:"null"}]},"searchbar-placement":{oneOf:[{$ref:"#/definitions/docs.SearchbarPlacement"},{type:"null"}]},"tabs-placement":{oneOf:[{$ref:"#/definitions/docs.TabsPlacement"},{type:"null"}]},"content-alignment":{oneOf:[{$ref:"#/definitions/docs.ContentAlignment"},{type:"null"}]},"header-position":{oneOf:[{$ref:"#/definitions/docs.HeaderPosition"},{type:"null"}]},"disable-header":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"docs.IntegrationsConfig":{type:"object",properties:{intercom:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.CssConfig":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"docs.JsScriptStrategy":{type:"string",enum:["beforeInteractive","afterInteractive","lazyOnload"]},"docs.JsRemoteConfig":{type:"object",properties:{url:{type:"string"},strategy:{oneOf:[{$ref:"#/definitions/docs.JsScriptStrategy"},{type:"null"}]}},required:["url"],additionalProperties:!1},"docs.JsFileConfigSettings":{type:"object",properties:{path:{type:"string"},strategy:{oneOf:[{$ref:"#/definitions/docs.JsScriptStrategy"},{type:"null"}]}},required:["path"],additionalProperties:!1},"docs.JsFileConfig":{anyOf:[{type:"string"},{$ref:"#/definitions/docs.JsFileConfigSettings"}]},"docs.JsConfigOptions":{anyOf:[{$ref:"#/definitions/docs.JsRemoteConfig"},{$ref:"#/definitions/docs.JsFileConfig"}]},"docs.JsConfig":{anyOf:[{$ref:"#/definitions/docs.JsConfigOptions"},{type:"array",items:{$ref:"#/definitions/docs.JsConfigOptions"}}]}},pVD={type:sVD,properties:cVD,required:lVD,additionalProperties:fVD,definitions:dVD};async function tYs({fernDirectory:e,context:t}){let r=Lu(e,Xa.of(a8t));if(!await Cf(r))return;let i=await _VD({absolutePathToDocsDefinition:e,context:t});if(i!=null)return{type:"docs",absoluteFilePath:e,config:i,workspaceName:void 0,absoluteFilepathToDocsConfig:Lu(e,Xa.of(a8t))}}async function _VD({absolutePathToDocsDefinition:e,context:t}){if(!await Cf(e))return;let r=Lu(e,Xa.of(a8t));return await hVD({absolutePathOfConfiguration:r,context:t})}async function hVD({absolutePathOfConfiguration:e,context:t}){let r=await(0,cQp.readFile)(e),i=Gd.load(r.toString()),n=yQr(i,eYs);if(n.success)return s8t.RawSchemas.Serializer.DocsConfiguration.parseOrThrow(i);throw new Error(`Failed to parse docs.yml because of ${n.error?.message??"Unknown error"}`)}async function rYs({context:e,nameOverride:t,...r}){let i=await b8t(t);return i==null?e.failAndThrow(`Directory "${t??UU}" not found.`):await fQp({absolutePathToFernDirectory:i,context:e,nameOverride:t,...r})}async function fQp({absolutePathToFernDirectory:e,cliName:t,cliVersion:r,commandLineApiWorkspace:i,defaultToAllApiWorkspaces:n,context:a}){let u=[];return(await Cf(Lu(e,Xa.of($ui)))||await Cf(Lu(e,Xa.of(i5)))||await Cf(Lu(e,Xa.of(ZN)))||await Cf(Lu(e,Xa.of(TZa)))||await Cf(Lu(e,Xa.of(EWf))))&&(u=await dQp({cliName:t,fernDirectory:e,cliVersion:r,context:a,commandLineApiWorkspace:i,defaultToAllApiWorkspaces:n})),{config:await UQr({directory:e,context:a}),apiWorkspaces:u,docsWorkspaces:await tYs({fernDirectory:e,context:a}),loadAPIWorkspace:l=>l==null?u[0]:u.find(f=>f.workspaceName===l)}}async function dQp({cliName:e,fernDirectory:t,context:r,cliVersion:i,commandLineApiWorkspace:n,defaultToAllApiWorkspaces:a}){let u=Lu(t,Xa.of($ui));if(await Cf(u)){let o=(await(0,lQp.readdir)(u,{withFileTypes:!0})).reduce((g,O)=>(O.isDirectory()&&g.push(O.name),g),[]);if(n!=null){if(!o.includes(n))return r.failAndThrow("API does not exist: "+n)}else{if(o.length===0)return r.failAndThrow("No APIs found.");if(o.length>1&&!a){let g=`There are multiple workspaces. You must specify one with --api:
|
|
1960
1960
|
`,O=Math.max(...o.map(m=>m.length));return g+=o.map(m=>{let P=`${e} ${process.argv.slice(2).join(" ")} --api ${m}`;return` \u203A ${Ws.bold(m.padEnd(O))} ${Ws.dim(P)}`}).join(`
|
|
@@ -2028,7 +2028,7 @@ ${fe.stack}`)),D}};D=await x();let L=A.apiWorkspaces.flatMap(K=>K.getAbsoluteFil
|
|
|
2028
2028
|
`},n)),a}var uv_=require("fs");var EsE=["mdxFlowExpression","mdxJsxFlowElement","mdxJsxTextElement","mdxTextExpression","mdxjsEsm"];function MsE({readFile:e=r=>(0,uv_.readFileSync)(r,"utf-8"),...t}){let r=new Set,i=[t],n=[],a=[],u=1e3,l=0;do{if(l++,l>u)throw new Error("Infinite loop detected while collecting links and sources");let f=i.shift();if(f==null)break;let{content:s,absoluteFilepath:o}=f;if(o!=null){if(r.has(o))throw new Error(`Circular import detected: ${o}`);r.add(o)}let c=yMn(s),b=fnc(c,{allowDangerousHtml:!0,passThrough:[...EsE]});xf(b,g=>{if(g.type==="mdxjsEsm"&&o!=null)return g.data?.estree&&AZt(g.data.estree,{enter:m=>{if(m.type==="ImportDeclaration"&&m.source.type==="Literal"&&typeof m.source.value=="string"){let P=Xa.of(m.source.value),E=Vg(Zd(o),P);(E.endsWith(".mdx")||E.endsWith(".md"))&&i.push({content:e(E),absoluteFilepath:E})}}}),"skip";if(g.type==="element"){let m=g.properties.href;typeof m=="string"&&n.push({href:m,sourceFilepath:o,position:g.position});let P=g.properties.src;typeof P=="string"&&a.push({src:P,sourceFilepath:o,position:g.position})}function O(m,P){vMn(m,{src:E=>{let q=PYr(E.value);typeof q=="string"&&a.push({src:q,sourceFilepath:o,position:P})},href:E=>{let q=PYr(E.value);typeof q=="string"&&n.push({href:q,sourceFilepath:o,position:P})}})}if(g.type==="mdxJsxFlowElement"||g.type==="mdxJsxTextElement"){let m=E_i(g.attributes.filter(jYr).find(E=>E.name==="href")?.value),P=E_i(g.attributes.filter(jYr).find(E=>E.name==="src")?.value);if(g.name==="Markdown"){if(o&&typeof P=="string"){let E=Vg(Zd(o),P);i.push({content:e(E),absoluteFilepath:E})}return"skip"}typeof m=="string"&&n.push({href:m,sourceFilepath:o,position:g.position}),typeof P=="string"&&a.push({src:P,sourceFilepath:o,position:g.position}),g.attributes.forEach(E=>{E.type==="mdxJsxAttribute"&&typeof E.value!="string"&&E.value!=null&&E.value.data?.estree?O(E.value.data.estree,E.position):E.type==="mdxJsxExpressionAttribute"&&E.data?.estree&&O(E.data.estree,E.position)})}(g.type==="mdxFlowExpression"||g.type==="mdxTextExpression")&&g.data?.estree&&O(g.data.estree,g.position)})}while(i.length>0);return{links:n,sources:a}}function sv_({content:e,absoluteFilepath:t}){try{return MsE({content:e,absoluteFilepath:t})}catch{return{links:[],sources:[]}}}function cv_({relativeFilepath:e,allRuleVisitors:t,addViolations:r}){function i(n){let a=async(u,l)=>{for(let f of t){let s=f[n];if(s!=null){let o=await s(u);r(o.map(c=>({name:c.name,severity:c.severity,relativeFilepath:c.relativeFilepath??Xa.of(""),nodePath:l,message:c.message})))}}};return{[n]:a}}return{...i("file"),...i("filepath"),...i("markdownPage"),...i("versionFile"),...i("apiSection"),...i("permissions")}}var dv_=require("fs/promises");async function XV({absoluteFilepathToConfiguration:e,rawUnresolvedFilepath:t,visitor:r,nodePath:i,willBeUploaded:n=!0}){let a=Vg(Zd(e),t);await r.filepath?.({absoluteFilepath:a,value:t,willBeUploaded:n},[a])}var lv_=require("fs/promises");async function pnc({absolutePathToFernFolder:e,navigation:t,apiWorkspaces:r,visitor:i,absoluteFilepathToConfiguration:n,context:a,nodePath:u}){TsE(t)?await Promise.all(t.map(async(l,f)=>{l.layout!=null&&await Promise.all(l.layout.map(async(s,o)=>{await dnc({absolutePathToFernFolder:e,navigationItem:s,visitor:i,nodePath:[...u,`${f}`,"layout",`${o}`],absoluteFilepathToConfiguration:n,apiWorkspaces:r,context:a})}))})):await Promise.all(t.map(async(l,f)=>{await dnc({absolutePathToFernFolder:e,navigationItem:l,visitor:i,nodePath:[...u,`${f}`],absoluteFilepathToConfiguration:n,apiWorkspaces:r,context:a})}))}async function dnc({absolutePathToFernFolder:e,navigationItem:t,visitor:r,nodePath:i,absoluteFilepathToConfiguration:n,apiWorkspaces:a,context:u}){if(await uGt(t,{alphabetized:Go,api:Go,apiName:Go,audiences:Go,openrpc:async l=>{l!=null&&await XV({absoluteFilepathToConfiguration:n,rawUnresolvedFilepath:l,visitor:r,nodePath:[...i,"openrpc"],willBeUploaded:!1})},displayErrors:Go,snippets:Go,summary:Go,title:Go,layout:Go,icon:Go,slug:Go,hidden:Go,skipSlug:Go,paginated:Go,playground:Go,flattened:Go,featureFlag:Go,path:async l=>{l!=null&&await XV({absoluteFilepathToConfiguration:n,rawUnresolvedFilepath:l,visitor:r,nodePath:[...i,"path"],willBeUploaded:!1})},page:Go,contents:async l=>{l!=null&&await Promise.all(l.map(async(f,s)=>{await dnc({absolutePathToFernFolder:e,navigationItem:f,visitor:r,nodePath:[...i,"contents",`${s}`],absoluteFilepathToConfiguration:n,apiWorkspaces:a,context:u})}))},viewers:async l=>{l!=null&&l.length>0&&await r.permissions?.({viewers:l},[...i,"viewers"])},orphaned:Go}),AsE(t)){let l=Vg(Zd(n),t.path);if(await Cf(l)){let f=(await(0,lv_.readFile)(l)).toString();await r.markdownPage?.({title:t.page,content:f,absoluteFilepath:l},[...i,t.path]);try{let{filepaths:s}=$ba(f,{absolutePathToFernFolder:e,absolutePathToMarkdownFile:l});for(let o of s)await r.filepath?.({absoluteFilepath:o,value:KA(e,o),willBeUploaded:!0},[...i,t.path])}catch{}}}if(qsE(t)){let l=a.find(f=>f.workspaceName===t.apiName);l!=null&&await r.apiSection?.({config:t,workspace:l,context:u},[...i,"api"])}}function AsE(e){return e.page!=null}function qsE(e){return e.api!=null}function TsE(e){return e[0]?.tab!=null}async function pv_({contents:e,visitor:t,absoluteFilepathToConfiguration:r,context:i,apiWorkspaces:n,absolutePathToFernFolder:a}){await t.file?.({config:e},[]),await uGt(e,{instances:Go,analytics:Go,aiChat:Go,aiSearch:Go,announcement:Go,backgroundImage:async u=>{u!=null&&(typeof u=="string"?await XV({absoluteFilepathToConfiguration:r,rawUnresolvedFilepath:u,visitor:t,nodePath:["background-image"]}):(u.dark!=null&&await XV({absoluteFilepathToConfiguration:r,rawUnresolvedFilepath:u.dark,visitor:t,nodePath:["background-image","dark"]}),u.light!=null&&await XV({absoluteFilepathToConfiguration:r,rawUnresolvedFilepath:u.light,visitor:t,nodePath:["background-image","light"]})))},colors:Go,css:async u=>{u!=null&&(Array.isArray(u)?await Promise.all(u.map((l,f)=>XV({absoluteFilepathToConfiguration:r,rawUnresolvedFilepath:l,visitor:t,nodePath:["css",`${f}`],willBeUploaded:!1}))):await XV({absoluteFilepathToConfiguration:r,rawUnresolvedFilepath:u,visitor:t,nodePath:["css"],willBeUploaded:!1}))},defaultLanguage:Go,experimental:Go,favicon:async u=>{u!=null&&await XV({absoluteFilepathToConfiguration:r,rawUnresolvedFilepath:u,visitor:t,nodePath:["favicon"]})},footerLinks:Go,integrations:Go,js:async u=>{u!=null&&(Array.isArray(u)?await Promise.all(u.map((l,f)=>fv_({absoluteFilepathToConfiguration:r,visitor:t,script:l,nodePath:["js",`${f}`]}))):await fv_({absoluteFilepathToConfiguration:r,visitor:t,script:u,nodePath:["js"]}))},landingPage:Go,layout:Go,logo:async u=>{e.logo?.dark!=null&&await XV({absoluteFilepathToConfiguration:r,rawUnresolvedFilepath:e.logo.dark,visitor:t,nodePath:["logo","dark"]}),e.logo?.light!=null&&await XV({absoluteFilepathToConfiguration:r,rawUnresolvedFilepath:e.logo.light,visitor:t,nodePath:["logo","light"]})},metadata:Go,navbarLinks:Go,navigation:async u=>{u!=null&&await pnc({absolutePathToFernFolder:a,navigation:u,visitor:t,nodePath:["navigation"],absoluteFilepathToConfiguration:r,apiWorkspaces:n,context:i})},redirects:Go,tabs:Go,title:Go,typography:async u=>{u!=null&&await uGt(u,{bodyFont:async l=>{l!=null&&await _nc({absoluteFilepathToConfiguration:r,visitor:t,font:l,nodePath:["typography","bodyFont"]})},codeFont:async l=>{l!=null&&await _nc({absoluteFilepathToConfiguration:r,visitor:t,font:l,nodePath:["typography","codeFont"]})},headingsFont:async l=>{l!=null&&await _nc({absoluteFilepathToConfiguration:r,visitor:t,font:l,nodePath:["typography","headingsFont"]})}})},versions:async u=>{u!=null&&await Promise.all(u.map(async(l,f)=>{await XV({absoluteFilepathToConfiguration:r,rawUnresolvedFilepath:l.path,visitor:t,nodePath:["versions",`${f}`],willBeUploaded:!1});let s=Vg(Zd(r),l.path),o=Gd.load((await(0,dv_.readFile)(s)).toString());await Cf(s)&&await t.versionFile?.({path:l.path,content:o},[l.path]);let c=await C2o({value:o});c.type==="success"&&await pnc({absolutePathToFernFolder:a,navigation:c.contents.navigation,visitor:t,nodePath:["navigation"],absoluteFilepathToConfiguration:s,apiWorkspaces:n,context:i})}))},roles:Go})}async function _nc({absoluteFilepathToConfiguration:e,visitor:t,font:r,nodePath:i}){r.path!=null&&await XV({absoluteFilepathToConfiguration:e,rawUnresolvedFilepath:r.path,visitor:t,nodePath:i,willBeUploaded:!0});for(let n of r.paths??[])typeof n=="string"?await XV({absoluteFilepathToConfiguration:e,rawUnresolvedFilepath:n,visitor:t,nodePath:i,willBeUploaded:!0}):await XV({absoluteFilepathToConfiguration:e,rawUnresolvedFilepath:n.path,visitor:t,nodePath:i,willBeUploaded:!0})}async function fv_({absoluteFilepathToConfiguration:e,visitor:t,script:r,nodePath:i}){let n=typeof r=="string"?r:"path"in r?r.path:null;n&&await XV({absoluteFilepathToConfiguration:e,rawUnresolvedFilepath:n,visitor:t,nodePath:i,willBeUploaded:!0})}var _v_={name:"accent-color-contrast",create:()=>({file:async({config:e})=>{if(e.colors==null)return[];let t=bro(e.colors);return t==="dark"?I2o(e.colors,"dark"):t==="light"?I2o(e.colors,"light"):t==="darkAndLight"?[...I2o(e.colors,"dark"),...I2o(e.colors,"light")]:[]}})};function I2o(e,t){let r=$aa(e.accentPrimary??e.accentPrimaryDeprecated,"accent-primary",t),i=$aa(e.background,"background",t)??(t==="dark"?"#000":"#FFF"),n=[];if(!o_(i).isValid())n.push({severity:"fatal",message:`Invalid background color provided for colors.background.${t}: ${i}.`});else{let a=CsE(o_(i),t);o_(i).toHexString()!==a.toHexString()&&n.push({severity:"warning",message:`The provided background color for ${t} mode is not ${t} enough. It will be adjusted to ${a.toHexString()}.`}),i=a.toHexString()}if(r==null)n.push({severity:"warning",message:`No accent-color provided for ${t} mode. A random color will be used.`});else if(!o_(r).isValid())n.push({severity:"fatal",message:`Invalid accent-color provided for colors.accent-primary.${t}: ${r}.`});else{let a=o_.readability(r,i),u=`${a.toFixed(2)}:1`;a<3?n.push({severity:"warning",message:`The contrast ratio between the accent color and the background color for ${t} mode is ${u}. It should be at least 3:1.`}):a<4.5?n.push({severity:"warning",message:`The contrast ratio between the accent color and the background color for ${t} mode is ${u}. Fern will adjust the color to meet the minimum contrast ratio of 4.5:1 for WCAG AA and 7:1 for WCAG AAA.`}):a<7&&n.push({severity:"warning",message:`The contrast ratio between the accent color and the background color for ${t} mode is ${u}. Fern will adjust the color to meet the minimum contrast ratio of 7:1 for WCAG AAA.`})}return n}function CsE(e,t){return t==="dark"&&e.isDark()||t==="light"&&e.isLight()?e:BsE(e)}function BsE(e){if(e==null)return;let{h:t,s:r,v:i}=e.toHsv();return o_({h:t,s:r,v:1-i})}var hv_={name:"all-roles-must-be-declared",create:e=>{let t=e.workspace.config.roles;return{permissions:r=>{let i=[...r.viewers??[]],n=[];for(let a of i)(t==null||!t.includes(a))&&n.push({severity:"fatal",message:`Role "${a}" is used but not declared at the top level of the docs.yml file.`});return n}}}};var hnc={name:"filepaths-exist",create:()=>({filepath:async({absoluteFilepath:e,value:t})=>await Cf(e)?[]:[{severity:"fatal",message:`Path ${t} does not exist`}]})};var ync={name:"only-versioned-navigation",create:()=>({file:async({config:e})=>e.navigation!=null&&e.versions!=null?[{severity:"fatal",message:"Cannot contain both navigation and versions. If you want versioned docs, use versions. Otherwise use navigation."}]:[]})};var vnc={name:"valid-docs-endpoints",create:()=>({file:async({config:e})=>!e.analytics||!Object.keys(e.analytics).length?[]:[[e.analytics.intercom?.apiBase,"Intercom API Base"],[e.analytics.posthog?.endpoint,"Posthog Host Endpoint"]].filter(([i])=>i&&!xsE(i)).map(([i,n])=>({severity:"warning",message:`${n} <${i}> is malformed. Make sure it includes a protocol (e.g. 'https://')!`}))})};function xsE(e){try{return!!new URL(e).protocol}catch{return!1}}var Gv_=li(Mv_(),1);var ncE="End-Of-Stream",qz=class extends Error{constructor(){super(ncE)}};var V2o=class{constructor(){this.resolve=()=>null,this.reject=()=>null,this.promise=new Promise((t,r)=>{this.reject=r,this.resolve=t})}};var acE=1*1024*1024,jga=class{constructor(t){if(this.s=t,this.deferred=null,this.endOfStream=!1,this.peekQueue=[],!t.read||!t.once)throw new Error("Expected an instance of stream.Readable");this.s.once("end",()=>this.reject(new qz)),this.s.once("error",r=>this.reject(r)),this.s.once("close",()=>this.reject(new Error("Stream closed")))}async peek(t,r,i){let n=await this.read(t,r,i);return this.peekQueue.push(t.subarray(r,r+n)),n}async read(t,r,i){if(i===0)return 0;if(this.peekQueue.length===0&&this.endOfStream)throw new qz;let n=i,a=0;for(;this.peekQueue.length>0&&n>0;){let u=this.peekQueue.pop();if(!u)throw new Error("peekData should be defined");let l=Math.min(u.length,n);t.set(u.subarray(0,l),r+a),a+=l,n-=l,l<u.length&&this.peekQueue.push(u.subarray(l))}for(;n>0&&!this.endOfStream;){let u=Math.min(n,acE),l=await this.readFromStream(t,r+a,u);if(a+=l,l<u)break;n-=l}return a}async readFromStream(t,r,i){let n=this.s.read(i);if(n)return t.set(n,r),n.length;{let a={buffer:t,offset:r,length:i,deferred:new V2o};return this.deferred=a.deferred,this.s.once("readable",()=>{this.readDeferred(a)}),a.deferred.promise}}readDeferred(t){let r=this.s.read(t.length);r?(t.buffer.set(r,t.offset),t.deferred.resolve(r.length),this.deferred=null):this.s.once("readable",()=>{this.readDeferred(t)})}reject(t){this.endOfStream=!0,this.deferred&&(this.deferred.reject(t),this.deferred=null)}};var Knc=require("buffer"),bAn=class{constructor(t){this.position=0,this.numBuffer=new Uint8Array(8),this.fileInfo=t||{}}async readToken(t,r=this.position){let i=Knc.Buffer.alloc(t.len);if(await this.readBuffer(i,{position:r})<t.len)throw new qz;return t.get(i,0)}async peekToken(t,r=this.position){let i=Knc.Buffer.alloc(t.len);if(await this.peekBuffer(i,{position:r})<t.len)throw new qz;return t.get(i,0)}async readNumber(t){if(await this.readBuffer(this.numBuffer,{length:t.len})<t.len)throw new qz;return t.get(this.numBuffer,0)}async peekNumber(t){if(await this.peekBuffer(this.numBuffer,{length:t.len})<t.len)throw new qz;return t.get(this.numBuffer,0)}async ignore(t){if(this.fileInfo.size!==void 0){let r=this.fileInfo.size-this.position;if(t>r)return this.position+=r,r}return this.position+=t,t}async close(){}normalizeOptions(t,r){if(r&&r.position!==void 0&&r.position<this.position)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");return r?{mayBeLess:r.mayBeLess===!0,offset:r.offset?r.offset:0,length:r.length?r.length:t.length-(r.offset?r.offset:0),position:r.position?r.position:this.position}:{mayBeLess:!1,offset:0,length:t.length,position:this.position}}};var ocE=256e3,W2o=class extends bAn{constructor(t,r){super(r),this.streamReader=new jga(t)}async getFileInfo(){return this.fileInfo}async readBuffer(t,r){let i=this.normalizeOptions(t,r),n=i.position-this.position;if(n>0)return await this.ignore(n),this.readBuffer(t,r);if(n<0)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");if(i.length===0)return 0;let a=await this.streamReader.read(t,i.offset,i.length);if(this.position+=a,(!r||!r.mayBeLess)&&a<i.length)throw new qz;return a}async peekBuffer(t,r){let i=this.normalizeOptions(t,r),n=0;if(i.position){let a=i.position-this.position;if(a>0){let u=new Uint8Array(i.length+a);return n=await this.peekBuffer(u,{mayBeLess:i.mayBeLess}),t.set(u.subarray(a),i.offset),n-a}else if(a<0)throw new Error("Cannot peek from a negative offset in a stream")}if(i.length>0){try{n=await this.streamReader.peek(t,i.offset,i.length)}catch(a){if(r&&r.mayBeLess&&a instanceof qz)return 0;throw a}if(!i.mayBeLess&&n<i.length)throw new qz}return n}async ignore(t){let r=Math.min(ocE,t),i=new Uint8Array(r),n=0;for(;n<t;){let a=t-n,u=await this.readBuffer(i,{length:Math.min(r,a)});if(u<0)return u;n+=u}return n}};var H2o=class extends bAn{constructor(t,r){super(r),this.uint8Array=t,this.fileInfo.size=this.fileInfo.size?this.fileInfo.size:t.length}async readBuffer(t,r){if(r&&r.position){if(r.position<this.position)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");this.position=r.position}let i=await this.peekBuffer(t,r);return this.position+=i,i}async peekBuffer(t,r){let i=this.normalizeOptions(t,r),n=Math.min(this.uint8Array.length-i.position,i.length);if(!i.mayBeLess&&n<i.length)throw new qz;return t.set(this.uint8Array.subarray(i.position,i.position+n),i.offset),n}async close(){}};function Av_(e,t){return t=t||{},new W2o(e,t)}function qv_(e,t){return new H2o(e,t)}var XYr=require("buffer");var Cv_=li(Tv_(),1),Bv_=require("buffer");function wne(e){return new DataView(e.buffer,e.byteOffset)}var xv_={len:1,get(e,t){return wne(e).getUint8(t)},put(e,t,r){return wne(e).setUint8(t,r),t+1}},$2o={len:2,get(e,t){return wne(e).getUint16(t,!0)},put(e,t,r){return wne(e).setUint16(t,r,!0),t+2}},G2o={len:2,get(e,t){return wne(e).getUint16(t)},put(e,t,r){return wne(e).setUint16(t,r),t+2}};var Iv_={len:4,get(e,t){return wne(e).getUint32(t,!0)},put(e,t,r){return wne(e).setUint32(t,r,!0),t+4}},zv_={len:4,get(e,t){return wne(e).getUint32(t)},put(e,t,r){return wne(e).setUint32(t,r),t+4}};var Rv_={len:4,get(e,t){return wne(e).getInt32(t)},put(e,t,r){return wne(e).setInt32(t,r),t+4}};var Nv_={len:8,get(e,t){return wne(e).getBigUint64(t,!0)},put(e,t,r){return wne(e).setBigUint64(t,r,!0),t+8}};var YYr=class{constructor(t,r){this.len=t,this.encoding=r}get(t,r){return Bv_.Buffer.from(t).toString(this.encoding,r,r+this.len)}},Xnc=class e{constructor(t){this.len=t}static decode(t,r,i){let n="";for(let a=r;a<i;++a)n+=e.codePointToString(e.singleByteDecoder(t[a]));return n}static inRange(t,r,i){return r<=t&&t<=i}static codePointToString(t){return t<=65535?String.fromCharCode(t):(t-=65536,String.fromCharCode((t>>10)+55296,(t&1023)+56320))}static singleByteDecoder(t){if(e.inRange(t,0,127))return t;let r=e.windows1252[t-128];if(r===null)throw Error("invaliding encoding");return r}get(t,r=0){return e.decode(t,r,r+this.len)}};Xnc.windows1252=[8364,129,8218,402,8222,8230,8224,8225,710,8240,352,8249,338,141,381,143,144,8216,8217,8220,8221,8226,8211,8212,732,8482,353,8250,339,157,382,376,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255];function Fv_(e){return[...e].map(t=>t.charCodeAt(0))}function Lv_(e,t=0){let r=Number.parseInt(e.toString("utf8",148,154).replace(/\0.*$/,"").trim(),8);if(Number.isNaN(r))return!1;let i=8*32;for(let n=t;n<t+148;n++)i+=e[n];for(let n=t+156;n<t+512;n++)i+=e[n];return r===i}var Uv_={get:(e,t)=>e[t+3]&127|e[t+2]<<7|e[t+1]<<14|e[t]<<21,len:4};var Vv_=["jpg","png","apng","gif","webp","flif","xcf","cr2","cr3","orf","arw","dng","nef","rw2","raf","tif","bmp","icns","jxr","psd","indd","zip","tar","rar","gz","bz2","7z","dmg","mp4","mid","mkv","webm","mov","avi","mpg","mp2","mp3","m4a","oga","ogg","ogv","opus","flac","wav","spx","amr","pdf","epub","elf","macho","exe","swf","rtf","wasm","woff","woff2","eot","ttf","otf","ico","flv","ps","xz","sqlite","nes","crx","xpi","cab","deb","ar","rpm","Z","lz","cfb","mxf","mts","blend","bpg","docx","pptx","xlsx","3gp","3g2","j2c","jp2","jpm","jpx","mj2","aif","qcp","odt","ods","odp","xml","mobi","heic","cur","ktx","ape","wv","dcm","ics","glb","pcap","dsf","lnk","alias","voc","ac3","m4v","m4p","m4b","f4v","f4p","f4b","f4a","mie","asf","ogm","ogx","mpc","arrow","shp","aac","mp1","it","s3m","xm","ai","skp","avif","eps","lzh","pgp","asar","stl","chm","3mf","zst","jxl","vcf","jls","pst","dwg","parquet","class","arj","cpio","ace","avro","icc","fbx"],Wv_=["image/jpeg","image/png","image/gif","image/webp","image/flif","image/x-xcf","image/x-canon-cr2","image/x-canon-cr3","image/tiff","image/bmp","image/vnd.ms-photo","image/vnd.adobe.photoshop","application/x-indesign","application/epub+zip","application/x-xpinstall","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.spreadsheet","application/vnd.oasis.opendocument.presentation","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/zip","application/x-tar","application/x-rar-compressed","application/gzip","application/x-bzip2","application/x-7z-compressed","application/x-apple-diskimage","application/x-apache-arrow","video/mp4","audio/midi","video/x-matroska","video/webm","video/quicktime","video/vnd.avi","audio/wav","audio/qcelp","audio/x-ms-asf","video/x-ms-asf","application/vnd.ms-asf","video/mpeg","video/3gpp","audio/mpeg","audio/mp4","audio/opus","video/ogg","audio/ogg","application/ogg","audio/x-flac","audio/ape","audio/wavpack","audio/amr","application/pdf","application/x-elf","application/x-mach-binary","application/x-msdownload","application/x-shockwave-flash","application/rtf","application/wasm","font/woff","font/woff2","application/vnd.ms-fontobject","font/ttf","font/otf","image/x-icon","video/x-flv","application/postscript","application/eps","application/x-xz","application/x-sqlite3","application/x-nintendo-nes-rom","application/x-google-chrome-extension","application/vnd.ms-cab-compressed","application/x-deb","application/x-unix-archive","application/x-rpm","application/x-compress","application/x-lzip","application/x-cfb","application/x-mie","application/mxf","video/mp2t","application/x-blender","image/bpg","image/j2c","image/jp2","image/jpx","image/jpm","image/mj2","audio/aiff","application/xml","application/x-mobipocket-ebook","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/icns","image/ktx","application/dicom","audio/x-musepack","text/calendar","text/vcard","model/gltf-binary","application/vnd.tcpdump.pcap","audio/x-dsf","application/x.ms.shortcut","application/x.apple.alias","audio/x-voc","audio/vnd.dolby.dd-raw","audio/x-m4a","image/apng","image/x-olympus-orf","image/x-sony-arw","image/x-adobe-dng","image/x-nikon-nef","image/x-panasonic-rw2","image/x-fujifilm-raf","video/x-m4v","video/3gpp2","application/x-esri-shape","audio/aac","audio/x-it","audio/x-s3m","audio/x-xm","video/MP1S","video/MP2P","application/vnd.sketchup.skp","image/avif","application/x-lzh-compressed","application/pgp-encrypted","application/x-asar","model/stl","application/vnd.ms-htmlhelp","model/3mf","image/jxl","application/zstd","image/jls","application/vnd.ms-outlook","image/vnd.dwg","application/x-parquet","application/java-vm","application/x-arj","application/x-cpio","application/x-ace-compressed","application/avro","application/vnd.iccprofile","application/x.autodesk.fbx"];var Hv_=4100;async function $v_(e){return new Znc().fromBuffer(e)}function kZt(e,t,r){r={offset:0,...r};for(let[i,n]of t.entries())if(r.mask){if(n!==(r.mask[i]&e[i+r.offset]))return!1}else if(n!==e[i+r.offset])return!1;return!0}var Znc=class{constructor(t){this.detectors=t?.customDetectors,this.fromTokenizer=this.fromTokenizer.bind(this),this.fromBuffer=this.fromBuffer.bind(this),this.parse=this.parse.bind(this)}async fromTokenizer(t){let r=t.position;for(let i of this.detectors||[]){let n=await i(t);if(n)return n;if(r!==t.position)return}return this.parse(t)}async fromBuffer(t){if(!(t instanceof Uint8Array||t instanceof ArrayBuffer))throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`Buffer\` or \`ArrayBuffer\`, got \`${typeof t}\``);let r=t instanceof Uint8Array?t:new Uint8Array(t);if(r?.length>1)return this.fromTokenizer(qv_(r))}async fromBlob(t){let r=await t.arrayBuffer();return this.fromBuffer(new Uint8Array(r))}async fromStream(t){let r=await Av_(t);try{return await this.fromTokenizer(r)}finally{await r.close()}}async toDetectionStream(t,r={}){let{default:i}=await import("stream"),{sampleSize:n=Hv_}=r;return new Promise((a,u)=>{t.on("error",u),t.once("readable",()=>{(async()=>{try{let l=new i.PassThrough,f=i.pipeline?i.pipeline(t,l,()=>{}):t.pipe(l),s=t.read(n)??t.read()??XYr.Buffer.alloc(0);try{l.fileType=await this.fromBuffer(s)}catch(o){o instanceof qz?l.fileType=void 0:u(o)}a(f)}catch(l){u(l)}})()})})}check(t,r){return kZt(this.buffer,t,r)}checkString(t,r){return this.check(Fv_(t),r)}async parse(t){if(this.buffer=XYr.Buffer.alloc(Hv_),t.fileInfo.size===void 0&&(t.fileInfo.size=Number.MAX_SAFE_INTEGER),this.tokenizer=t,await t.peekBuffer(this.buffer,{length:12,mayBeLess:!0}),this.check([66,77]))return{ext:"bmp",mime:"image/bmp"};if(this.check([11,119]))return{ext:"ac3",mime:"audio/vnd.dolby.dd-raw"};if(this.check([120,1]))return{ext:"dmg",mime:"application/x-apple-diskimage"};if(this.check([77,90]))return{ext:"exe",mime:"application/x-msdownload"};if(this.check([37,33]))return await t.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString("PS-Adobe-",{offset:2})&&this.checkString(" EPSF-",{offset:14})?{ext:"eps",mime:"application/eps"}:{ext:"ps",mime:"application/postscript"};if(this.check([31,160])||this.check([31,157]))return{ext:"Z",mime:"application/x-compress"};if(this.check([199,113]))return{ext:"cpio",mime:"application/x-cpio"};if(this.check([96,234]))return{ext:"arj",mime:"application/x-arj"};if(this.check([239,187,191]))return this.tokenizer.ignore(3),this.parse(t);if(this.check([71,73,70]))return{ext:"gif",mime:"image/gif"};if(this.check([73,73,188]))return{ext:"jxr",mime:"image/vnd.ms-photo"};if(this.check([31,139,8]))return{ext:"gz",mime:"application/gzip"};if(this.check([66,90,104]))return{ext:"bz2",mime:"application/x-bzip2"};if(this.checkString("ID3")){await t.ignore(6);let r=await t.readToken(Uv_);return t.position+r>t.fileInfo.size?{ext:"mp3",mime:"audio/mpeg"}:(await t.ignore(r),this.fromTokenizer(t))}if(this.checkString("MP+"))return{ext:"mpc",mime:"audio/x-musepack"};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:"swf",mime:"application/x-shockwave-flash"};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:"jls",mime:"image/jls"}:{ext:"jpg",mime:"image/jpeg"};if(this.check([79,98,106,1]))return{ext:"avro",mime:"application/avro"};if(this.checkString("FLIF"))return{ext:"flif",mime:"image/flif"};if(this.checkString("8BPS"))return{ext:"psd",mime:"image/vnd.adobe.photoshop"};if(this.checkString("WEBP",{offset:8}))return{ext:"webp",mime:"image/webp"};if(this.checkString("MPCK"))return{ext:"mpc",mime:"audio/x-musepack"};if(this.checkString("FORM"))return{ext:"aif",mime:"audio/aiff"};if(this.checkString("icns",{offset:0}))return{ext:"icns",mime:"image/icns"};if(this.check([80,75,3,4])){try{for(;t.position+30<t.fileInfo.size;){await t.readBuffer(this.buffer,{length:30});let r={compressedSize:this.buffer.readUInt32LE(18),uncompressedSize:this.buffer.readUInt32LE(22),filenameLength:this.buffer.readUInt16LE(26),extraFieldLength:this.buffer.readUInt16LE(28)};if(r.filename=await t.readToken(new YYr(r.filenameLength,"utf-8")),await t.ignore(r.extraFieldLength),r.filename==="META-INF/mozilla.rsa")return{ext:"xpi",mime:"application/x-xpinstall"};if(r.filename.endsWith(".rels")||r.filename.endsWith(".xml"))switch(r.filename.split("/")[0]){case"_rels":break;case"word":return{ext:"docx",mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};case"ppt":return{ext:"pptx",mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation"};case"xl":return{ext:"xlsx",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};default:break}if(r.filename.startsWith("xl/"))return{ext:"xlsx",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};if(r.filename.startsWith("3D/")&&r.filename.endsWith(".model"))return{ext:"3mf",mime:"model/3mf"};if(r.filename==="mimetype"&&r.compressedSize===r.uncompressedSize){let i=await t.readToken(new YYr(r.compressedSize,"utf-8"));switch(i=i.trim(),i){case"application/epub+zip":return{ext:"epub",mime:"application/epub+zip"};case"application/vnd.oasis.opendocument.text":return{ext:"odt",mime:"application/vnd.oasis.opendocument.text"};case"application/vnd.oasis.opendocument.spreadsheet":return{ext:"ods",mime:"application/vnd.oasis.opendocument.spreadsheet"};case"application/vnd.oasis.opendocument.presentation":return{ext:"odp",mime:"application/vnd.oasis.opendocument.presentation"};default:}}if(r.compressedSize===0){let i=-1;for(;i<0&&t.position<t.fileInfo.size;)await t.peekBuffer(this.buffer,{mayBeLess:!0}),i=this.buffer.indexOf("504B0304",0,"hex"),await t.ignore(i>=0?i:this.buffer.length)}else await t.ignore(r.compressedSize)}}catch(r){if(!(r instanceof qz))throw r}return{ext:"zip",mime:"application/zip"}}if(this.checkString("OggS")){await t.ignore(28);let r=XYr.Buffer.alloc(8);return await t.readBuffer(r),kZt(r,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/opus"}:kZt(r,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:kZt(r,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:kZt(r,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:kZt(r,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:kZt(r,[1,118,111,114,98,105,115])?{ext:"ogg",mime:"audio/ogg"}:{ext:"ogx",mime:"application/ogg"}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:"zip",mime:"application/zip"};if(this.checkString("ftyp",{offset:4})&&this.buffer[8]&96){let r=this.buffer.toString("binary",8,12).replace("\0"," ").trim();switch(r){case"avif":case"avis":return{ext:"avif",mime:"image/avif"};case"mif1":return{ext:"heic",mime:"image/heif"};case"msf1":return{ext:"heic",mime:"image/heif-sequence"};case"heic":case"heix":return{ext:"heic",mime:"image/heic"};case"hevc":case"hevx":return{ext:"heic",mime:"image/heic-sequence"};case"qt":return{ext:"mov",mime:"video/quicktime"};case"M4V":case"M4VH":case"M4VP":return{ext:"m4v",mime:"video/x-m4v"};case"M4P":return{ext:"m4p",mime:"video/mp4"};case"M4B":return{ext:"m4b",mime:"audio/mp4"};case"M4A":return{ext:"m4a",mime:"audio/x-m4a"};case"F4V":return{ext:"f4v",mime:"video/mp4"};case"F4P":return{ext:"f4p",mime:"video/mp4"};case"F4A":return{ext:"f4a",mime:"audio/mp4"};case"F4B":return{ext:"f4b",mime:"audio/mp4"};case"crx":return{ext:"cr3",mime:"image/x-canon-cr3"};default:return r.startsWith("3g")?r.startsWith("3g2")?{ext:"3g2",mime:"video/3gpp2"}:{ext:"3gp",mime:"video/3gpp"}:{ext:"mp4",mime:"video/mp4"}}}if(this.checkString("MThd"))return{ext:"mid",mime:"audio/midi"};if(this.checkString("wOFF")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff",mime:"font/woff"};if(this.checkString("wOF2")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff2",mime:"font/woff2"};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:"pcap",mime:"application/vnd.tcpdump.pcap"};if(this.checkString("DSD "))return{ext:"dsf",mime:"audio/x-dsf"};if(this.checkString("LZIP"))return{ext:"lz",mime:"application/x-lzip"};if(this.checkString("fLaC"))return{ext:"flac",mime:"audio/x-flac"};if(this.check([66,80,71,251]))return{ext:"bpg",mime:"image/bpg"};if(this.checkString("wvpk"))return{ext:"wv",mime:"audio/wavpack"};if(this.checkString("%PDF")){try{await t.ignore(1350);let r=10*1024*1024,i=XYr.Buffer.alloc(Math.min(r,t.fileInfo.size));if(await t.readBuffer(i,{mayBeLess:!0}),i.includes(XYr.Buffer.from("AIPrivateData")))return{ext:"ai",mime:"application/postscript"}}catch(r){if(!(r instanceof qz))throw r}return{ext:"pdf",mime:"application/pdf"}}if(this.check([0,97,115,109]))return{ext:"wasm",mime:"application/wasm"};if(this.check([73,73])){let r=await this.readTiffHeader(!1);if(r)return r}if(this.check([77,77])){let r=await this.readTiffHeader(!0);if(r)return r}if(this.checkString("MAC "))return{ext:"ape",mime:"audio/ape"};if(this.check([26,69,223,163])){async function r(){let l=await t.peekNumber(xv_),f=128,s=0;for(;!(l&f)&&f!==0;)++s,f>>=1;let o=XYr.Buffer.alloc(s+1);return await t.readBuffer(o),o}async function i(){let l=await r(),f=await r();f[0]^=128>>f.length-1;let s=Math.min(6,f.length);return{id:l.readUIntBE(0,l.length),len:f.readUIntBE(f.length-s,s)}}async function n(l){for(;l>0;){let f=await i();if(f.id===17026)return(await t.readToken(new YYr(f.len,"utf-8"))).replaceAll(/\00.*$/g,"");await t.ignore(f.len),--l}}let a=await i();switch(await n(a.len)){case"webm":return{ext:"webm",mime:"video/webm"};case"matroska":return{ext:"mkv",mime:"video/x-matroska"};default:return}}if(this.check([82,73,70,70])){if(this.check([65,86,73],{offset:8}))return{ext:"avi",mime:"video/vnd.avi"};if(this.check([87,65,86,69],{offset:8}))return{ext:"wav",mime:"audio/wav"};if(this.check([81,76,67,77],{offset:8}))return{ext:"qcp",mime:"audio/qcelp"}}if(this.checkString("SQLi"))return{ext:"sqlite",mime:"application/x-sqlite3"};if(this.check([78,69,83,26]))return{ext:"nes",mime:"application/x-nintendo-nes-rom"};if(this.checkString("Cr24"))return{ext:"crx",mime:"application/x-google-chrome-extension"};if(this.checkString("MSCF")||this.checkString("ISc("))return{ext:"cab",mime:"application/vnd.ms-cab-compressed"};if(this.check([237,171,238,219]))return{ext:"rpm",mime:"application/x-rpm"};if(this.check([197,208,211,198]))return{ext:"eps",mime:"application/eps"};if(this.check([40,181,47,253]))return{ext:"zst",mime:"application/zstd"};if(this.check([127,69,76,70]))return{ext:"elf",mime:"application/x-elf"};if(this.check([33,66,68,78]))return{ext:"pst",mime:"application/vnd.ms-outlook"};if(this.checkString("PAR1"))return{ext:"parquet",mime:"application/x-parquet"};if(this.check([207,250,237,254]))return{ext:"macho",mime:"application/x-mach-binary"};if(this.check([79,84,84,79,0]))return{ext:"otf",mime:"font/otf"};if(this.checkString("#!AMR"))return{ext:"amr",mime:"audio/amr"};if(this.checkString("{\\rtf"))return{ext:"rtf",mime:"application/rtf"};if(this.check([70,76,86,1]))return{ext:"flv",mime:"video/x-flv"};if(this.checkString("IMPM"))return{ext:"it",mime:"audio/x-it"};if(this.checkString("-lh0-",{offset:2})||this.checkString("-lh1-",{offset:2})||this.checkString("-lh2-",{offset:2})||this.checkString("-lh3-",{offset:2})||this.checkString("-lh4-",{offset:2})||this.checkString("-lh5-",{offset:2})||this.checkString("-lh6-",{offset:2})||this.checkString("-lh7-",{offset:2})||this.checkString("-lzs-",{offset:2})||this.checkString("-lz4-",{offset:2})||this.checkString("-lz5-",{offset:2})||this.checkString("-lhd-",{offset:2}))return{ext:"lzh",mime:"application/x-lzh-compressed"};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:"mpg",mime:"video/MP1S"};if(this.check([68],{offset:4,mask:[196]}))return{ext:"mpg",mime:"video/MP2P"}}if(this.checkString("ITSF"))return{ext:"chm",mime:"application/vnd.ms-htmlhelp"};if(this.check([202,254,186,190]))return{ext:"class",mime:"application/java-vm"};if(this.check([253,55,122,88,90,0]))return{ext:"xz",mime:"application/x-xz"};if(this.checkString("<?xml "))return{ext:"xml",mime:"application/xml"};if(this.check([55,122,188,175,39,28]))return{ext:"7z",mime:"application/x-7z-compressed"};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:"rar",mime:"application/x-rar-compressed"};if(this.checkString("solid "))return{ext:"stl",mime:"model/stl"};if(this.checkString("AC")){let r=this.buffer.toString("binary",2,6);if(r.match("^d*")&&r>=1e3&&r<=1050)return{ext:"dwg",mime:"image/vnd.dwg"}}if(this.checkString("070707"))return{ext:"cpio",mime:"application/x-cpio"};if(this.checkString("BLENDER"))return{ext:"blend",mime:"application/x-blender"};if(this.checkString("!<arch>"))return await t.ignore(8),await t.readToken(new YYr(13,"ascii"))==="debian-binary"?{ext:"deb",mime:"application/x-deb"}:{ext:"ar",mime:"application/x-unix-archive"};if(this.checkString("**ACE",{offset:7})&&(await t.peekBuffer(this.buffer,{length:14,mayBeLess:!0}),this.checkString("**",{offset:12})))return{ext:"ace",mime:"application/x-ace-compressed"};if(this.check([137,80,78,71,13,10,26,10])){await t.ignore(8);async function r(){return{length:await t.readToken(Rv_),type:await t.readToken(new YYr(4,"binary"))}}do{let i=await r();if(i.length<0)return;switch(i.type){case"IDAT":return{ext:"png",mime:"image/png"};case"acTL":return{ext:"apng",mime:"image/apng"};default:await t.ignore(i.length+4)}}while(t.position+8<t.fileInfo.size);return{ext:"png",mime:"image/png"}}if(this.check([65,82,82,79,87,49,0,0]))return{ext:"arrow",mime:"application/x-apache-arrow"};if(this.check([103,108,84,70,2,0,0,0]))return{ext:"glb",mime:"model/gltf-binary"};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:"mov",mime:"video/quicktime"};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:"orf",mime:"image/x-olympus-orf"};if(this.checkString("gimp xcf "))return{ext:"xcf",mime:"image/x-xcf"};if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:"rw2",mime:"image/x-panasonic-rw2"};if(this.check([48,38,178,117,142,102,207,17,166,217])){async function r(){let i=XYr.Buffer.alloc(16);return await t.readBuffer(i),{id:i,size:Number(await t.readToken(Nv_))}}for(await t.ignore(30);t.position+24<t.fileInfo.size;){let i=await r(),n=i.size-24;if(kZt(i.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let a=XYr.Buffer.alloc(16);if(n-=await t.readBuffer(a),kZt(a,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"audio/x-ms-asf"};if(kZt(a,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"video/x-ms-asf"};break}await t.ignore(n)}return{ext:"asf",mime:"application/vnd.ms-asf"}}if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:"ktx",mime:"image/ktx"};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:"mie",mime:"application/x-mie"};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:"shp",mime:"application/x-esri-shape"};if(this.check([255,79,255,81]))return{ext:"j2c",mime:"image/j2c"};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10]))switch(await t.ignore(20),await t.readToken(new YYr(4,"ascii"))){case"jp2 ":return{ext:"jp2",mime:"image/jp2"};case"jpx ":return{ext:"jpx",mime:"image/jpx"};case"jpm ":return{ext:"jpm",mime:"image/jpm"};case"mjp2":return{ext:"mj2",mime:"image/mj2"};default:return}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:"jxl",mime:"image/jxl"};if(this.check([254,255]))return this.check([0,60,0,63,0,120,0,109,0,108],{offset:2})?{ext:"xml",mime:"application/xml"}:void 0;if(this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:"mpg",mime:"video/mpeg"};if(this.check([0,1,0,0,0]))return{ext:"ttf",mime:"font/ttf"};if(this.check([0,0,1,0]))return{ext:"ico",mime:"image/x-icon"};if(this.check([0,0,2,0]))return{ext:"cur",mime:"image/x-icon"};if(this.check([208,207,17,224,161,177,26,225]))return{ext:"cfb",mime:"application/x-cfb"};if(await t.peekBuffer(this.buffer,{length:Math.min(256,t.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:"icc",mime:"application/vnd.iccprofile"};if(this.checkString("BEGIN:")){if(this.checkString("VCARD",{offset:6}))return{ext:"vcf",mime:"text/vcard"};if(this.checkString("VCALENDAR",{offset:6}))return{ext:"ics",mime:"text/calendar"}}if(this.checkString("FUJIFILMCCD-RAW"))return{ext:"raf",mime:"image/x-fujifilm-raf"};if(this.checkString("Extended Module:"))return{ext:"xm",mime:"audio/x-xm"};if(this.checkString("Creative Voice File"))return{ext:"voc",mime:"audio/x-voc"};if(this.check([4,0,0,0])&&this.buffer.length>=16){let r=this.buffer.readUInt32LE(12);if(r>12&&this.buffer.length>=r+16)try{let i=this.buffer.slice(16,r+16).toString();if(JSON.parse(i).files)return{ext:"asar",mime:"application/x-asar"}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:"mxf",mime:"application/mxf"};if(this.checkString("SCRM",{offset:44}))return{ext:"s3m",mime:"audio/x-s3m"};if(this.check([71])&&this.check([71],{offset:188}))return{ext:"mts",mime:"video/mp2t"};if(this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:"mts",mime:"video/mp2t"};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:"mobi",mime:"application/x-mobipocket-ebook"};if(this.check([68,73,67,77],{offset:128}))return{ext:"dcm",mime:"application/dicom"};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:"lnk",mime:"application/x.ms.shortcut"};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:"alias",mime:"application/x.apple.alias"};if(this.checkString("Kaydara FBX Binary \0"))return{ext:"fbx",mime:"application/x.autodesk.fbx"};if(this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8})))return{ext:"eot",mime:"application/vnd.ms-fontobject"};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:"indd",mime:"application/x-indesign"};if(await t.peekBuffer(this.buffer,{length:Math.min(512,t.fileInfo.size),mayBeLess:!0}),Lv_(this.buffer))return{ext:"tar",mime:"application/x-tar"};if(this.check([255,254]))return this.check([60,0,63,0,120,0,109,0,108,0],{offset:2})?{ext:"xml",mime:"application/xml"}:this.check([255,14,83,0,107,0,101,0,116,0,99,0,104,0,85,0,112,0,32,0,77,0,111,0,100,0,101,0,108,0],{offset:2})?{ext:"skp",mime:"application/vnd.sketchup.skp"}:void 0;if(this.checkString("-----BEGIN PGP MESSAGE-----"))return{ext:"pgp",mime:"application/pgp-encrypted"};if(this.buffer.length>=2&&this.check([255,224],{offset:0,mask:[255,224]})){if(this.check([16],{offset:1,mask:[22]}))return this.check([8],{offset:1,mask:[8]})?{ext:"aac",mime:"audio/aac"}:{ext:"aac",mime:"audio/aac"};if(this.check([2],{offset:1,mask:[6]}))return{ext:"mp3",mime:"audio/mpeg"};if(this.check([4],{offset:1,mask:[6]}))return{ext:"mp2",mime:"audio/mpeg"};if(this.check([6],{offset:1,mask:[6]}))return{ext:"mp1",mime:"audio/mpeg"}}}async readTiffTag(t){let r=await this.tokenizer.readToken(t?G2o:$2o);switch(this.tokenizer.ignore(10),r){case 50341:return{ext:"arw",mime:"image/x-sony-arw"};case 50706:return{ext:"dng",mime:"image/x-adobe-dng"};default:}}async readTiffIFD(t){let r=await this.tokenizer.readToken(t?G2o:$2o);for(let i=0;i<r;++i){let n=await this.readTiffTag(t);if(n)return n}}async readTiffHeader(t){let r=(t?G2o:$2o).get(this.buffer,2),i=(t?zv_:Iv_).get(this.buffer,4);if(r===42){if(i>=6){if(this.checkString("CR",{offset:8}))return{ext:"cr2",mime:"image/x-canon-cr2"};if(i>=8&&(this.check([28,0,254,0],{offset:8})||this.check([31,0,11,0],{offset:8})))return{ext:"nef",mime:"image/x-nikon-nef"}}return await this.tokenizer.ignore(i),await this.readTiffIFD(t)??{ext:"tif",mime:"image/tiff"}}if(r===43)return{ext:"tif",mime:"image/tiff"}}};var dr8=new Set(Vv_),pr8=new Set(Wv_);var Qv_=require("fs/promises"),Jv_=li(require("path"),1);var ccE=new Set(["image/jpeg","image/png","image/gif","image/webp","image/tiff","image/x-icon","video/quicktime","video/mp4","video/webm","audio/mpeg","audio/ogg","audio/wav","application/pdf","application/xml","font/woff","font/woff2","font/otf","font/ttf"]),lcE=new Set(["ASCII","UTF-8","UTF-16","ISO-8859-1","ISO-8859-2","ISO-8859-3","ISO-8859-4","ISO-8859-5","ISO-8859-6","ISO-8859-7","ISO-8859-8","ISO-8859-9","ISO-8859-10","ISO-8859-13","ISO-8859-14","ISO-8859-15","ISO-8859-16","WINDOWS-1250","WINDOWS-1251","WINDOWS-1252","WINDOWS-1253","WINDOWS-1254","WINDOWS-1255","WINDOWS-1256","WINDOWS-1257","WINDOWS-1258","SHIFT_JIS","SHIFT-JIS","EUC-JP","ISO-2022-JP","BIG5","GB2312","GB18030","KOI8-R"]),knc={name:"valid-file-types",create:()=>({filepath:async({absoluteFilepath:e,willBeUploaded:t})=>t?await Cf(e)?fcE(e):[]:[]})},fcE=async e=>{let t=new Uint8Array(await(0,Qv_.readFile)(e)),r=await $v_(t);if(r!=null)return ccE.has(r.mime)?[]:[{severity:"fatal",message:`The file type of ${r.mime} is not allowed: ${e}`}];let i=Jv_.default.extname(e).toLowerCase();i.startsWith(".")&&(i=i.substring(1));let n=Gv_.default.detect(t);return n==null?[{severity:"fatal",message:`The encoding of the file could not be detected: ${e}`}]:lcE.has(n.toUpperCase())?[]:[{severity:"fatal",message:`The encoding of ${n} is not allowed: ${e}`}]};var Kv_=require("fs/promises"),Yv_=li(oXt(),1),eac={name:"valid-frontmatter",create:()=>({filepath:async({absoluteFilepath:e})=>{if(!e.endsWith(".md")&&!e.endsWith(".mdx"))return[];try{let t=await(0,Kv_.readFile)(e,"utf-8");return(0,Yv_.default)(t),[]}catch(t){return[{severity:"fatal",message:`Failed to parse frontmatter${t instanceof Error?`: ${t.message}`:""}`}]}}})};var sb_=require("crypto"),sac=li(require("path"),1);var Xv_=require("fs"),Q2o=class{parse({absoluteFilePath:t}){let r=(0,Xv_.readFileSync)(t,"utf-8"),i=r.match(/option\s+csharp_namespace\s*=\s*"([^"]+)";/),n=r.match(/package\s+([a-zA-Z_][\w.]*);/),a=r.match(/service\s+([a-zA-Z_]\w*)\s*{/);return{csharpNamespace:i?.[1],packageName:n?.[1],serviceName:a?.[1]}}};var J2o=class{context;workspace;sourceCache;constructor(t,r){this.context=t,this.workspace=r,this.sourceCache=new Map}resolveSourceOrThrow({source:t,relativeFilepath:r}){let i=this.resolveSource({source:t});if(i==null){if(_Jt(t))throw new Error(`Cannot resolve source ${t.proto} from file ${r}`);this.context.logger.warn(`Cannot resolve source ${t.openapi} from file ${r}`)}return i}resolveSource({source:t}){return _Jt(t)?this.resolveProtobufSource({source:t}):this.resolveOpenAPISource({source:t})}resolveProtobufSource({source:t}){let r=Lu(this.workspace.absoluteFilePath,Xa.of(t.proto));if(this.sourceCache.has(r))return this.sourceCache.get(r);if(!mQr(r))return;let n=new Q2o().parse({absoluteFilePath:r}),a={type:"protobuf",absoluteFilePath:r,relativeFilePath:Xa.of(t.proto),csharpNamespace:n.csharpNamespace,packageName:n.packageName,serviceName:n.serviceName};return this.sourceCache.set(r,a),a}resolveOpenAPISource({source:t}){let r=Lu(this.workspace.absoluteFilePath,Xa.of(t.openapi));if(this.sourceCache.has(r))return this.sourceCache.get(r);if(!mQr(r))return;let i={type:"openapi",absoluteFilePath:r,relativeFilePath:Xa.of(t.openapi)};return this.sourceCache.set(r,i),i}};function dcE(e){for(var t=[],r=0;r<e.length;){var i=e[r];if(i==="*"||i==="+"||i==="?"){t.push({type:"MODIFIER",index:r,value:e[r++]});continue}if(i==="\\"){t.push({type:"ESCAPED_CHAR",index:r++,value:e[r++]});continue}if(i==="{"){t.push({type:"OPEN",index:r,value:e[r++]});continue}if(i==="}"){t.push({type:"CLOSE",index:r,value:e[r++]});continue}if(i===":"){for(var n="",a=r+1;a<e.length;){var u=e.charCodeAt(a);if(u>=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||u===95){n+=e[a++];continue}break}if(!n)throw new TypeError("Missing parameter name at ".concat(r));t.push({type:"NAME",index:r,value:n}),r=a;continue}if(i==="("){var l=1,f="",a=r+1;if(e[a]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(a));for(;a<e.length;){if(e[a]==="\\"){f+=e[a++]+e[a++];continue}if(e[a]===")"){if(l--,l===0){a++;break}}else if(e[a]==="("&&(l++,e[a+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(a));f+=e[a++]}if(l)throw new TypeError("Unbalanced pattern at ".concat(r));if(!f)throw new TypeError("Missing pattern at ".concat(r));t.push({type:"PATTERN",index:r,value:f}),r=a;continue}t.push({type:"CHAR",index:r,value:e[r++]})}return t.push({type:"END",index:r,value:""}),t}function Zv_(e,t){t===void 0&&(t={});for(var r=dcE(e),i=t.prefixes,n=i===void 0?"./":i,a=t.delimiter,u=a===void 0?"/#?":a,l=[],f=0,s=0,o="",c=function(L){if(s<r.length&&r[s].type===L)return r[s++].value},b=function(L){var V=c(L);if(V!==void 0)return V;var Y=r[s],K=Y.type,Z=Y.index;throw new TypeError("Unexpected ".concat(K," at ").concat(Z,", expected ").concat(L))},g=function(){for(var L="",V;V=c("CHAR")||c("ESCAPED_CHAR");)L+=V;return L},O=function(L){for(var V=0,Y=u;V<Y.length;V++){var K=Y[V];if(L.indexOf(K)>-1)return!0}return!1},m=function(L){var V=l[l.length-1],Y=L||(V&&typeof V=="string"?V:"");if(V&&!Y)throw new TypeError('Must have text between two parameters, missing text after "'.concat(V.name,'"'));return!Y||O(Y)?"[^".concat(nhi(u),"]+?"):"(?:(?!".concat(nhi(Y),")[^").concat(nhi(u),"])+?")};s<r.length;){var P=c("CHAR"),E=c("NAME"),q=c("PATTERN");if(E||q){var A=P||"";n.indexOf(A)===-1&&(o+=A,A=""),o&&(l.push(o),o=""),l.push({name:E||f++,prefix:A,suffix:"",pattern:q||m(A),modifier:c("MODIFIER")||""});continue}var D=P||c("ESCAPED_CHAR");if(D){o+=D;continue}o&&(l.push(o),o="");var C=c("OPEN");if(C){var A=g(),z=c("NAME")||"",$=c("PATTERN")||"",x=g();b("CLOSE"),l.push({name:z||($?f++:""),pattern:z&&!$?m(A):$,prefix:A,suffix:x,modifier:c("MODIFIER")||""});continue}b("END")}return l}function kv_(e,t){return pcE(Zv_(e,t),t)}function pcE(e,t){t===void 0&&(t={});var r=tac(t),i=t.encode,n=i===void 0?function(f){return f}:i,a=t.validate,u=a===void 0?!0:a,l=e.map(function(f){if(typeof f=="object")return new RegExp("^(?:".concat(f.pattern,")$"),r)});return function(f){for(var s="",o=0;o<e.length;o++){var c=e[o];if(typeof c=="string"){s+=c;continue}var b=f?f[c.name]:void 0,g=c.modifier==="?"||c.modifier==="*",O=c.modifier==="*"||c.modifier==="+";if(Array.isArray(b)){if(!O)throw new TypeError('Expected "'.concat(c.name,'" to not repeat, but got an array'));if(b.length===0){if(g)continue;throw new TypeError('Expected "'.concat(c.name,'" to not be empty'))}for(var m=0;m<b.length;m++){var P=n(b[m],c);if(u&&!l[o].test(P))throw new TypeError('Expected all "'.concat(c.name,'" to match "').concat(c.pattern,'", but got "').concat(P,'"'));s+=c.prefix+P+c.suffix}continue}if(typeof b=="string"||typeof b=="number"){var P=n(String(b),c);if(u&&!l[o].test(P))throw new TypeError('Expected "'.concat(c.name,'" to match "').concat(c.pattern,'", but got "').concat(P,'"'));s+=c.prefix+P+c.suffix;continue}if(!g){var E=O?"an array":"a string";throw new TypeError('Expected "'.concat(c.name,'" to be ').concat(E))}}return s}}function eb_(e,t){var r=[],i=tb_(e,r,t);return _cE(i,r,t)}function _cE(e,t,r){r===void 0&&(r={});var i=r.decode,n=i===void 0?function(a){return a}:i;return function(a){var u=e.exec(a);if(!u)return!1;for(var l=u[0],f=u.index,s=Object.create(null),o=function(b){if(u[b]===void 0)return"continue";var g=t[b-1];g.modifier==="*"||g.modifier==="+"?s[g.name]=u[b].split(g.prefix+g.suffix).map(function(O){return n(O,g)}):s[g.name]=n(u[b],g)},c=1;c<u.length;c++)o(c);return{path:l,index:f,params:s}}}function nhi(e){return e.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}function tac(e){return e&&e.sensitive?"":"i"}function hcE(e,t){if(!t)return e;for(var r=/\((?:\?<(.*?)>)?(?!\?)/g,i=0,n=r.exec(e.source);n;)t.push({name:n[1]||i++,prefix:"",suffix:"",modifier:"",pattern:""}),n=r.exec(e.source);return e}function ycE(e,t,r){var i=e.map(function(n){return tb_(n,t,r).source});return new RegExp("(?:".concat(i.join("|"),")"),tac(r))}function vcE(e,t,r){return bcE(Zv_(e,r),t,r)}function bcE(e,t,r){r===void 0&&(r={});for(var i=r.strict,n=i===void 0?!1:i,a=r.start,u=a===void 0?!0:a,l=r.end,f=l===void 0?!0:l,s=r.encode,o=s===void 0?function(V){return V}:s,c=r.delimiter,b=c===void 0?"/#?":c,g=r.endsWith,O=g===void 0?"":g,m="[".concat(nhi(O),"]|$"),P="[".concat(nhi(b),"]"),E=u?"^":"",q=0,A=e;q<A.length;q++){var D=A[q];if(typeof D=="string")E+=nhi(o(D));else{var C=nhi(o(D.prefix)),z=nhi(o(D.suffix));if(D.pattern)if(t&&t.push(D),C||z)if(D.modifier==="+"||D.modifier==="*"){var $=D.modifier==="*"?"?":"";E+="(?:".concat(C,"((?:").concat(D.pattern,")(?:").concat(z).concat(C,"(?:").concat(D.pattern,"))*)").concat(z,")").concat($)}else E+="(?:".concat(C,"(").concat(D.pattern,")").concat(z,")").concat(D.modifier);else{if(D.modifier==="+"||D.modifier==="*")throw new TypeError('Can not repeat "'.concat(D.name,'" without a prefix and suffix'));E+="(".concat(D.pattern,")").concat(D.modifier)}else E+="(?:".concat(C).concat(z,")").concat(D.modifier)}}if(f)n||(E+="".concat(P,"?")),E+=r.endsWith?"(?=".concat(m,")"):"$";else{var x=e[e.length-1],L=typeof x=="string"?P.indexOf(x[x.length-1])>-1:x===void 0;n||(E+="(?:".concat(P,"(?=").concat(m,"))?")),L||(E+="(?=".concat(P,"|").concat(m,")"))}return new RegExp(E,tac(r))}function tb_(e,t,r){return e instanceof RegExp?hcE(e,t):Array.isArray(e)?ycE(e,t,r):vcE(e,t,r)}function rb_(e){return e.split(/[?#]/)[0]??""}function K2o(e){return e.startsWith("/")?e.slice(1):e}function rac(e){return e.startsWith("/")?e:`/${e}`}function Y2o(e){return e.endsWith("/")?e.slice(0,-1):e}function ib_(e){let t=[];return e.config.instances.forEach(r=>{t.push(r.url),typeof r.customDomain=="string"?t.push(r.customDomain):Array.isArray(r.customDomain)&&t.push(...r.customDomain)}),t}function nb_(e){let t=new URL(HX(e));return{domain:t.host,basePath:t.pathname==="/"||t.pathname===""?void 0:t.pathname}}function gcE(e,t){if(e===t)return{params:{},path:t,index:0};try{return eb_(e)(t)}catch(r){return console.error(r,{pattern:e,path:t}),!1}}function OcE(e,t){try{return kv_(e)(t.params)}catch(r){return console.error(r,{match:t,destination:e}),e}}function ab_(e,t,r=[]){for(let i of r){let n=Y2o(mcE(i.source,t.basePath)),a=gcE(n,e);if(a){let u=OcE(i.destination,a);if(!u.startsWith("/"))try{new URL(u)}catch{console.error("Invalid redirect destination:",u);return}return{redirect:{destination:encodeURI(u),permanent:i.permanent??!1}}}}}function mcE(e,t){return t==null||e.startsWith(t)?e:Wv(t,e)}async function aac({pathname:e,markdown:t,absoluteFilepath:r,workspaceAbsoluteFilePath:i,pageSlugs:n,absoluteFilePathsToSlugs:a,redirects:u=[],baseUrl:l}){e=Y2o(e);let f=r!=null?a.get(r)??[]:[];if(e.trim()==="")return!0;if(e=nac(e),e.startsWith("/")){let o=nac(iac(e,l,u));for(let b=0;b<5;++b){let g=nac(iac(o,l,u));if(o===g)break;o=g}if(t&&n.has(K2o(o)))return!0;let c=Lu(i,Xa.of(K2o(e)));return await Cf(c,"file")?!0:f.map(b=>rac(b))}if(r!=null){if(e==="."){let c=Zd(r);if(await Cf(c,"directory"))return!0}let o=Lu(Zd(r),Xa.of(e));if(await Cf(o,"file"))return!0}if(!t)return f.map(o=>rac(o));let s=[];for(let o of f){let c=new URL(`/${o}`,HX(l.domain)),b=iac(new URL(e,c).pathname,l,u);n.has(K2o(b))||s.push(o)}return s.length>0?s:!0}function iac(e,t,r){let i=ab_(e,t,r);return i==null?e:i.redirect.destination}function nac(e){let t=e.indexOf("#");return t===-1?e:e.substring(0,t)}var ob_=/^(?:[a-z+]+:)/gi;function PcE(e){let t=/^---\n([\s\S]*?)\n---/,r=e.match(t);return r?(r[0].match(/\n/g)||[]).length+1:0}function oac(e,t){return e&&{...e,start:{...e.start,line:e.start.line+t},end:{...e.end,line:e.end.line+t}}}function uac(e,{absoluteFilepath:t,instanceUrls:r}){let i=[],n=[],a=PcE(e),{links:u,sources:l}=sv_({content:e,absoluteFilepath:t});return u.forEach(f=>{if(f.href.trimStart().match(ob_)){if(!f.href.trimStart().startsWith("http"))return;try{let o=new URL(f.href);if(!r.some(c=>f.href.includes(c)))return;n.push({pathname:o.pathname,sourceFilepath:f.sourceFilepath,position:oac(f.position,a),markdown:!0})}catch{i.push({severity:"warning",message:`Invalid URL: ${f.href}`})}return}let s=rb_(f.href);s.trim()!==""&&n.push({pathname:s,sourceFilepath:f.sourceFilepath,position:oac(f.position,a),markdown:!0})}),l.forEach(f=>{if(f.src.match(ob_))try{new URL(f.src)}catch{i.push({severity:"warning",message:`Invalid URL: ${f.src}`});return}else n.push({pathname:f.src,sourceFilepath:f.sourceFilepath,position:oac(f.position,a),markdown:!1})}),{pathnamesToCheck:n,violations:i}}var X2o=fbs({logger:EQr(Go)}),U3i={name:"valid-markdown-links",create:async({workspace:e,apiWorkspaces:t,ossWorkspaces:r})=>{let i=ib_(e),n=i[0]??"http://localhost",a=nb_(i[0]??"http://localhost"),l=await new F9t(n,e,r,t,X2o).resolve();if(!l.config.root)throw new Error("Root node not found");let f=xo.migrate.FernNavigationV1ToLatest.create().root(l.config.root),s=xo.NodeCollector.collect(f),o=new Set,c=new Map,b=[];return s.slugMap.forEach((g,O)=>{if(o.add(O),g==null||!xo.isPage(g))return;xo.isApiLeaf(g)&&b.push(g);let m=xo.getPageId(g);if(m==null)return;let P=Lu(e.absoluteFilePath,Xa.of(m)),E=c.get(P)??[];E.push(O),c.set(P,E)}),{markdownPage:async({content:g,absoluteFilepath:O})=>{let m=c.get(O);if(!m||m.length===0)return[];let{pathnamesToCheck:P,violations:E}=uac(g,{absoluteFilepath:O,instanceUrls:i}),q=await Promise.all(P.map(async A=>{let D=await aac({pathname:A.pathname,markdown:A.markdown,absoluteFilepath:O,workspaceAbsoluteFilePath:e.absoluteFilePath,pageSlugs:o,absoluteFilePathsToSlugs:c,redirects:e.config.redirects,baseUrl:a});return D===!0?[]:D.map(C=>{let[z,$]=ub_({pathnameToCheck:A,targetPathname:C,absoluteFilepathToWorkspace:e.absoluteFilePath});return{name:U3i.name,severity:"error",message:z,relativeFilepath:$}})}));return[...E,...q.flat()]},apiSection:async({workspace:g,config:O})=>{let m=await g.toFernWorkspace({context:X2o},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1}),P=FF({workspace:m,audiences:O.audiences?{type:"select",audiences:O.audiences}:{type:"all"},generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:X2o,sourceResolver:new J2o(X2o,m)}),E=jcE(G0a(P,(0,sb_.randomUUID)())),q=[];for(let A of b){let D=await wcE(R_i.prune(E,A));for(let C of D){let{pathnamesToCheck:z,violations:$}=uac(C,{instanceUrls:i});q.push(...$);let x=await Promise.all(z.map(async L=>{let V=await aac({pathname:L.pathname,markdown:L.markdown,workspaceAbsoluteFilePath:e.absoluteFilePath,pageSlugs:o,absoluteFilePathsToSlugs:c,redirects:e.config.redirects,baseUrl:a});return V===!0?[]:V.map(Y=>{let[K,Z]=ub_({pathnameToCheck:L,targetPathname:Y,absoluteFilepathToWorkspace:e.absoluteFilePath});return{name:U3i.name,severity:"error",message:K,relFilepath:Z}})}));q.push(...x.flat())}}return q}}}};function ub_({pathnameToCheck:e,targetPathname:t,absoluteFilepathToWorkspace:r}){let i=`${t} links to non-existent page ${Ws.bold(e.pathname)}`,{position:n,sourceFilepath:a}=e;if(a==null||n==null)return[i,Xa.of("")];i=`broken link to ${Ws.bold(e.pathname)}`,e.pathname.length>0&&!sac.default.isAbsolute(e.pathname)&&(i+=` (resolved path: ${sac.default.join(t,e.pathname)})`);let u=KA(r,a);return i+=`
|
|
2029
2029
|
fix here: ${u}:${n.start.line}:${n.start.column}`,[i,u]}function jcE(e){return R_i.ApiDefinitionV1ToLatest.from(e,{useJavaScriptAsTypeScript:!1,alwaysEnableJavaScriptFetch:!1,usesApplicationJsonInFormDataValue:!1}).migrate()}async function wcE(e){let t=[];return R_i.Transformer.descriptions(r=>(typeof r=="string"&&t.push(r),r)).apiDefinition(e),t}var cac={name:"validate-version-file",create:()=>({versionFile:async({path:e,content:t})=>{let r=await C2o({value:t});return r.type==="success"?[]:[{severity:"fatal",message:`${r.message}`}]}})};var cb_=[hnc,ync,cac,_v_,U3i,knc,vnc,hv_,eac];function lb_(e){if(!e)return cb_;let t=new Set(e);return cb_.filter(r=>!t.has(r.name))}async function wga(e,t,r,i,n,a){let u=n?[U3i]:lb_(a);return ScE({workspace:e,rules:u,context:t,apiWorkspaces:r,ossWorkspaces:i})}async function ScE({workspace:e,rules:t,context:r,apiWorkspaces:i,ossWorkspaces:n}){let a=[],u=await Promise.all(t.map(f=>f.create({workspace:e,apiWorkspaces:i,ossWorkspaces:n,logger:r.logger}))),l=cv_({relativeFilepath:Xa.of(a8t),allRuleVisitors:u,addViolations:f=>{a.push(...f)}});return await pv_({contents:e.config,visitor:l,absoluteFilepathToConfiguration:Lu(e.absoluteFilePath,Xa.of(a8t)),absolutePathToFernFolder:e.absoluteFilePath,context:r,apiWorkspaces:i}),a}function gAn({context:e,violations:t,logWarnings:r,logSummary:i=!0,logBreadcrumbs:n=!0,elapsedMillis:a=0}){let u=[],l={};for(let o of t){let c=JSON.stringify(o.nodePath),b=l[c]??[];b.some(O=>O.message===o.message&&O.nodePath.length===o.nodePath.length&&O.nodePath.every((m,P)=>_Se(m,o.nodePath[P]))&&O.relativeFilepath===o.relativeFilepath&&O.severity===o.severity)||(u.push(o),l[c]=[...b,o])}t=u;let f=TcE(t),s=DcE(t);for(let o of Array.from(s.keys()).sort()){let c=s.get(o);if(c){let b=c[0]?.relativeFilepath??"";EcE({logWarnings:r,logBreadcrumbs:n,configRelativeFilepath:b,nodePath:o,violations:c,context:e})}}return i&&qcE({context:e,stats:f,logWarnings:r,elapsedMillis:a}),{hasErrors:f.numFatal>0}}function DcE(e){let t={};for(let r of e){let i=JSON.stringify(r.nodePath),n=t[i]??[];t[i]=[...n,r]}return new Map(Object.entries(t).map(([r,i])=>[JSON.parse(r),i]))}function EcE({logWarnings:e,logBreadcrumbs:t,configRelativeFilepath:r,nodePath:i,violations:n,context:a}){let u=McE(n);if(u==="warning"&&!e)return;let l="",f=n.map(s=>s.severity==="warning"&&!e?null:(l===""&&(l=s.relativeFilepath),s.message)).filter(s=>s!=null).join(`
|
|
2030
2030
|
`);a.logger.log(AcE(u),kie({breadcrumbs:t?[r,...i.map(s=>{let o=typeof s=="string"?s:s.key;return typeof s!="string"&&s.arrayIndex!=null&&(o+=`[${s.arrayIndex}]`),o})]:[],title:l,subtitle:f})+`
|
|
2031
|
-
`)}function McE(e){return e.some(t=>t.severity==="fatal")?"fatal":e.some(t=>t.severity==="error")?"error":"warning"}function AcE(e){switch(e){case"fatal":return G0.Error;case"error":return G0.Error;case"warning":return G0.Warn;default:Mo(e)}}function qcE({stats:e,context:t,logWarnings:r,elapsedMillis:i=0}){let{numFatal:n,numErrors:a,numWarnings:u}=e,l=i>0?` in ${(i/1e3).toFixed(3)} seconds.`:".",f=`Found ${n+a} errors and ${u} warnings`+l;!r&&u>0&&(f+=" Run fern check --warnings to print out the warnings not shown."),n+a>0?t.logger.error(f):u>0?t.logger.warn(f):t.logger.info(Ws.green("\u2713 All checks passed"))}function TcE(e){let t=0,r=0,i=0;for(let n of e)switch(n.severity){case"fatal":t+=1;continue;case"error":r+=1;continue;case"warning":i+=1;continue;default:Mo(n.severity)}return{numFatal:t,numErrors:r,numWarnings:i}}async function OAn({workspace:e,apiWorkspaces:t,ossWorkspaces:r,context:i,logWarnings:n,errorOnBrokenLinks:a,logSummary:u=!0,excludeRules:l}){let f=performance.now(),s=await wga(e,i,t,r,!1,l),o=performance.now()-f,{hasErrors:c}=gAn({violations:s,context:i,logWarnings:n,logSummary:u,logBreadcrumbs:!1,elapsedMillis:o});return a&&(c=c||s.some(b=>b.name==="valid-markdown-links")),{hasErrors:c}}async function Z2o({workspace:e,apiWorkspaces:t,ossWorkspaces:r,context:i,logWarnings:n,errorOnBrokenLinks:a,excludeRules:u}){let{hasErrors:l}=await OAn({workspace:e,context:i,logWarnings:n,apiWorkspaces:t,ossWorkspaces:r,errorOnBrokenLinks:a,excludeRules:u});l&&i.failAndThrow()}var CcE=["cohere","deepgram","payroc","chainalysis","devrev","deriv","webflow"];async function fb_({loadProject:e,cliContext:t,port:r,bundlePath:i,brokenLinks:n,appPreview:a,legacyPreview:u,backendPort:l}){let f=await e(),s=f.docsWorkspaces;if(s==null)return;let o=CcE.includes(f.config.organization);if(a?o=!1:u&&(o=!0),!o||a){await t.instrumentPostHogEvent({orgId:f.config.organization,command:"fern docs dev --beta"}),await t.runTaskForWorkspace(s,async c=>{c.logger.info(`Starting server on port ${r}`),await snc({initialProject:f,reloadProject:e,validateProject:async b=>{let g=b.docsWorkspaces;if(g==null)return;let O=n?[]:["valid-markdown-links"];g.config.experimental?.openapiParserV3?await OAn({workspace:g,context:c,logWarnings:!0,logSummary:!1,apiWorkspaces:[],ossWorkspaces:await JV(b),excludeRules:O}):await OAn({workspace:g,context:c,logWarnings:!0,logSummary:!1,apiWorkspaces:b.apiWorkspaces,ossWorkspaces:await JV(b),excludeRules:O})},context:c,port:r,bundlePath:i,backendPort:l})});return}await t.instrumentPostHogEvent({orgId:f.config.organization,command:"fern docs dev --legacy"}),await t.runTaskForWorkspace(s,async c=>{c.logger.info(`Starting server on port ${r}`),await unc({initialProject:f,reloadProject:e,validateProject:async b=>{let g=b.docsWorkspaces;if(g==null)return;let O=n?[]:["valid-markdown-links"];g.config.experimental?.openapiParserV3?await OAn({workspace:g,context:c,logWarnings:!0,logSummary:!1,apiWorkspaces:[],ossWorkspaces:await JV(b),excludeRules:O}):await OAn({workspace:g,context:c,logWarnings:!0,logSummary:!1,apiWorkspaces:b.apiWorkspaces,ossWorkspaces:await JV(b),excludeRules:O})},context:c,port:r,bundlePath:i})})}async function db_({project:e,cliContext:t,shouldFix:r}){await Promise.all(e.apiWorkspaces.map(async i=>{i instanceof nN||await t.runTaskForWorkspace(i,async n=>{await WRs({workspace:await i.toFernWorkspace({context:n}),context:n,shouldFix:r})})}))}var p0_=li(require("path"),1);var d0_=li(_b_(),1);var s9={RequestReference:"requestReference",InlinedRequestProperty:"inlinedRequestProperty",Response:"response",StreamingResponse:"streamingResponse"};function tT(e,t){return r=>{r!=null&&e.docs?.(r,[...t,"docs"])}}function mRe({example:e,visitor:t,nodePath:r}){if(typeof e=="string")e.startsWith(fJt)&&t.exampleTypeReference?.(e,r);else if(mj(e))for(let i of Object.values(e))mRe({example:i,visitor:t,nodePath:r});else if(Array.isArray(e))for(let i of e)mRe({example:i,visitor:t,nodePath:r})}function L9t(e){return(t,r,{_default:i,validation:n,location:a}={})=>{e.typeReference?.({typeReference:t,_default:i,validation:n,location:a,nodePath:r},r)}}function hb_({service:e,visitor:t,nodePath:r}){t.httpService?.(e,r),aw(e,{url:i=>{t.serviceBaseUrl?.(i,[...r,"url"])},"base-path":Go,"display-name":Go,availability:Go,headers:i=>{yb_({headers:i,visitor:t,nodePath:[...r,"headers"]})},audiences:Go,auth:Go,"path-parameters":i=>{Dga({pathParameters:i,visitor:t,nodePath:[...r,"path-parameters"]})},endpoints:i=>{for(let[n,a]of Object.entries(i)){let u=[...r,"endpoints",n];RcE({endpointId:n,endpoint:a,service:e,visitor:t,nodePathForEndpoint:u})}},idempotent:Go,transport:Go,source:Go})}function RcE({endpointId:e,endpoint:t,service:r,visitor:i,nodePathForEndpoint:n}){let a=L9t(i);i.httpEndpoint?.({endpointId:e,endpoint:t,service:r},n),aw(t,{docs:tT(i,n),"display-name":Go,availability:Go,"base-path":Go,path:Go,idempotent:Go,url:u=>{i.endpointBaseUrl?.({baseUrl:u,service:r},[...n,"url"])},"path-parameters":u=>{Dga({pathParameters:u,visitor:i,nodePath:[...n,"path-parameters"]})},request:u=>{if(u==null)return;let l=[...n,"request"];if(typeof u=="string"){a(u,l,{location:"requestReference"});return}aw(u,{name:Go,docs:tT(i,l),"path-parameters":f=>{Dga({pathParameters:f,visitor:i,nodePath:[...l,"path-parameters"]})},"query-parameters":f=>{if(f!=null)for(let[s,o]of Object.entries(f)){let c=[...l,"query-parameters",s];i.queryParameter?.({queryParameterKey:s,queryParameter:o},c),typeof o=="string"?a(o,c):aw(o,{name:Go,docs:tT(i,c),availability:Go,type:b=>{a(b,[...c,"type"],{_default:o.default,validation:o.validation})},"allow-multiple":Go,audiences:Go,encoding:Go,default:Go,validation:Go})}},"content-type":Go,headers:f=>{yb_({headers:f,visitor:i,nodePath:[...l,"headers"]})},body:f=>{if(f==null)return;let s=[...l,"body"];typeof f=="string"?a(f,s,{location:"requestReference"}):oC(f)?(i.typeDeclaration?.({typeName:{isInlined:!0,location:"inlinedRequest"},declaration:f},s),aw(f,{extends:o=>{if(o==null)return;let c=typeof o=="string"?[o]:o;for(let b of c){let g=[...s,"extends",b];i.extension?.(b,g),a(b,g)}},properties:o=>{if(o!=null)for(let[c,b]of Object.entries(o)){let g=[...s,"properties",c];typeof b=="string"?a(b,g,{location:s9.InlinedRequestProperty}):aw(b,{name:Go,docs:tT(i,g),availability:Go,type:O=>{a(O,[...g,"type"],{location:s9.InlinedRequestProperty,_default:b.default,validation:b.validation})},style:Go,"content-type":Go,audiences:Go,encoding:Go,default:Go,validation:Go})}},"extra-properties":Go})):(tT(i,s)(f.docs),a(f.type,s))}})},audiences:Go,method:Go,auth:Go,"stream-condition":u=>{i.streamCondition?.({streamCondition:u,endpoint:t},[...n,"stream-condition"])},"response-stream":u=>{u!=null&&(typeof u=="string"?a(u,[...n,"response-stream"],{location:s9.StreamingResponse}):a(u.type,[...n,"response-stream"],{location:s9.StreamingResponse}))},response:u=>{if(u==null)return;let l=[...n,"response"];typeof u=="string"?a(u,l,{location:s9.Response}):aw(u,{docs:tT(i,l),type:f=>{f!=null&&a(f,[...l,"type"],{location:s9.Response})},property:Go,"status-code":Go})},errors:u=>{if(u!=null)for(let l of u){let f=[...n,"errors",typeof l=="string"?l:l.error];typeof l=="string"?i.errorReference?.(l,f):aw(l,{docs:tT(i,f),error:s=>{i.errorReference?.(s,[...f,"error"])}})}},examples:u=>{if(u!=null)for(let[l,f]of u.entries())NcE({nodePathForExample:[...n,{key:"examples",arrayIndex:l}],visitor:i,service:r,endpoint:t,example:f})},pagination:Go,source:Go,transport:Go})}function NcE({nodePathForExample:e,visitor:t,service:r,endpoint:i,example:n}){if(n.headers==null&&n["path-parameters"]==null&&n["query-parameters"]==null&&n.request==null&&n.response==null&&n["code-samples"]!=null)return;t.exampleHttpEndpointCall?.({service:r,endpoint:i,example:n},e);let a=[...e,"headers"];if(t.exampleHeaders?.({service:r,endpoint:i,examples:n.headers},a),n.headers!=null)for(let o of Object.values(n.headers))mRe({example:o,visitor:t,nodePath:a});let u=[...e,"path-parameters"];if(t.examplePathParameters?.({service:r,endpoint:i,examples:n["path-parameters"]},u),n["path-parameters"]!=null)for(let o of Object.values(n["path-parameters"]))mRe({example:o,visitor:t,nodePath:u});let l=[...e,"query-parameters"];if(t.exampleQueryParameters?.({service:r,endpoint:i,examples:n["query-parameters"]},l),n["query-parameters"]!=null)for(let o of Object.values(n["query-parameters"]))mRe({example:o,visitor:t,nodePath:l});let f=[...e,"request"];t.exampleRequest?.({service:r,endpoint:i,example:n.request},f),n.request!=null&&mRe({example:n.request,visitor:t,nodePath:f});let s=[...e,"response"];if(t.exampleResponse?.({service:r,endpoint:i,example:n.response},s),n.response!=null&&xxi(i,n.response,{body:o=>{o.body!=null&&mRe({example:o.body,visitor:t,nodePath:s}),o.error!=null&&t.errorReference?.(o.error,[...s,"error"])},stream:o=>{for(let c of o.stream)mRe({example:c,visitor:t,nodePath:s})},events:o=>{for(let{data:c}of o.stream)mRe({example:c,visitor:t,nodePath:s})}}),n["code-samples"]!=null)for(let[o,c]of n["code-samples"].entries())t.exampleCodeSample?.({service:r,endpoint:i,example:n,sample:c},[...e,{key:"code-samples",arrayIndex:o}])}function Dga({pathParameters:e,visitor:t,nodePath:r}){if(e==null)return;let i=L9t(t);for(let[n,a]of Object.entries(e)){let u=[...r,n];t.pathParameter?.({pathParameterKey:n,pathParameter:a},u),$0n(a)?typeof a=="string"?t.variableReference?.(a,u):aw(a,{docs:tT(t,u),variable:l=>t.variableReference?.(l,[...u,"variable"]),availability:Go}):typeof a=="string"?i(a,u):aw(a,{docs:tT(t,u),type:l=>{i(l,[...u,"type"],{_default:a.default,validation:a.validation})},availability:Go,encoding:Go,default:Go,validation:Go,name:Go,audiences:Go})}}function yb_({headers:e,visitor:t,nodePath:r}){if(e==null)return;let i=L9t(t);for(let[n,a]of Object.entries(e)){let u=[...r,n];t.header?.({headerKey:n,header:a},u),typeof a=="string"?i(a,u):aw(a,{name:Go,availability:Go,type:l=>{i(l,u,{_default:a.default,validation:a.validation})},docs:tT(t,u),audiences:Go,encoding:Go,env:Go,default:Go,validation:Go})}}function vb_({typeDeclarations:e,visitor:t,nodePath:r}){if(e!=null)for(let[i,n]of Object.entries(e)){let a=[...r,i];t.typeName?.(i,a),lac({typeName:i,declaration:n,visitor:t,nodePathForType:a})}}function lac({typeName:e,declaration:t,visitor:r,nodePathForType:i}){let n=L9t(r);r.typeDeclaration?.({typeName:{isInlined:!1,name:e},declaration:t,nodePath:i},i);let a=u=>{if(u!=null)for(let[l,f]of u.entries()){let s=[...i,{key:"examples",arrayIndex:l}];r.exampleType?.({typeName:e,typeDeclaration:t,example:f},s),mRe({example:f.value,nodePath:s,visitor:r})}};dF(t,{alias:u=>{typeof u=="string"?n(u,i):aw(u,{type:l=>{n(l,[...i,"type"])},docs:tT(r,i),availability:Go,audiences:Go,examples:a,validation:Go,encoding:Go,source:Go,inline:Go})},object:u=>{aw(u,{docs:tT(r,i),extends:l=>{if(l==null)return;let f=typeof l=="string"?[l]:l;for(let s of f){let o=[...i,"extends",s];r.extension?.(s,o),n(s,o)}},properties:l=>{if(l!=null)for(let[f,s]of Object.entries(l)){let o=[...i,"properties",f];typeof s=="string"?n(s,o):aw(s,{name:Go,docs:tT(r,o),availability:Go,type:c=>{n(c,[...o,"type"],{_default:s.default,validation:s.validation})},audiences:Go,encoding:Go,default:Go,validation:Go,access:Go})}},"extra-properties":Go,availability:Go,audiences:Go,encoding:Go,source:Go,examples:a,inline:Go})},discriminatedUnion:u=>{aw(u,{docs:tT(r,i),discriminant:Go,extends:l=>{if(l==null)return;let f=typeof l=="string"?[l]:l;for(let s of f){let o=[...i,"extends",s];r.extension?.(s,o),n(s,o)}},union:l=>{for(let[f,s]of Object.entries(l)){let o=[...i,"union",f];typeof s=="string"?n(s,o):aw(s,{docs:tT(r,o),name:Go,key:Go,type:c=>{typeof c=="string"&&n(c,[...i,"type"])},"display-name":Go,availability:Go})}},"base-properties":Go,availability:Go,audiences:Go,encoding:Go,source:Go,examples:a,inline:Go})},undiscriminatedUnion:u=>{aw(u,{docs:tT(r,i),discriminated:Go,union:l=>{for(let[f,s]of l.entries()){let o=[...i,`union[${f}]`];typeof s!="string"&&aw(s,{docs:tT(r,o),type:c=>{n(c,[...i,"type"])},"display-name":Go,validation:Go})}},availability:Go,audiences:Go,encoding:Go,source:Go,examples:a,inline:Go})},enum:u=>{aw(u,{docs:tT(r,i),enum:l=>{for(let f of l){let s=[...i,typeof f=="string"?f:f.name??f.value];typeof f!="string"&&aw(f,{docs:tT(r,s),name:Go,value:Go,casing:Go})}},availability:Go,audiences:Go,default:Go,encoding:Go,source:Go,examples:a,inline:Go})}})}function bb_({errorDeclarations:e,visitor:t,nodePath:r}){if(e!=null)for(let[i,n]of Object.entries(e)){let a=[...r,i];t.errorDeclaration?.({errorName:i,declaration:n},a),FcE({errorName:i,declaration:n,visitor:t,nodePathForError:a})}}function FcE({errorName:e,declaration:t,visitor:r,nodePathForError:i}){let n=L9t(r);typeof t=="string"?n(t,i):aw(t,{docs:tT(r,i),"status-code":Go,type:a=>{if(a==null)return;let u=[...i,"type"];typeof a=="string"?n(a,u):lac({typeName:e,declaration:a,visitor:r,nodePathForType:u})},examples:a=>{if(a!=null)for(let u of a){let l=[...i,"type"];r.exampleError?.({errorName:e,declaration:t,example:u},l)}}})}function gb_({imports:e,visitor:t,nodePath:r}){if(e!=null)for(let[i,n]of Object.entries(e))t.import?.({importPath:n,importedAs:i},[...r,i])}function Ob_({webhook:e,visitor:t,nodePathForWebhook:r}){let i=L9t(t);aw(e,{"display-name":Go,method:Go,examples:Go,headers:n=>{LcE({headers:n,visitor:t,nodePath:[...r,"headers"]})},payload:n=>{let a=[...r,"payload"];if(typeof n=="string"){i(n,a,{location:"requestReference"});return}if(UcE(n)){i(n.type,[...a,"type"],{location:"requestReference"});return}let u=[...a];t.typeDeclaration?.({typeName:{isInlined:!0,location:"inlinedRequest"},declaration:n},u),aw(n,{name:Go,extends:l=>{if(l==null)return;let f=typeof l=="string"?[l]:l;for(let s of f){let o=[...u,"extends",s];t.extension?.(s,o),i(s,o)}},properties:l=>{if(l!=null)for(let[f,s]of Object.entries(l)){let o=[...u,"properties",f];typeof s=="string"?i(s,o,{location:s9.InlinedRequestProperty}):aw(s,{name:Go,docs:tT(t,o),availability:Go,type:c=>{i(c,[...o,"type"],{_default:s.default,validation:s.validation,location:s9.InlinedRequestProperty})},audiences:Go,encoding:Go,default:Go,validation:Go,access:Go})}}})},audiences:Go,availability:Go,docs:tT(t,r)})}function LcE({headers:e,visitor:t,nodePath:r}){if(e==null)return;let i=L9t(t);for(let[n,a]of Object.entries(e)){let u=[...r,n];t.header?.({headerKey:n,header:a},u),typeof a=="string"?i(a,u):aw(a,{name:Go,availability:Go,type:l=>{i(l,u,{_default:a.default,validation:a.validation})},docs:tT(t,u),audiences:Go,encoding:Go,env:Go,default:Go,validation:Go})}}function UcE(e){return e.type!=null}function ZV(e,t){aw(e,{docs:tT(t,[]),imports:r=>{gb_({imports:r,visitor:t,nodePath:["imports"]})},types:r=>{vb_({typeDeclarations:r,visitor:t,nodePath:["types"]})},service:r=>{r!=null&&hb_({service:r,visitor:t,nodePath:["service"]})},webhooks:r=>{for(let[i,n]of Object.entries(r??{}))Ob_({webhook:n,visitor:t,nodePathForWebhook:["webhooks",i]})},channel:Go,errors:r=>{bb_({errorDeclarations:r,visitor:t,nodePath:["errors"]})}})}function fac(e,t){aw(e,{docs:Go,imports:Go,types:Go,service:Go,webhooks:Go,errors:Go,channel:Go,export:r=>{t.export?.(typeof r=="string"?r:r?.dependency,["export"])},navigation:r=>{t.navigation?.(r,["navigation"])}})}function dac(e,t){t.file?.(e,[]),aw(e,{version:Go,name:Go,"default-url":Go,"display-name":Go,imports:Go,auth:Go,"idempotency-headers":Go,"auth-schemes":r=>Object.entries(r??{}).map(([i,n])=>{vjs(n)&&t.oauth?.({name:i,oauth:n},["auth-scheme",i])}),pagination:Go,"default-environment":r=>{t.defaultEnvironment?.(r,["default-environment"])},docs:Go,headers:Go,environments:r=>{if(r!=null)for(let[i,n]of Object.entries(r))t.environment?.({environmentId:i,environment:n},["environments",i])},"error-discrimination":r=>{t.errorDiscrimination?.(r,["error-discrimination"])},audiences:Go,errors:r=>{if(r!=null)for(let i of r)t.errorReference?.(i,["errors",i])},"base-path":Go,"path-parameters":r=>{Dga({pathParameters:r,visitor:t,nodePath:["path-parameters"]})},variables:r=>{if(r!=null)for(let[i,n]of Object.entries(r))t.variableDeclaration?.({variableId:i,variable:n},["variables",i])}})}var k2o=new RegExp("^[a-zA-Z][a-zA-Z0-9_]*$");function mb_({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:i}){function n(a){let u=(l,f)=>{for(let s of r){let o=s.definitionFile?.[a];if(o!=null){let c=o(l,{relativeFilepath:e,contents:t});i(c.map(b=>({severity:b.severity,relativeFilepath:e,nodePath:f,message:b.message})))}}};return{[a]:u}}return{...n("docs"),...n("import"),...n("typeReference"),...n("typeDeclaration"),...n("typeName"),...n("httpService"),...n("httpEndpoint"),...n("pathParameter"),...n("queryParameter"),...n("streamCondition"),...n("header"),...n("errorDeclaration"),...n("errorReference"),...n("exampleType"),...n("exampleTypeReference"),...n("exampleHttpEndpointCall"),...n("exampleCodeSample"),...n("exampleHeaders"),...n("examplePathParameters"),...n("exampleQueryParameters"),...n("exampleRequest"),...n("exampleResponse"),...n("variableReference"),...n("extension"),...n("serviceBaseUrl"),...n("endpointBaseUrl"),...n("exampleError")}}function Pb_({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:i}){function n(a){let u=(l,f)=>{for(let s of r){let o=s.packageMarker?.[a];if(o!=null){let c=o(l,{relativeFilepath:e,contents:t});i(c.map(b=>({severity:b.severity,relativeFilepath:e,nodePath:f,message:b.message})))}}};return{[a]:u}}return{...n("export"),...n("navigation")}}function jb_({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:i}){function n(a){let u=(l,f)=>{for(let s of r){let o=s.rootApiFile?.[a];if(o!=null){let c=o(l,{relativeFilepath:e,contents:t});i(c.map(b=>({severity:b.severity,relativeFilepath:e,nodePath:f,message:b.message})))}}};return{[a]:u}}return{...n("file"),...n("oauth"),...n("defaultEnvironment"),...n("environment"),...n("errorDiscrimination"),...n("errorReference"),...n("variableDeclaration"),...n("variableReference"),...n("pathParameter")}}var pac={name:"content-type-only-for-multipart",DISABLE_RULE:!1,create:()=>({definitionFile:{httpEndpoint:({endpoint:e})=>{if(e.request==null)return[];if(Bxi(e.request)!=null)return[];if(typeof e.request!="string"&&e.request.body!=null&&oC(e.request.body)){let r=[];for(let[i,n]of Object.entries(e.request.body.properties??{}))typeof n!="string"&&n["content-type"]!=null&&r.push({severity:"fatal",message:`${i} has content-type, but the request is not multipart`});return r}return[]}}})};var _S=BDe({generationLanguage:void 0,keywords:void 0,smartCasing:!1});var _ac={name:"exploded-form-data-is-array",create:({workspace:e})=>{let t=new h1(e);return{definitionFile:{httpEndpoint:({endpoint:r},{relativeFilepath:i,contents:n})=>{if(r.request==null||typeof r.request=="string"||r.request?.body==null||typeof r.request.body=="string")return[];if(!VcE(r.request.body))return[];let a=[];for(let[u,l]of Object.entries(r.request.body.properties??{})){if(typeof l=="string"||l.style!=="exploded")continue;let f=r0({relativeFilepath:i,definitionFile:n,casingsGenerator:_S,rootApiFile:e.definition.rootApiFile.contents}),s=t.resolveType({type:l.type,file:f});if(s==null)return[];wb_(s)||a.push({message:`${u} is exploded and must be a list. Did you mean list<${l.type}>?`,severity:"error"})}return a}}}}};function wb_(e){return e._type!=="container"?!1:e.container._type==="list"?!0:e.container._type==="optional"||e.container._type==="nullable"?wb_(e.container.itemType):!1}function VcE(e){return e?.properties!=null}var hac={name:"import-file-exists",create:({workspace:e})=>{let t=Object.keys(kKr(e.definition)),r=new Set;return t.forEach(i=>{let n=Lu(e.definition.absoluteFilePath,Xa.of(i));r.add(n)}),{definitionFile:{import:({importedAs:i,importPath:n},{relativeFilepath:a})=>{let u=[],l=Lu(e.definition.absoluteFilePath,Zd(a),Xa.of(n));return r.has(l)||u.push({severity:"fatal",message:`Import ${Ws.bold(i)} points to non-existent path ${Ws.bold(n)}.`}),u}}}}};function e4o(e){return e.definition.rootApiFile.contents.environments==null?[]:Object.values(e.definition.rootApiFile.contents.environments).reduce((t,r)=>{if(H0n(r))for(let i of Object.keys(r.urls))t.includes(i)||t.push(i);return t},[])}var yac={name:"matching-environment-urls",create:({workspace:e})=>{let t=e4o(e);return t.length===0?{}:{rootApiFile:{environment:({environmentId:r,environment:i})=>{let n=[],a=u=>{n.push({severity:"fatal",message:`Environment ${r} is missing URL for ${Ws.bold(u)}`})};return XQr(i,{singleBaseUrl:()=>{for(let u of t)a(u)},multipleBaseUrls:u=>{for(let l of t)u.urls[l]==null&&a(l)}}),n}}}}};var vac={name:"no-circular-imports",DISABLE_RULE:!0,create:({workspace:e})=>{let t=WcE(e.definition.namedDefinitionFiles);return{definitionFile:{import:({importPath:r},{relativeFilepath:i})=>{let n=t[i];if(n==null)return[];let a=F_i({referencedIn:i,importPath:Xa.of(r)});return n.filter(({chainWithoutStartingFilepath:l})=>l.length===0||l[0]===a).map(l=>({severity:"fatal",message:l.chainWithoutStartingFilepath.length===0?"A file cannot import itself":`Circular import detected: ${[l.startingFilepath,...l.chainWithoutStartingFilepath,l.startingFilepath].join(" -> ")}`}))}}}}};function WcE(e){let t={};for(let r of k4t(e))t[r]=Sb_(r,[r],e);return t}function Sb_(e,t,r){let i=[],n=r[e];if(n==null)return[];if(n.contents.imports!=null)for(let a of Object.values(n.contents.imports)){let u=F_i({referencedIn:e,importPath:Xa.of(a)});t.includes(u)?t[0]===u&&t[0]===HcE(t)&&i.push({startingFilepath:u,chainWithoutStartingFilepath:t.slice(1)}):i.push(...Sb_(u,[...t,u],r))}return i}function HcE(e){return e.reduce((t,r)=>r<t?r:t)}var t4o=class{workspace;typeResolver;constructor(t){this.workspace=t,this.typeResolver=new h1(t)}isTypeComplex(t,r){let i=r0({relativeFilepath:r.relativeFilepath,definitionFile:r.contents,casingsGenerator:_S,rootApiFile:this.workspace.definition.rootApiFile.contents}),n=this.typeResolver.resolveType({type:t,file:i});if(n==null)return;let a=new Set;return this.isResolvedReferenceComplex({type:n,file:i,visited:a})}isResolvedReferenceComplex({type:t,file:r,visited:i}){switch(t._type){case"container":return this.isResolvedContainerComplex({type:t.container,file:r,visited:i});case"named":return this.isNamedTypeComplex({type:t,file:r,visited:i});case"primitive":return!1;case"unknown":return!0;default:Mo(t)}}isResolvedContainerComplex({type:t,file:r,visited:i}){switch(t._type){case"literal":return!1;case"map":return(this.isResolvedReferenceComplex({type:t.keyType,file:r,visited:i})||this.isResolvedReferenceComplex({type:t.valueType,file:r,visited:i}))&&!(t.keyType._type==="primitive"&&t.keyType.primitive.v1==="STRING"&&t.valueType._type==="unknown");case"optional":case"nullable":case"list":case"set":return this.isResolvedReferenceComplex({type:t.itemType,file:r,visited:i});default:Mo(t)}}isNamedTypeComplex({type:t,file:r,visited:i}){if(i.has(t.rawName))return!1;if(i.add(t.rawName),Lci(t.declaration))return!0;if($8t(t.declaration))return!1;if(cS(t.declaration))return this.objectHasComplexProperties({typeName:t.rawName,objectDeclaration:t.declaration,file:r,visited:i});if(G0n(t.declaration)){for(let n of t.declaration.union){let a=typeof n=="string"?n:n.type,u=this.isTypeComplex(a,{contents:r.definitionFile,relativeFilepath:r.relativeFilepath});if(u!=null&&u)return!0}return!1}Mo(t.declaration)}objectHasComplexProperties({typeName:t,objectDeclaration:r,file:i,visited:n}){return x9t({typeName:t,objectDeclaration:r,typeResolver:this.typeResolver,definitionFile:i.definitionFile,workspace:this.workspace,filepathOfDeclaration:i.relativeFilepath,smartCasing:!1}).some(u=>this.isComplex({type:u.resolvedPropertyType,file:i,visited:n}))}isComplex({type:t,file:r,visited:i}){switch(t._type){case"named":return this.isNamedTypeComplex({type:t,file:r,visited:i});case"primitive":case"unknown":return!1;case"container":return this.isComplexContainer({type:t.container,file:r,visited:i});default:Mo(t)}}isComplexContainer({type:t,file:r,visited:i}){switch(t._type){case"literal":return!1;case"map":return this.isComplex({type:t.keyType,file:r,visited:i})||this.isComplex({type:t.valueType,file:r,visited:i});case"optional":case"nullable":case"list":case"set":return this.isComplex({type:t.itemType,file:r,visited:i});default:Mo(t)}}};var bac={name:"no-complex-query-params",create:({workspace:e})=>{let t=new t4o(e);return{definitionFile:{queryParameter:({queryParameter:r},i)=>{let n=typeof r=="string"?r:r.type,a=t.isTypeComplex(n,i);return a!=null&&a?[{severity:"fatal",message:`${n} is not a valid type for a query parameter`}]:[]}}}}};var gac={name:"no-conflicting-endpoint-parameters",create:()=>({definitionFile:{pathParameter:({pathParameterKey:e})=>e===g7o?[{severity:"fatal",message:`Path parameter ${Ws.bold(e)} is not suitable for code generation, because it can conflict with the request body parameter.`}]:[]}})};function Ega({service:e,endpoint:t}){return e["base-path"]+t.path}var r4o=class{root=new Oac;registerEndpoint(t){this.root.insert(this.getPathPartsForEndpoint(t),t)}getConflictingEndpoints(t){return this.root.getMatchingEndpoints(this.getPathPartsForEndpoint(t)).filter(r=>!(r.relativeFilepath===t.relativeFilepath&&r.endpointId===t.endpointId)&&r.endpoint.method===t.endpoint.method)}getPathPartsForEndpoint(t){return Ega({service:t.service,endpoint:t.endpoint}).split("/").filter(r=>r.length>0)}},Oac=class e{childPaths={};childPathParam;endpointsThatEndWithThisNode=[];insert(t,r){let[i,...n]=t;if(i==null){this.endpointsThatEndWithThisNode.push(r);return}(this.isPathParam(i)?this.childPathParam??=new e:this.childPaths[i]??=new e).insert(n,r)}getMatchingEndpoints(t){let[r,...i]=t;if(r==null)return this.endpointsThatEndWithThisNode;let n=[];if(this.isPathParam(r))n.push(...Object.values(this.childPaths).flatMap(a=>a.getMatchingEndpoints(i)));else{let a=this.childPaths[r];a!=null&&n.push(...a.getMatchingEndpoints(i))}return this.childPathParam!=null&&n.push(...this.childPathParam.getMatchingEndpoints(i)),n}isPathParam(t){return t.startsWith("{")&&t.endsWith("}")}};var mac={name:"no-conflicting-endpoint-paths",create:({workspace:e})=>{let t=new r4o;return AF(e,(r,i)=>{ZV(i,{httpEndpoint:({service:n,endpointId:a,endpoint:u})=>{t.registerEndpoint({service:n,endpointId:a,endpoint:u,relativeFilepath:r})}})}),{definitionFile:{httpEndpoint:({service:r,endpoint:i,endpointId:n},{relativeFilepath:a})=>{let u=t.getConflictingEndpoints({service:r,endpointId:n,endpoint:i,relativeFilepath:a});return u.length===0?[]:[{severity:"warning",message:[`Endpoint path ${Ega({service:r,endpoint:i})} conflicts with other endpoints:`,...u.map(l=>` - ${l.relativeFilepath} -> ${l.endpointId} ${Ws.dim(Ega({service:l.service,endpoint:l.endpoint}))}`)].join(`
|
|
2031
|
+
`)}function McE(e){return e.some(t=>t.severity==="fatal")?"fatal":e.some(t=>t.severity==="error")?"error":"warning"}function AcE(e){switch(e){case"fatal":return G0.Error;case"error":return G0.Error;case"warning":return G0.Warn;default:Mo(e)}}function qcE({stats:e,context:t,logWarnings:r,elapsedMillis:i=0}){let{numFatal:n,numErrors:a,numWarnings:u}=e,l=i>0?` in ${(i/1e3).toFixed(3)} seconds.`:".",f=`Found ${n+a} errors and ${u} warnings`+l;!r&&u>0&&(f+=" Run fern check --warnings to print out the warnings not shown."),n+a>0?t.logger.error(f):u>0?t.logger.warn(f):t.logger.info(Ws.green("\u2713 All checks passed"))}function TcE(e){let t=0,r=0,i=0;for(let n of e)switch(n.severity){case"fatal":t+=1;continue;case"error":r+=1;continue;case"warning":i+=1;continue;default:Mo(n.severity)}return{numFatal:t,numErrors:r,numWarnings:i}}async function OAn({workspace:e,apiWorkspaces:t,ossWorkspaces:r,context:i,logWarnings:n,errorOnBrokenLinks:a,logSummary:u=!0,excludeRules:l}){let f=performance.now(),s=await wga(e,i,t,r,!1,l),o=performance.now()-f,{hasErrors:c}=gAn({violations:s,context:i,logWarnings:n,logSummary:u,logBreadcrumbs:!1,elapsedMillis:o});return a&&(c=c||s.some(b=>b.name==="valid-markdown-links")),{hasErrors:c}}async function Z2o({workspace:e,apiWorkspaces:t,ossWorkspaces:r,context:i,logWarnings:n,errorOnBrokenLinks:a,excludeRules:u}){let{hasErrors:l}=await OAn({workspace:e,context:i,logWarnings:n,apiWorkspaces:t,ossWorkspaces:r,errorOnBrokenLinks:a,excludeRules:u});l&&i.failAndThrow()}var CcE=["cohere","deepgram","chainalysis","devrev","deriv","webflow"];async function fb_({loadProject:e,cliContext:t,port:r,bundlePath:i,brokenLinks:n,appPreview:a,legacyPreview:u,backendPort:l}){let f=await e(),s=f.docsWorkspaces;if(s==null)return;let o=CcE.includes(f.config.organization);if(a?o=!1:u&&(o=!0),!o||a){await t.instrumentPostHogEvent({orgId:f.config.organization,command:"fern docs dev --beta"}),await t.runTaskForWorkspace(s,async c=>{c.logger.info(`Starting server on port ${r}`),await snc({initialProject:f,reloadProject:e,validateProject:async b=>{let g=b.docsWorkspaces;if(g==null)return;let O=n?[]:["valid-markdown-links"];g.config.experimental?.openapiParserV3?await OAn({workspace:g,context:c,logWarnings:!0,logSummary:!1,apiWorkspaces:[],ossWorkspaces:await JV(b),excludeRules:O}):await OAn({workspace:g,context:c,logWarnings:!0,logSummary:!1,apiWorkspaces:b.apiWorkspaces,ossWorkspaces:await JV(b),excludeRules:O})},context:c,port:r,bundlePath:i,backendPort:l})});return}await t.instrumentPostHogEvent({orgId:f.config.organization,command:"fern docs dev --legacy"}),await t.runTaskForWorkspace(s,async c=>{c.logger.info(`Starting server on port ${r}`),await unc({initialProject:f,reloadProject:e,validateProject:async b=>{let g=b.docsWorkspaces;if(g==null)return;let O=n?[]:["valid-markdown-links"];g.config.experimental?.openapiParserV3?await OAn({workspace:g,context:c,logWarnings:!0,logSummary:!1,apiWorkspaces:[],ossWorkspaces:await JV(b),excludeRules:O}):await OAn({workspace:g,context:c,logWarnings:!0,logSummary:!1,apiWorkspaces:b.apiWorkspaces,ossWorkspaces:await JV(b),excludeRules:O})},context:c,port:r,bundlePath:i})})}async function db_({project:e,cliContext:t,shouldFix:r}){await Promise.all(e.apiWorkspaces.map(async i=>{i instanceof nN||await t.runTaskForWorkspace(i,async n=>{await WRs({workspace:await i.toFernWorkspace({context:n}),context:n,shouldFix:r})})}))}var p0_=li(require("path"),1);var d0_=li(_b_(),1);var s9={RequestReference:"requestReference",InlinedRequestProperty:"inlinedRequestProperty",Response:"response",StreamingResponse:"streamingResponse"};function tT(e,t){return r=>{r!=null&&e.docs?.(r,[...t,"docs"])}}function mRe({example:e,visitor:t,nodePath:r}){if(typeof e=="string")e.startsWith(fJt)&&t.exampleTypeReference?.(e,r);else if(mj(e))for(let i of Object.values(e))mRe({example:i,visitor:t,nodePath:r});else if(Array.isArray(e))for(let i of e)mRe({example:i,visitor:t,nodePath:r})}function L9t(e){return(t,r,{_default:i,validation:n,location:a}={})=>{e.typeReference?.({typeReference:t,_default:i,validation:n,location:a,nodePath:r},r)}}function hb_({service:e,visitor:t,nodePath:r}){t.httpService?.(e,r),aw(e,{url:i=>{t.serviceBaseUrl?.(i,[...r,"url"])},"base-path":Go,"display-name":Go,availability:Go,headers:i=>{yb_({headers:i,visitor:t,nodePath:[...r,"headers"]})},audiences:Go,auth:Go,"path-parameters":i=>{Dga({pathParameters:i,visitor:t,nodePath:[...r,"path-parameters"]})},endpoints:i=>{for(let[n,a]of Object.entries(i)){let u=[...r,"endpoints",n];RcE({endpointId:n,endpoint:a,service:e,visitor:t,nodePathForEndpoint:u})}},idempotent:Go,transport:Go,source:Go})}function RcE({endpointId:e,endpoint:t,service:r,visitor:i,nodePathForEndpoint:n}){let a=L9t(i);i.httpEndpoint?.({endpointId:e,endpoint:t,service:r},n),aw(t,{docs:tT(i,n),"display-name":Go,availability:Go,"base-path":Go,path:Go,idempotent:Go,url:u=>{i.endpointBaseUrl?.({baseUrl:u,service:r},[...n,"url"])},"path-parameters":u=>{Dga({pathParameters:u,visitor:i,nodePath:[...n,"path-parameters"]})},request:u=>{if(u==null)return;let l=[...n,"request"];if(typeof u=="string"){a(u,l,{location:"requestReference"});return}aw(u,{name:Go,docs:tT(i,l),"path-parameters":f=>{Dga({pathParameters:f,visitor:i,nodePath:[...l,"path-parameters"]})},"query-parameters":f=>{if(f!=null)for(let[s,o]of Object.entries(f)){let c=[...l,"query-parameters",s];i.queryParameter?.({queryParameterKey:s,queryParameter:o},c),typeof o=="string"?a(o,c):aw(o,{name:Go,docs:tT(i,c),availability:Go,type:b=>{a(b,[...c,"type"],{_default:o.default,validation:o.validation})},"allow-multiple":Go,audiences:Go,encoding:Go,default:Go,validation:Go})}},"content-type":Go,headers:f=>{yb_({headers:f,visitor:i,nodePath:[...l,"headers"]})},body:f=>{if(f==null)return;let s=[...l,"body"];typeof f=="string"?a(f,s,{location:"requestReference"}):oC(f)?(i.typeDeclaration?.({typeName:{isInlined:!0,location:"inlinedRequest"},declaration:f},s),aw(f,{extends:o=>{if(o==null)return;let c=typeof o=="string"?[o]:o;for(let b of c){let g=[...s,"extends",b];i.extension?.(b,g),a(b,g)}},properties:o=>{if(o!=null)for(let[c,b]of Object.entries(o)){let g=[...s,"properties",c];typeof b=="string"?a(b,g,{location:s9.InlinedRequestProperty}):aw(b,{name:Go,docs:tT(i,g),availability:Go,type:O=>{a(O,[...g,"type"],{location:s9.InlinedRequestProperty,_default:b.default,validation:b.validation})},style:Go,"content-type":Go,audiences:Go,encoding:Go,default:Go,validation:Go})}},"extra-properties":Go})):(tT(i,s)(f.docs),a(f.type,s))}})},audiences:Go,method:Go,auth:Go,"stream-condition":u=>{i.streamCondition?.({streamCondition:u,endpoint:t},[...n,"stream-condition"])},"response-stream":u=>{u!=null&&(typeof u=="string"?a(u,[...n,"response-stream"],{location:s9.StreamingResponse}):a(u.type,[...n,"response-stream"],{location:s9.StreamingResponse}))},response:u=>{if(u==null)return;let l=[...n,"response"];typeof u=="string"?a(u,l,{location:s9.Response}):aw(u,{docs:tT(i,l),type:f=>{f!=null&&a(f,[...l,"type"],{location:s9.Response})},property:Go,"status-code":Go})},errors:u=>{if(u!=null)for(let l of u){let f=[...n,"errors",typeof l=="string"?l:l.error];typeof l=="string"?i.errorReference?.(l,f):aw(l,{docs:tT(i,f),error:s=>{i.errorReference?.(s,[...f,"error"])}})}},examples:u=>{if(u!=null)for(let[l,f]of u.entries())NcE({nodePathForExample:[...n,{key:"examples",arrayIndex:l}],visitor:i,service:r,endpoint:t,example:f})},pagination:Go,source:Go,transport:Go})}function NcE({nodePathForExample:e,visitor:t,service:r,endpoint:i,example:n}){if(n.headers==null&&n["path-parameters"]==null&&n["query-parameters"]==null&&n.request==null&&n.response==null&&n["code-samples"]!=null)return;t.exampleHttpEndpointCall?.({service:r,endpoint:i,example:n},e);let a=[...e,"headers"];if(t.exampleHeaders?.({service:r,endpoint:i,examples:n.headers},a),n.headers!=null)for(let o of Object.values(n.headers))mRe({example:o,visitor:t,nodePath:a});let u=[...e,"path-parameters"];if(t.examplePathParameters?.({service:r,endpoint:i,examples:n["path-parameters"]},u),n["path-parameters"]!=null)for(let o of Object.values(n["path-parameters"]))mRe({example:o,visitor:t,nodePath:u});let l=[...e,"query-parameters"];if(t.exampleQueryParameters?.({service:r,endpoint:i,examples:n["query-parameters"]},l),n["query-parameters"]!=null)for(let o of Object.values(n["query-parameters"]))mRe({example:o,visitor:t,nodePath:l});let f=[...e,"request"];t.exampleRequest?.({service:r,endpoint:i,example:n.request},f),n.request!=null&&mRe({example:n.request,visitor:t,nodePath:f});let s=[...e,"response"];if(t.exampleResponse?.({service:r,endpoint:i,example:n.response},s),n.response!=null&&xxi(i,n.response,{body:o=>{o.body!=null&&mRe({example:o.body,visitor:t,nodePath:s}),o.error!=null&&t.errorReference?.(o.error,[...s,"error"])},stream:o=>{for(let c of o.stream)mRe({example:c,visitor:t,nodePath:s})},events:o=>{for(let{data:c}of o.stream)mRe({example:c,visitor:t,nodePath:s})}}),n["code-samples"]!=null)for(let[o,c]of n["code-samples"].entries())t.exampleCodeSample?.({service:r,endpoint:i,example:n,sample:c},[...e,{key:"code-samples",arrayIndex:o}])}function Dga({pathParameters:e,visitor:t,nodePath:r}){if(e==null)return;let i=L9t(t);for(let[n,a]of Object.entries(e)){let u=[...r,n];t.pathParameter?.({pathParameterKey:n,pathParameter:a},u),$0n(a)?typeof a=="string"?t.variableReference?.(a,u):aw(a,{docs:tT(t,u),variable:l=>t.variableReference?.(l,[...u,"variable"]),availability:Go}):typeof a=="string"?i(a,u):aw(a,{docs:tT(t,u),type:l=>{i(l,[...u,"type"],{_default:a.default,validation:a.validation})},availability:Go,encoding:Go,default:Go,validation:Go,name:Go,audiences:Go})}}function yb_({headers:e,visitor:t,nodePath:r}){if(e==null)return;let i=L9t(t);for(let[n,a]of Object.entries(e)){let u=[...r,n];t.header?.({headerKey:n,header:a},u),typeof a=="string"?i(a,u):aw(a,{name:Go,availability:Go,type:l=>{i(l,u,{_default:a.default,validation:a.validation})},docs:tT(t,u),audiences:Go,encoding:Go,env:Go,default:Go,validation:Go})}}function vb_({typeDeclarations:e,visitor:t,nodePath:r}){if(e!=null)for(let[i,n]of Object.entries(e)){let a=[...r,i];t.typeName?.(i,a),lac({typeName:i,declaration:n,visitor:t,nodePathForType:a})}}function lac({typeName:e,declaration:t,visitor:r,nodePathForType:i}){let n=L9t(r);r.typeDeclaration?.({typeName:{isInlined:!1,name:e},declaration:t,nodePath:i},i);let a=u=>{if(u!=null)for(let[l,f]of u.entries()){let s=[...i,{key:"examples",arrayIndex:l}];r.exampleType?.({typeName:e,typeDeclaration:t,example:f},s),mRe({example:f.value,nodePath:s,visitor:r})}};dF(t,{alias:u=>{typeof u=="string"?n(u,i):aw(u,{type:l=>{n(l,[...i,"type"])},docs:tT(r,i),availability:Go,audiences:Go,examples:a,validation:Go,encoding:Go,source:Go,inline:Go})},object:u=>{aw(u,{docs:tT(r,i),extends:l=>{if(l==null)return;let f=typeof l=="string"?[l]:l;for(let s of f){let o=[...i,"extends",s];r.extension?.(s,o),n(s,o)}},properties:l=>{if(l!=null)for(let[f,s]of Object.entries(l)){let o=[...i,"properties",f];typeof s=="string"?n(s,o):aw(s,{name:Go,docs:tT(r,o),availability:Go,type:c=>{n(c,[...o,"type"],{_default:s.default,validation:s.validation})},audiences:Go,encoding:Go,default:Go,validation:Go,access:Go})}},"extra-properties":Go,availability:Go,audiences:Go,encoding:Go,source:Go,examples:a,inline:Go})},discriminatedUnion:u=>{aw(u,{docs:tT(r,i),discriminant:Go,extends:l=>{if(l==null)return;let f=typeof l=="string"?[l]:l;for(let s of f){let o=[...i,"extends",s];r.extension?.(s,o),n(s,o)}},union:l=>{for(let[f,s]of Object.entries(l)){let o=[...i,"union",f];typeof s=="string"?n(s,o):aw(s,{docs:tT(r,o),name:Go,key:Go,type:c=>{typeof c=="string"&&n(c,[...i,"type"])},"display-name":Go,availability:Go})}},"base-properties":Go,availability:Go,audiences:Go,encoding:Go,source:Go,examples:a,inline:Go})},undiscriminatedUnion:u=>{aw(u,{docs:tT(r,i),discriminated:Go,union:l=>{for(let[f,s]of l.entries()){let o=[...i,`union[${f}]`];typeof s!="string"&&aw(s,{docs:tT(r,o),type:c=>{n(c,[...i,"type"])},"display-name":Go,validation:Go})}},availability:Go,audiences:Go,encoding:Go,source:Go,examples:a,inline:Go})},enum:u=>{aw(u,{docs:tT(r,i),enum:l=>{for(let f of l){let s=[...i,typeof f=="string"?f:f.name??f.value];typeof f!="string"&&aw(f,{docs:tT(r,s),name:Go,value:Go,casing:Go})}},availability:Go,audiences:Go,default:Go,encoding:Go,source:Go,examples:a,inline:Go})}})}function bb_({errorDeclarations:e,visitor:t,nodePath:r}){if(e!=null)for(let[i,n]of Object.entries(e)){let a=[...r,i];t.errorDeclaration?.({errorName:i,declaration:n},a),FcE({errorName:i,declaration:n,visitor:t,nodePathForError:a})}}function FcE({errorName:e,declaration:t,visitor:r,nodePathForError:i}){let n=L9t(r);typeof t=="string"?n(t,i):aw(t,{docs:tT(r,i),"status-code":Go,type:a=>{if(a==null)return;let u=[...i,"type"];typeof a=="string"?n(a,u):lac({typeName:e,declaration:a,visitor:r,nodePathForType:u})},examples:a=>{if(a!=null)for(let u of a){let l=[...i,"type"];r.exampleError?.({errorName:e,declaration:t,example:u},l)}}})}function gb_({imports:e,visitor:t,nodePath:r}){if(e!=null)for(let[i,n]of Object.entries(e))t.import?.({importPath:n,importedAs:i},[...r,i])}function Ob_({webhook:e,visitor:t,nodePathForWebhook:r}){let i=L9t(t);aw(e,{"display-name":Go,method:Go,examples:Go,headers:n=>{LcE({headers:n,visitor:t,nodePath:[...r,"headers"]})},payload:n=>{let a=[...r,"payload"];if(typeof n=="string"){i(n,a,{location:"requestReference"});return}if(UcE(n)){i(n.type,[...a,"type"],{location:"requestReference"});return}let u=[...a];t.typeDeclaration?.({typeName:{isInlined:!0,location:"inlinedRequest"},declaration:n},u),aw(n,{name:Go,extends:l=>{if(l==null)return;let f=typeof l=="string"?[l]:l;for(let s of f){let o=[...u,"extends",s];t.extension?.(s,o),i(s,o)}},properties:l=>{if(l!=null)for(let[f,s]of Object.entries(l)){let o=[...u,"properties",f];typeof s=="string"?i(s,o,{location:s9.InlinedRequestProperty}):aw(s,{name:Go,docs:tT(t,o),availability:Go,type:c=>{i(c,[...o,"type"],{_default:s.default,validation:s.validation,location:s9.InlinedRequestProperty})},audiences:Go,encoding:Go,default:Go,validation:Go,access:Go})}}})},audiences:Go,availability:Go,docs:tT(t,r)})}function LcE({headers:e,visitor:t,nodePath:r}){if(e==null)return;let i=L9t(t);for(let[n,a]of Object.entries(e)){let u=[...r,n];t.header?.({headerKey:n,header:a},u),typeof a=="string"?i(a,u):aw(a,{name:Go,availability:Go,type:l=>{i(l,u,{_default:a.default,validation:a.validation})},docs:tT(t,u),audiences:Go,encoding:Go,env:Go,default:Go,validation:Go})}}function UcE(e){return e.type!=null}function ZV(e,t){aw(e,{docs:tT(t,[]),imports:r=>{gb_({imports:r,visitor:t,nodePath:["imports"]})},types:r=>{vb_({typeDeclarations:r,visitor:t,nodePath:["types"]})},service:r=>{r!=null&&hb_({service:r,visitor:t,nodePath:["service"]})},webhooks:r=>{for(let[i,n]of Object.entries(r??{}))Ob_({webhook:n,visitor:t,nodePathForWebhook:["webhooks",i]})},channel:Go,errors:r=>{bb_({errorDeclarations:r,visitor:t,nodePath:["errors"]})}})}function fac(e,t){aw(e,{docs:Go,imports:Go,types:Go,service:Go,webhooks:Go,errors:Go,channel:Go,export:r=>{t.export?.(typeof r=="string"?r:r?.dependency,["export"])},navigation:r=>{t.navigation?.(r,["navigation"])}})}function dac(e,t){t.file?.(e,[]),aw(e,{version:Go,name:Go,"default-url":Go,"display-name":Go,imports:Go,auth:Go,"idempotency-headers":Go,"auth-schemes":r=>Object.entries(r??{}).map(([i,n])=>{vjs(n)&&t.oauth?.({name:i,oauth:n},["auth-scheme",i])}),pagination:Go,"default-environment":r=>{t.defaultEnvironment?.(r,["default-environment"])},docs:Go,headers:Go,environments:r=>{if(r!=null)for(let[i,n]of Object.entries(r))t.environment?.({environmentId:i,environment:n},["environments",i])},"error-discrimination":r=>{t.errorDiscrimination?.(r,["error-discrimination"])},audiences:Go,errors:r=>{if(r!=null)for(let i of r)t.errorReference?.(i,["errors",i])},"base-path":Go,"path-parameters":r=>{Dga({pathParameters:r,visitor:t,nodePath:["path-parameters"]})},variables:r=>{if(r!=null)for(let[i,n]of Object.entries(r))t.variableDeclaration?.({variableId:i,variable:n},["variables",i])}})}var k2o=new RegExp("^[a-zA-Z][a-zA-Z0-9_]*$");function mb_({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:i}){function n(a){let u=(l,f)=>{for(let s of r){let o=s.definitionFile?.[a];if(o!=null){let c=o(l,{relativeFilepath:e,contents:t});i(c.map(b=>({severity:b.severity,relativeFilepath:e,nodePath:f,message:b.message})))}}};return{[a]:u}}return{...n("docs"),...n("import"),...n("typeReference"),...n("typeDeclaration"),...n("typeName"),...n("httpService"),...n("httpEndpoint"),...n("pathParameter"),...n("queryParameter"),...n("streamCondition"),...n("header"),...n("errorDeclaration"),...n("errorReference"),...n("exampleType"),...n("exampleTypeReference"),...n("exampleHttpEndpointCall"),...n("exampleCodeSample"),...n("exampleHeaders"),...n("examplePathParameters"),...n("exampleQueryParameters"),...n("exampleRequest"),...n("exampleResponse"),...n("variableReference"),...n("extension"),...n("serviceBaseUrl"),...n("endpointBaseUrl"),...n("exampleError")}}function Pb_({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:i}){function n(a){let u=(l,f)=>{for(let s of r){let o=s.packageMarker?.[a];if(o!=null){let c=o(l,{relativeFilepath:e,contents:t});i(c.map(b=>({severity:b.severity,relativeFilepath:e,nodePath:f,message:b.message})))}}};return{[a]:u}}return{...n("export"),...n("navigation")}}function jb_({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:i}){function n(a){let u=(l,f)=>{for(let s of r){let o=s.rootApiFile?.[a];if(o!=null){let c=o(l,{relativeFilepath:e,contents:t});i(c.map(b=>({severity:b.severity,relativeFilepath:e,nodePath:f,message:b.message})))}}};return{[a]:u}}return{...n("file"),...n("oauth"),...n("defaultEnvironment"),...n("environment"),...n("errorDiscrimination"),...n("errorReference"),...n("variableDeclaration"),...n("variableReference"),...n("pathParameter")}}var pac={name:"content-type-only-for-multipart",DISABLE_RULE:!1,create:()=>({definitionFile:{httpEndpoint:({endpoint:e})=>{if(e.request==null)return[];if(Bxi(e.request)!=null)return[];if(typeof e.request!="string"&&e.request.body!=null&&oC(e.request.body)){let r=[];for(let[i,n]of Object.entries(e.request.body.properties??{}))typeof n!="string"&&n["content-type"]!=null&&r.push({severity:"fatal",message:`${i} has content-type, but the request is not multipart`});return r}return[]}}})};var _S=BDe({generationLanguage:void 0,keywords:void 0,smartCasing:!1});var _ac={name:"exploded-form-data-is-array",create:({workspace:e})=>{let t=new h1(e);return{definitionFile:{httpEndpoint:({endpoint:r},{relativeFilepath:i,contents:n})=>{if(r.request==null||typeof r.request=="string"||r.request?.body==null||typeof r.request.body=="string")return[];if(!VcE(r.request.body))return[];let a=[];for(let[u,l]of Object.entries(r.request.body.properties??{})){if(typeof l=="string"||l.style!=="exploded")continue;let f=r0({relativeFilepath:i,definitionFile:n,casingsGenerator:_S,rootApiFile:e.definition.rootApiFile.contents}),s=t.resolveType({type:l.type,file:f});if(s==null)return[];wb_(s)||a.push({message:`${u} is exploded and must be a list. Did you mean list<${l.type}>?`,severity:"error"})}return a}}}}};function wb_(e){return e._type!=="container"?!1:e.container._type==="list"?!0:e.container._type==="optional"||e.container._type==="nullable"?wb_(e.container.itemType):!1}function VcE(e){return e?.properties!=null}var hac={name:"import-file-exists",create:({workspace:e})=>{let t=Object.keys(kKr(e.definition)),r=new Set;return t.forEach(i=>{let n=Lu(e.definition.absoluteFilePath,Xa.of(i));r.add(n)}),{definitionFile:{import:({importedAs:i,importPath:n},{relativeFilepath:a})=>{let u=[],l=Lu(e.definition.absoluteFilePath,Zd(a),Xa.of(n));return r.has(l)||u.push({severity:"fatal",message:`Import ${Ws.bold(i)} points to non-existent path ${Ws.bold(n)}.`}),u}}}}};function e4o(e){return e.definition.rootApiFile.contents.environments==null?[]:Object.values(e.definition.rootApiFile.contents.environments).reduce((t,r)=>{if(H0n(r))for(let i of Object.keys(r.urls))t.includes(i)||t.push(i);return t},[])}var yac={name:"matching-environment-urls",create:({workspace:e})=>{let t=e4o(e);return t.length===0?{}:{rootApiFile:{environment:({environmentId:r,environment:i})=>{let n=[],a=u=>{n.push({severity:"fatal",message:`Environment ${r} is missing URL for ${Ws.bold(u)}`})};return XQr(i,{singleBaseUrl:()=>{for(let u of t)a(u)},multipleBaseUrls:u=>{for(let l of t)u.urls[l]==null&&a(l)}}),n}}}}};var vac={name:"no-circular-imports",DISABLE_RULE:!0,create:({workspace:e})=>{let t=WcE(e.definition.namedDefinitionFiles);return{definitionFile:{import:({importPath:r},{relativeFilepath:i})=>{let n=t[i];if(n==null)return[];let a=F_i({referencedIn:i,importPath:Xa.of(r)});return n.filter(({chainWithoutStartingFilepath:l})=>l.length===0||l[0]===a).map(l=>({severity:"fatal",message:l.chainWithoutStartingFilepath.length===0?"A file cannot import itself":`Circular import detected: ${[l.startingFilepath,...l.chainWithoutStartingFilepath,l.startingFilepath].join(" -> ")}`}))}}}}};function WcE(e){let t={};for(let r of k4t(e))t[r]=Sb_(r,[r],e);return t}function Sb_(e,t,r){let i=[],n=r[e];if(n==null)return[];if(n.contents.imports!=null)for(let a of Object.values(n.contents.imports)){let u=F_i({referencedIn:e,importPath:Xa.of(a)});t.includes(u)?t[0]===u&&t[0]===HcE(t)&&i.push({startingFilepath:u,chainWithoutStartingFilepath:t.slice(1)}):i.push(...Sb_(u,[...t,u],r))}return i}function HcE(e){return e.reduce((t,r)=>r<t?r:t)}var t4o=class{workspace;typeResolver;constructor(t){this.workspace=t,this.typeResolver=new h1(t)}isTypeComplex(t,r){let i=r0({relativeFilepath:r.relativeFilepath,definitionFile:r.contents,casingsGenerator:_S,rootApiFile:this.workspace.definition.rootApiFile.contents}),n=this.typeResolver.resolveType({type:t,file:i});if(n==null)return;let a=new Set;return this.isResolvedReferenceComplex({type:n,file:i,visited:a})}isResolvedReferenceComplex({type:t,file:r,visited:i}){switch(t._type){case"container":return this.isResolvedContainerComplex({type:t.container,file:r,visited:i});case"named":return this.isNamedTypeComplex({type:t,file:r,visited:i});case"primitive":return!1;case"unknown":return!0;default:Mo(t)}}isResolvedContainerComplex({type:t,file:r,visited:i}){switch(t._type){case"literal":return!1;case"map":return(this.isResolvedReferenceComplex({type:t.keyType,file:r,visited:i})||this.isResolvedReferenceComplex({type:t.valueType,file:r,visited:i}))&&!(t.keyType._type==="primitive"&&t.keyType.primitive.v1==="STRING"&&t.valueType._type==="unknown");case"optional":case"nullable":case"list":case"set":return this.isResolvedReferenceComplex({type:t.itemType,file:r,visited:i});default:Mo(t)}}isNamedTypeComplex({type:t,file:r,visited:i}){if(i.has(t.rawName))return!1;if(i.add(t.rawName),Lci(t.declaration))return!0;if($8t(t.declaration))return!1;if(cS(t.declaration))return this.objectHasComplexProperties({typeName:t.rawName,objectDeclaration:t.declaration,file:r,visited:i});if(G0n(t.declaration)){for(let n of t.declaration.union){let a=typeof n=="string"?n:n.type,u=this.isTypeComplex(a,{contents:r.definitionFile,relativeFilepath:r.relativeFilepath});if(u!=null&&u)return!0}return!1}Mo(t.declaration)}objectHasComplexProperties({typeName:t,objectDeclaration:r,file:i,visited:n}){return x9t({typeName:t,objectDeclaration:r,typeResolver:this.typeResolver,definitionFile:i.definitionFile,workspace:this.workspace,filepathOfDeclaration:i.relativeFilepath,smartCasing:!1}).some(u=>this.isComplex({type:u.resolvedPropertyType,file:i,visited:n}))}isComplex({type:t,file:r,visited:i}){switch(t._type){case"named":return this.isNamedTypeComplex({type:t,file:r,visited:i});case"primitive":case"unknown":return!1;case"container":return this.isComplexContainer({type:t.container,file:r,visited:i});default:Mo(t)}}isComplexContainer({type:t,file:r,visited:i}){switch(t._type){case"literal":return!1;case"map":return this.isComplex({type:t.keyType,file:r,visited:i})||this.isComplex({type:t.valueType,file:r,visited:i});case"optional":case"nullable":case"list":case"set":return this.isComplex({type:t.itemType,file:r,visited:i});default:Mo(t)}}};var bac={name:"no-complex-query-params",create:({workspace:e})=>{let t=new t4o(e);return{definitionFile:{queryParameter:({queryParameter:r},i)=>{let n=typeof r=="string"?r:r.type,a=t.isTypeComplex(n,i);return a!=null&&a?[{severity:"fatal",message:`${n} is not a valid type for a query parameter`}]:[]}}}}};var gac={name:"no-conflicting-endpoint-parameters",create:()=>({definitionFile:{pathParameter:({pathParameterKey:e})=>e===g7o?[{severity:"fatal",message:`Path parameter ${Ws.bold(e)} is not suitable for code generation, because it can conflict with the request body parameter.`}]:[]}})};function Ega({service:e,endpoint:t}){return e["base-path"]+t.path}var r4o=class{root=new Oac;registerEndpoint(t){this.root.insert(this.getPathPartsForEndpoint(t),t)}getConflictingEndpoints(t){return this.root.getMatchingEndpoints(this.getPathPartsForEndpoint(t)).filter(r=>!(r.relativeFilepath===t.relativeFilepath&&r.endpointId===t.endpointId)&&r.endpoint.method===t.endpoint.method)}getPathPartsForEndpoint(t){return Ega({service:t.service,endpoint:t.endpoint}).split("/").filter(r=>r.length>0)}},Oac=class e{childPaths={};childPathParam;endpointsThatEndWithThisNode=[];insert(t,r){let[i,...n]=t;if(i==null){this.endpointsThatEndWithThisNode.push(r);return}(this.isPathParam(i)?this.childPathParam??=new e:this.childPaths[i]??=new e).insert(n,r)}getMatchingEndpoints(t){let[r,...i]=t;if(r==null)return this.endpointsThatEndWithThisNode;let n=[];if(this.isPathParam(r))n.push(...Object.values(this.childPaths).flatMap(a=>a.getMatchingEndpoints(i)));else{let a=this.childPaths[r];a!=null&&n.push(...a.getMatchingEndpoints(i))}return this.childPathParam!=null&&n.push(...this.childPathParam.getMatchingEndpoints(i)),n}isPathParam(t){return t.startsWith("{")&&t.endsWith("}")}};var mac={name:"no-conflicting-endpoint-paths",create:({workspace:e})=>{let t=new r4o;return AF(e,(r,i)=>{ZV(i,{httpEndpoint:({service:n,endpointId:a,endpoint:u})=>{t.registerEndpoint({service:n,endpointId:a,endpoint:u,relativeFilepath:r})}})}),{definitionFile:{httpEndpoint:({service:r,endpoint:i,endpointId:n},{relativeFilepath:a})=>{let u=t.getConflictingEndpoints({service:r,endpointId:n,endpoint:i,relativeFilepath:a});return u.length===0?[]:[{severity:"warning",message:[`Endpoint path ${Ega({service:r,endpoint:i})} conflicts with other endpoints:`,...u.map(l=>` - ${l.relativeFilepath} -> ${l.endpointId} ${Ws.dim(Ega({service:l.service,endpoint:l.endpoint}))}`)].join(`
|
|
2032
2032
|
`)}]}}}}};var Pac={name:"no-conflicting-request-wrapper-properties",create:({workspace:e})=>({definitionFile:{httpEndpoint:({endpoint:t,service:r},{contents:i,relativeFilepath:n})=>{let a=$cE({endpoint:t,service:r,relativeFilepath:n,definitionFile:i,workspace:e}),u=[];for(let[l,f]of Object.entries(a))f.length<=1||u.push({severity:"fatal",message:`Multiple request properties have the name ${Ws.bold(l)}. This is not suitable for code generation. Use the "name" property to deconflict.
|
|
2033
2033
|
`+f.map(s=>` - ${GcE(s)}`).join(`
|
|
2034
2034
|
`)});return u}}})};function $cE({endpoint:e,service:t,relativeFilepath:r,definitionFile:i,workspace:n}){let a={},u=(l,f)=>{(a[l]??=[]).push(f)};if(e.request!=null&&typeof e.request!="string"&&e.request.body!=null&&!oC(e.request.body)&&O7o({request:e.request,file:r0({relativeFilepath:r,definitionFile:i,casingsGenerator:_S,rootApiFile:n.definition.rootApiFile.contents}),typeResolver:new h1(n)})&&u(R0a,{type:"referenced-body",propertyName:R0a}),t.headers!=null)for(let[l,f]of Object.entries(t.headers))u(LZt({headerKey:l,header:f}).name,{type:"service-header",headerKey:l,header:f});if(e.request!=null&&typeof e.request!="string"){if(e.request.headers!=null)for(let[l,f]of Object.entries(e.request.headers))u(LZt({headerKey:l,header:f}).name,{type:"endpoint-header",headerKey:l,header:f});if(e.request["query-parameters"]!=null)for(let[l,f]of Object.entries(e.request["query-parameters"]))u(FYr({queryParameterKey:l,queryParameter:f}).name,{type:"endpoint-query-parameter",queryParameterKey:l,queryParameter:f});if(e.request.body!=null&&oC(e.request.body)){let l=x9t({typeName:void 0,objectDeclaration:{extends:e.request.body.extends,properties:e.request.body.properties??{}},filepathOfDeclaration:r,definitionFile:i,workspace:n,typeResolver:new h1(n),smartCasing:!1});for(let f of l)u(f.name,{type:"inlined-body",property:f})}}return a}function GcE(e){switch(e.type){case"service-header":return`Service header "${e.headerKey}"`;case"endpoint-header":return`Endpoint header "${e.headerKey}"`;case"endpoint-query-parameter":return`Query Parameter "${e.queryParameterKey}"`;case"inlined-body":return`Body property: ${RMn({property:e.property,prefixBreadcrumbs:["<Request Body>"]})}`;case"referenced-body":return`Body property "${e.propertyName}"`;default:Mo(e)}}var jac=li(require("path"),1);var wac={name:"no-duplicate-declarations",create:({workspace:e,logger:t})=>{let r=QcE(e),i={},n=({declaredName:a,relativeFilepath:u})=>{let l=jac.default.dirname(u),f=r[l]?.[a];if(f==null)return t.error(`Could not find declarations for name: ${a}. This is an error in the Fern validator.`),[];let s=i[l]??=new Set;if(!s.has(a))return s.add(a),[];let o=f.indexOf(u);return f.filter((b,g)=>g!==o).map(b=>({severity:"fatal",message:`${a} is already declared in ${b===u?"this file":b}`}))};return{definitionFile:{typeName:(a,{relativeFilepath:u})=>n({declaredName:a,relativeFilepath:u}),errorDeclaration:({errorName:a},{relativeFilepath:u})=>n({declaredName:a,relativeFilepath:u}),httpEndpoint:({endpoint:a},{relativeFilepath:u})=>typeof a.request!="string"&&a.request?.name!=null?n({declaredName:a.request.name,relativeFilepath:u}):[]}}}};function QcE(e){let t={};return AF(e,(r,i)=>{let n=jac.default.dirname(r),a=t[n]??={},u=l=>{(a[l]??=[]).push(r)};ZV(i,{typeName:l=>{u(l)},errorDeclaration:({errorName:l})=>{u(l)},httpEndpoint:({endpoint:l})=>{typeof l.request!="string"&&l.request?.name!=null&&u(l.request.name)}})}),t}function Mga(e){let t=new Set,r=new Set,i=[];for(let n of e)t.has(n)&&!r.has(n)&&(r.add(n),i.push(n)),t.add(n);return i}var Sac={name:"no-duplicate-enum-values",create:()=>({definitionFile:{typeDeclaration:({declaration:e})=>$8t(e)?Mga(e.enum.map(r=>typeof r=="string"?r:r.value)).map(r=>({severity:"fatal",message:`Duplicated enum value: ${Ws.bold(r)}.`})):[]}})};var Dac={name:"no-duplicate-example-names",create:()=>({definitionFile:{typeDeclaration:({declaration:e})=>{if(typeof e=="string"||e.examples==null)return[];let t=e.examples.map(r=>r.name).filter(g0);return Mga(t).map(r=>({severity:"fatal",message:`Duplicate example name: ${r}`}))},httpEndpoint:({endpoint:e})=>{if(e.examples==null)return[];let t=e.examples.map(r=>r.name).filter(g0);return Mga(t).map(r=>({severity:"fatal",message:`Duplicate example name: ${r}`}))}}})};function Db_(e){if(!e.isInlined)return e.name;switch(e.location){case"inlinedRequest":return"<Inlined Request>";default:Mo(e.location)}}var Eac={name:"no-duplicate-field-names",create:({workspace:e})=>{let t=new h1(e);return{definitionFile:{typeDeclaration:({typeName:r,declaration:i},{relativeFilepath:n,contents:a})=>{let u=[];return dF(i,{alias:kBe,enum:l=>{let f=Eb_(l.enum,s=>UMn(s).name);for(let s of f)u.push({severity:"fatal",message:`Name "${s}" is used by multiple values.`})},object:l=>{let f=Db_(r),s=x9t({typeName:f,objectDeclaration:l,filepathOfDeclaration:n,definitionFile:a,workspace:e,typeResolver:t,smartCasing:!1}),o=a_s(s,c=>c.name);for(let[c,b]of Object.entries(o))if(b.length>1){let g=[`Object has multiple properties named "${c}":`,...b.map(O=>` - ${RMn({property:O,prefixBreadcrumbs:[f]})}`)].join(`
|